function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
sequence
def testDataEmpty(self): output_dir = test.get_temp_dir() run_metadata = config_pb2.RunMetadata() graph = test.mock.MagicMock() graph.get_operations.return_value = [] profiles = pprof_profiler.get_profiles(graph, run_metadata) self.assertEqual(0, len(profiles)) profile_files = pprof_profiler.profile( graph, run_metadata, output_dir) self.assertEqual(0, len(profile_files))
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def testValidProfile(self): output_dir = test.get_temp_dir() run_metadata = config_pb2.RunMetadata() node1 = step_stats_pb2.NodeExecStats( node_name='Add/123', op_start_rel_micros=3, op_end_rel_micros=5, all_end_rel_micros=4) run_metadata = config_pb2.RunMetadata() device1 = run_metadata.step_stats.dev_stats.add() device1.device = 'deviceA' device1.node_stats.extend([node1]) graph = test.mock.MagicMock() op1 = test.mock.MagicMock() op1.name = 'Add/123' op1.traceback = [ ('a/b/file1', 10, 'apply_op', 'abc'), ('a/c/file2', 12, 'my_op', 'def')] op1.type = 'add' graph.get_operations.return_value = [op1] expected_proto = """sample_type {
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def testProfileWithWhileLoop(self): options = config_pb2.RunOptions() options.trace_level = config_pb2.RunOptions.FULL_TRACE run_metadata = config_pb2.RunMetadata() num_iters = 5 with self.cached_session() as sess: i = constant_op.constant(0) c = lambda i: math_ops.less(i, num_iters) b = lambda i: math_ops.add(i, 1) r = control_flow_ops.while_loop(c, b, [i]) sess.run(r, options=options, run_metadata=run_metadata) profiles = pprof_profiler.get_profiles(sess.graph, run_metadata) self.assertEqual(1, len(profiles)) profile = next(iter(profiles.values())) add_samples = [] # Samples for the while/Add node for sample in profile.sample: if profile.string_table[sample.label[0].str] == 'while/Add': add_samples.append(sample) # Values for same nodes are aggregated. self.assertEqual(1, len(add_samples)) # Value of "count" should be equal to number of iterations. self.assertEqual(num_iters, add_samples[0].value[0])
tensorflow/tensorflow
[ 171949, 87931, 171949, 2300, 1446859160 ]
def fuzzy_compare(self, a, b, newlines_are_spaces=True, tabs_are_spaces=True, fuzzy_spacing=True, ignore_spaces=False, ignore_newlines=False, case_sensitive=False, leave_padding=False): """ Performs a fuzzy comparison of two strings. A fuzzy comparison is a comparison that ignores insignificant differences in the two comparands. The significance of certain differences can be specified via the keyword parameters of this method. """ if not leave_padding: a = a.strip() b = b.strip() if ignore_newlines: a = a.replace('\n', '') b = b.replace('\n', '') if newlines_are_spaces: a = a.replace('\n', ' ') b = b.replace('\n', ' ') if tabs_are_spaces: a = a.replace('\t', ' ') b = b.replace('\t', ' ') if ignore_spaces: a = a.replace(' ', '') b = b.replace(' ', '') if fuzzy_spacing: a = self.recursive_replace(a, ' ', ' ') b = self.recursive_replace(b, ' ', ' ') if not case_sensitive: a = a.lower() b = b.lower() self.assertEqual(a, b)
unnikrishnankgs/va
[ 1, 5, 1, 10, 1496432585 ]
def create_temp_cwd(self, copy_filenames=None): temp_dir = TemporaryWorkingDirectory() #Copy the files if requested. if copy_filenames is not None: self.copy_files_to(copy_filenames, dest=temp_dir.name) #Return directory handler return temp_dir
unnikrishnankgs/va
[ 1, 5, 1, 10, 1496432585 ]
def create_empty_notebook(self, path): nb = v4.new_notebook() with io.open(path, 'w', encoding='utf-8') as f: write(nb, f, 4)
unnikrishnankgs/va
[ 1, 5, 1, 10, 1496432585 ]
def _get_files_path(self): #Get the relative path to this module in the IPython directory. names = self.__module__.split('.')[1:-1] names.append('files')
unnikrishnankgs/va
[ 1, 5, 1, 10, 1496432585 ]
def nbconvert(self, parameters, ignore_return_code=False, stdin=None): """ Run nbconvert as a shell command, listening for both Errors and non-zero return codes. Returns the tuple (stdout, stderr) of output produced during the nbconvert run. Parameters ---------- parameters : str, list(str) List of parameters to pass to IPython. ignore_return_code : optional bool (default False) Throw an OSError if the return code """ if isinstance(parameters, string_types): parameters = shlex.split(parameters) cmd = [sys.executable, '-m', 'nbconvert'] + parameters p = Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE) stdout, stderr = p.communicate(input=stdin) if not (p.returncode == 0 or ignore_return_code): raise OSError(bytes_to_str(stderr)) return stdout.decode('utf8', 'replace'), stderr.decode('utf8', 'replace')
unnikrishnankgs/va
[ 1, 5, 1, 10, 1496432585 ]
def _system_path(path_insertion): old_system_path = sys.path[:] sys.path = sys.path[0:1] + path_insertion + sys.path[1:] yield sys.path = old_system_path
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def _massage_proto_content(raw_proto_content): imports_substituted = raw_proto_content.replace( b'import "tests/protoc_plugin/protos/', b'import "beta_grpc_plugin_test/') package_statement_substituted = imports_substituted.replace( b'package grpc_protoc_plugin;', b'package beta_grpc_protoc_plugin;') return package_statement_substituted
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def __init__(self, payload_pb2, responses_pb2): self._condition = threading.Condition() self._paused = False self._fail = False self._payload_pb2 = payload_pb2 self._responses_pb2 = responses_pb2
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def pause(self): # pylint: disable=invalid-name with self._condition: self._paused = True yield with self._condition: self._paused = False self._condition.notify_all()
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def fail(self): # pylint: disable=invalid-name with self._condition: self._fail = True yield with self._condition: self._fail = False
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def UnaryCall(self, request, unused_rpc_context): response = self._responses_pb2.SimpleResponse() response.payload.payload_type = self._payload_pb2.COMPRESSABLE response.payload.payload_compressable = 'a' * request.response_size self._control() return response
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def StreamingInputCall(self, request_iter, unused_rpc_context): response = self._responses_pb2.StreamingInputCallResponse() aggregated_payload_size = 0 for request in request_iter: aggregated_payload_size += len(request.payload.payload_compressable) response.aggregated_payload_size = aggregated_payload_size self._control() return response
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def HalfDuplexCall(self, request_iter, unused_rpc_context): responses = [] for request in request_iter: for parameter in request.response_parameters: response = self._responses_pb2.StreamingOutputCallResponse() response.payload.payload_type = self._payload_pb2.COMPRESSABLE response.payload.payload_compressable = 'a' * parameter.size self._control() responses.append(response) for response in responses: yield response
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def _CreateService(payload_pb2, responses_pb2, service_pb2): """Provides a servicer backend and a stub. The servicer is just the implementation of the actual servicer passed to the face player of the python RPC implementation; the two are detached. Yields: A (servicer_methods, stub) pair where servicer_methods is the back-end of the service bound to the stub and stub is the stub on which to invoke RPCs. """ servicer_methods = _ServicerMethods(payload_pb2, responses_pb2) class Servicer(getattr(service_pb2, SERVICER_IDENTIFIER)): def UnaryCall(self, request, context): return servicer_methods.UnaryCall(request, context) def StreamingOutputCall(self, request, context): return servicer_methods.StreamingOutputCall(request, context) def StreamingInputCall(self, request_iter, context): return servicer_methods.StreamingInputCall(request_iter, context) def FullDuplexCall(self, request_iter, context): return servicer_methods.FullDuplexCall(request_iter, context) def HalfDuplexCall(self, request_iter, context): return servicer_methods.HalfDuplexCall(request_iter, context) servicer = Servicer() server = getattr(service_pb2, SERVER_FACTORY_IDENTIFIER)(servicer) port = server.add_insecure_port('[::]:0') server.start() channel = implementations.insecure_channel('localhost', port) stub = getattr(service_pb2, STUB_FACTORY_IDENTIFIER)(channel) yield servicer_methods, stub server.stop(0)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def _CreateIncompleteService(service_pb2): """Provides a servicer backend that fails to implement methods and its stub. The servicer is just the implementation of the actual servicer passed to the face player of the python RPC implementation; the two are detached. Args: service_pb2: The service_pb2 module generated by this test. Yields: A (servicer_methods, stub) pair where servicer_methods is the back-end of the service bound to the stub and stub is the stub on which to invoke RPCs. """ class Servicer(getattr(service_pb2, SERVICER_IDENTIFIER)): pass servicer = Servicer() server = getattr(service_pb2, SERVER_FACTORY_IDENTIFIER)(servicer) port = server.add_insecure_port('[::]:0') server.start() channel = implementations.insecure_channel('localhost', port) stub = getattr(service_pb2, STUB_FACTORY_IDENTIFIER)(channel) yield None, stub server.stop(0)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def _streaming_output_request(requests_pb2): request = requests_pb2.StreamingOutputCallRequest() sizes = [1, 2, 3] request.response_parameters.add(size=sizes[0], interval_us=0) request.response_parameters.add(size=sizes[1], interval_us=0) request.response_parameters.add(size=sizes[2], interval_us=0) return request
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def setUp(self): self._directory = tempfile.mkdtemp(dir='.') self._proto_path = path.join(self._directory, _RELATIVE_PROTO_PATH) self._python_out = path.join(self._directory, _RELATIVE_PYTHON_OUT) os.makedirs(self._proto_path) os.makedirs(self._python_out) directories_path_components = { proto_file_path_components[:-1] for proto_file_path_components in _PROTO_FILES_PATH_COMPONENTS } _create_directory_tree(self._proto_path, directories_path_components) self._proto_file_names = set() for proto_file_path_components in _PROTO_FILES_PATH_COMPONENTS: raw_proto_content = pkgutil.get_data( 'tests.protoc_plugin.protos', path.join(*proto_file_path_components[1:])) massaged_proto_content = _massage_proto_content(raw_proto_content) proto_file_name = path.join(self._proto_path, *proto_file_path_components) with open(proto_file_name, 'wb') as proto_file: proto_file.write(massaged_proto_content) self._proto_file_names.add(proto_file_name)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def _protoc(self): args = [ '', '--proto_path={}'.format(self._proto_path), '--python_out={}'.format(self._python_out), '--grpc_python_out=grpc_1_0:{}'.format(self._python_out), ] + list(self._proto_file_names) protoc_exit_code = protoc.main(args) self.assertEqual(0, protoc_exit_code) _packagify(self._python_out) with _system_path([self._python_out]): self._payload_pb2 = importlib.import_module(_PAYLOAD_PB2) self._requests_pb2 = importlib.import_module(_REQUESTS_PB2) self._responses_pb2 = importlib.import_module(_RESPONSES_PB2) self._service_pb2 = importlib.import_module(_SERVICE_PB2)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testUpDown(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2): self._requests_pb2.SimpleRequest(response_size=13)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testUnaryCall(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): request = self._requests_pb2.SimpleRequest(response_size=13) response = stub.UnaryCall(request, test_constants.LONG_TIMEOUT) expected_response = methods.UnaryCall(request, 'not a real context!') self.assertEqual(expected_response, response)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testUnaryCallFutureExpired(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): request = self._requests_pb2.SimpleRequest(response_size=13) with methods.pause(): response_future = stub.UnaryCall.future( request, test_constants.SHORT_TIMEOUT) with self.assertRaises(face.ExpirationError): response_future.result()
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testUnaryCallFutureFailed(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): request = self._requests_pb2.SimpleRequest(response_size=13) with methods.fail(): response_future = stub.UnaryCall.future( request, test_constants.LONG_TIMEOUT) self.assertIsNotNone(response_future.exception())
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testStreamingOutputCallExpired(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): request = _streaming_output_request(self._requests_pb2) with methods.pause(): responses = stub.StreamingOutputCall( request, test_constants.SHORT_TIMEOUT) with self.assertRaises(face.ExpirationError): list(responses)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testStreamingOutputCallFailed(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): request = _streaming_output_request(self._requests_pb2) with methods.fail(): responses = stub.StreamingOutputCall(request, 1) self.assertIsNotNone(responses) with self.assertRaises(face.RemoteError): next(responses)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testStreamingInputCallFuture(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): with methods.pause(): response_future = stub.StreamingInputCall.future( _streaming_input_request_iterator(self._payload_pb2, self._requests_pb2), test_constants.LONG_TIMEOUT) response = response_future.result() expected_response = methods.StreamingInputCall( _streaming_input_request_iterator(self._payload_pb2, self._requests_pb2), 'not a real RpcContext!') self.assertEqual(expected_response, response)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testStreamingInputCallFutureCancelled(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): with methods.pause(): response_future = stub.StreamingInputCall.future( _streaming_input_request_iterator(self._payload_pb2, self._requests_pb2), test_constants.LONG_TIMEOUT) response_future.cancel() self.assertTrue(response_future.cancelled()) with self.assertRaises(future.CancelledError): response_future.result()
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testFullDuplexCall(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): responses = stub.FullDuplexCall( _full_duplex_request_iterator(self._requests_pb2), test_constants.LONG_TIMEOUT) expected_responses = methods.FullDuplexCall( _full_duplex_request_iterator(self._requests_pb2), 'not a real RpcContext!') for expected_response, response in moves.zip_longest( expected_responses, responses): self.assertEqual(expected_response, response)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testFullDuplexCallCancelled(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): request_iterator = _full_duplex_request_iterator(self._requests_pb2) responses = stub.FullDuplexCall(request_iterator, test_constants.LONG_TIMEOUT) next(responses) responses.cancel() with self.assertRaises(face.CancellationError): next(responses)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def testHalfDuplexCall(self): self._protoc() with _CreateService(self._payload_pb2, self._responses_pb2, self._service_pb2) as (methods, stub): def half_duplex_request_iterator(): request = self._requests_pb2.StreamingOutputCallRequest() request.response_parameters.add(size=1, interval_us=0) yield request request = self._requests_pb2.StreamingOutputCallRequest() request.response_parameters.add(size=2, interval_us=0) request.response_parameters.add(size=3, interval_us=0) yield request responses = stub.HalfDuplexCall(half_duplex_request_iterator(), test_constants.LONG_TIMEOUT) expected_responses = methods.HalfDuplexCall( half_duplex_request_iterator(), 'not a real RpcContext!') for check in moves.zip_longest(expected_responses, responses): expected_response, response = check self.assertEqual(expected_response, response)
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def wait(): # pylint: disable=invalid-name # Where's Python 3's 'nonlocal' statement when you need it? with condition: wait_cell[0] = True yield with condition: wait_cell[0] = False condition.notify_all()
endlessm/chromium-browser
[ 21, 16, 21, 3, 1435959644 ]
def wraps(original): def inner(f): f.__name__ = original.__name__ f.__doc__ = original.__doc__ f.__module__ = original.__module__ return f return inner
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def next(obj): return obj.next()
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _isidentifier(string): if string in keyword.kwlist: return False return regex.match(string)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _is_instance_mock(obj): # can't use isinstance on Mock objects because they override __class__ # The base class for all mocks is NonCallableMock return issubclass(type(obj), NonCallableMock)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _getsignature(func, skipfirst): if inspect is None: raise ImportError('inspect module not available') if inspect.isclass(func): func = func.__init__ # will have a self arg skipfirst = True elif not (inspect.ismethod(func) or inspect.isfunction(func)): func = func.__call__ regargs, varargs, varkwargs, defaults = inspect.getargspec(func) # instance methods need to lose the self argument if getattr(func, self, None) is not None: regargs = regargs[1:] _msg = ("_mock_ is a reserved argument name, can't mock signatures using " "_mock_") assert '_mock_' not in regargs, _msg if varargs is not None: assert '_mock_' not in varargs, _msg if varkwargs is not None: assert '_mock_' not in varkwargs, _msg if skipfirst: regargs = regargs[1:] signature = inspect.formatargspec(regargs, varargs, varkwargs, defaults, formatvalue=lambda value: "") return signature[1:-1], func
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _check_signature(func, mock, skipfirst, instance=False): if not _callable(func): return result = _getsignature2(func, skipfirst, instance) if result is None: return signature, func = result # can't use self because "self" is common as an argument name # unfortunately even not in the first place src = "lambda _mock_self, %s: None" % signature checksig = eval(src, {}) _copy_func_details(func, checksig) type(mock)._mock_check_sig = checksig
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _callable(obj): if isinstance(obj, ClassTypes): return True if getattr(obj, '__call__', None) is not None: return True return False
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _instance_callable(obj): """Given an object, return True if the object is callable. For classes, return True if instances would be callable.""" if not isinstance(obj, ClassTypes): # already an instance return getattr(obj, '__call__', None) is not None klass = obj # uses __bases__ instead of __mro__ so that we work with old style classes if klass.__dict__.get('__call__') is not None: return True for base in klass.__bases__: if _instance_callable(base): return True return False
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def mocksignature(func, mock=None, skipfirst=False): """ mocksignature(func, mock=None, skipfirst=False) Create a new function with the same signature as `func` that delegates to `mock`. If `skipfirst` is True the first argument is skipped, useful for methods where `self` needs to be omitted from the new function. If you don't pass in a `mock` then one will be created for you. The mock is set as the `mock` attribute of the returned function for easy access. Functions returned by `mocksignature` have many of the same attributes and assert methods as a mock object. `mocksignature` can also be used with classes. It copies the signature of the `__init__` method. When used with callable objects (instances) it copies the signature of the `__call__` method. """ if mock is None: mock = Mock() signature, func = _getsignature(func, skipfirst) src = "lambda %(signature)s: _mock_(%(signature)s)" % { 'signature': signature } funcopy = eval(src, dict(_mock_=mock)) _copy_func_details(func, funcopy) _setup_func(funcopy, mock) return funcopy
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def assert_called_with(*args, **kwargs): return mock.assert_called_with(*args, **kwargs)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def assert_has_calls(*args, **kwargs): return mock.assert_has_calls(*args, **kwargs)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def reset_mock(): funcopy.method_calls = _CallList() funcopy.mock_calls = _CallList() mock.reset_mock() ret = funcopy.return_value if _is_instance_mock(ret) and not ret is mock: ret.reset_mock()
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _is_magic(name): return '__%s__' % name[2:-2] == name
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, name): self.name = name
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self): self._sentinels = {}
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _copy(value): if type(value) in (dict, list, tuple, set): return type(value)(value) return value
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _mock_signature_property(name): _allowed_names.add(name) _the_name = '_mock_' + name def _get(self, name=name, _the_name=_the_name): sig = self._mock_signature if sig is None: return getattr(self, _the_name) return getattr(sig, name) def _set(self, value, name=name, _the_name=_the_name): sig = self._mock_signature if sig is None: self.__dict__[_the_name] = value else: setattr(sig, name, value) return property(_get, _set)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __contains__(self, value): if not isinstance(value, list): return list.__contains__(self, value) len_value = len(value) len_self = len(self) if len_value > len_self: return False for i in range(0, len_self - len_value + 1): sub_list = self[i:i+len_value] if sub_list == value: return True return False
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _check_and_set_parent(parent, value, name, new_name): if not _is_instance_mock(value): return False if ((value._mock_name or value._mock_new_name) or (value._mock_parent is not None) or (value._mock_new_parent is not None)): return False _parent = parent while _parent is not None: # setting a mock (value) as a child or return value of itself # should not modify the mock if _parent is value: return False _parent = _parent._mock_new_parent if new_name: value._mock_new_parent = parent value._mock_new_name = new_name if name: value._mock_parent = parent value._mock_name = name return True
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, *args, **kwargs): pass
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __new__(cls, *args, **kw): # every instance has its own class # so we can create magic methods on the # class without stomping on other mocks new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__}) instance = object.__new__(new) return instance
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def attach_mock(self, mock, attribute): """ Attach a mock as an attribute of this one, replacing its name and parent. Calls to the attached mock will be recorded in the `method_calls` and `mock_calls` attributes of this one.""" mock._mock_parent = None mock._mock_new_parent = None mock._mock_name = '' mock._mock_new_name = None setattr(self, attribute, mock)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _mock_add_spec(self, spec, spec_set): _spec_class = None if spec is not None and not _is_list(spec): if isinstance(spec, ClassTypes): _spec_class = spec else: _spec_class = _get_class(spec) spec = dir(spec) __dict__ = self.__dict__ __dict__['_spec_class'] = _spec_class __dict__['_spec_set'] = spec_set __dict__['_mock_methods'] = spec
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __set_return_value(self, value): if self._mock_signature is not None: self._mock_signature.return_value = value else: self._mock_return_value = value _check_and_set_parent(self, value, None, '()')
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __class__(self): if self._spec_class is None: return type(self) return self._spec_class
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __get_side_effect(self): sig = self._mock_signature if sig is None: return self._mock_side_effect return sig.side_effect
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def reset_mock(self): "Restore the mock object to its initial state." self.called = False self.call_args = None self.call_count = 0 self.mock_calls = _CallList() self.call_args_list = _CallList() self.method_calls = _CallList() for child in self._mock_children.values(): child.reset_mock() ret = self._mock_return_value if _is_instance_mock(ret) and ret is not self: ret.reset_mock()
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __getattr__(self, name): if name == '_mock_methods': raise AttributeError(name) elif self._mock_methods is not None: if name not in self._mock_methods or name in _all_magics: raise AttributeError("Mock object has no attribute %r" % name) elif _is_magic(name): raise AttributeError(name) result = self._mock_children.get(name) if result is None: wraps = None if self._mock_wraps is not None: # XXXX should we get the attribute without triggering code # execution? wraps = getattr(self._mock_wraps, name) result = self._get_child_mock( parent=self, name=name, wraps=wraps, _new_name=name, _new_parent=self ) self._mock_children[name] = result elif isinstance(result, _SpecState): result = create_autospec( result.spec, result.spec_set, result.instance, result.parent, result.name ) self._mock_children[name] = result return result
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __dir__(self): """Filter the output of `dir(mock)` to only useful members. XXXX """ extras = self._mock_methods or [] from_type = dir(type(self)) from_dict = list(self.__dict__) if FILTER_DIR: from_type = [e for e in from_type if not e.startswith('_')] from_dict = [e for e in from_dict if not e.startswith('_') or _is_magic(e)] return sorted(set(extras + from_type + from_dict + list(self._mock_children)))
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __delattr__(self, name): if name in _all_magics and name in type(self).__dict__: delattr(type(self), name) if name not in self.__dict__: # for magic methods that are still MagicProxy objects and # not set on the instance itself return return object.__delattr__(self, name)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _format_mock_failure_message(self, args, kwargs): message = 'Expected call: %s\nActual call: %s' expected_string = self._format_mock_call_signature(args, kwargs) call_args = self.call_args if len(call_args) == 3: call_args = call_args[1:] actual_string = self._format_mock_call_signature(*call_args) return message % (expected_string, actual_string)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def assert_called_once_with(_mock_self, *args, **kwargs): """assert that the mock was called exactly once and with the specified arguments.""" self = _mock_self if not self.call_count == 1: msg = ("Expected to be called once. Called %s times." % self.call_count) raise AssertionError(msg) return self.assert_called_with(*args, **kwargs)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def assert_any_call(self, *args, **kwargs): """assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if the call is the most recent one.""" kall = call(*args, **kwargs) if kall not in self.call_args_list: expected_string = self._format_mock_call_signature(args, kwargs) raise AssertionError( '%s call not found' % expected_string )
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _try_iter(obj): if obj is None: return obj if _is_exception(obj): return obj if _callable(obj): return obj try: return iter(obj) except TypeError: # XXXX backwards compatibility # but this will blow up on first call - so maybe we should fail early? return obj
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, spec=None, side_effect=None, return_value=DEFAULT, wraps=None, name=None, spec_set=None, parent=None, _spec_state=None, _new_name='', _new_parent=None, **kwargs): self.__dict__['_mock_return_value'] = return_value _super(CallableMixin, self).__init__( spec, wraps, name, spec_set, parent, _spec_state, _new_name, _new_parent, **kwargs ) self.side_effect = side_effect
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __call__(_mock_self, *args, **kwargs): # can't use self in-case a function / method we are mocking uses self # in the signature _mock_self._mock_check_sig(*args, **kwargs) return _mock_self._mock_call(*args, **kwargs)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _dot_lookup(thing, comp, import_path): try: return getattr(thing, comp) except AttributeError: __import__(import_path) return getattr(thing, comp)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _is_started(patcher): # XXXX horrible return hasattr(patcher, 'is_local')
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__( self, getter, attribute, new, spec, create, mocksignature, spec_set, autospec, new_callable, kwargs ): if new_callable is not None: if new is not DEFAULT: raise ValueError( "Cannot use 'new' and 'new_callable' together" ) if autospec is not False: raise ValueError( "Cannot use 'autospec' and 'new_callable' together" ) self.getter = getter self.attribute = attribute self.new = new self.new_callable = new_callable self.spec = spec self.create = create self.has_local = False self.mocksignature = mocksignature self.spec_set = spec_set self.autospec = autospec self.kwargs = kwargs self.additional_patchers = []
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __call__(self, func): if isinstance(func, ClassTypes): return self.decorate_class(func) return self.decorate_callable(func)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def decorate_callable(self, func): if hasattr(func, 'patchings'): func.patchings.append(self) return func @wraps(func) def patched(*args, **keywargs): # don't use a with here (backwards compatability with Python 2.4) extra_args = [] entered_patchers = [] # can't use try...except...finally because of Python 2.4 # compatibility try: try: for patching in patched.patchings: arg = patching.__enter__() entered_patchers.append(patching) if patching.attribute_name is not None: keywargs.update(arg) elif patching.new is DEFAULT: extra_args.append(arg) args += tuple(extra_args) return func(*args, **keywargs) except: if (patching not in entered_patchers and _is_started(patching)): # the patcher may have been started, but an exception # raised whilst entering one of its additional_patchers entered_patchers.append(patching) # re-raise the exception raise finally: for patching in reversed(entered_patchers): patching.__exit__() patched.patchings = [self] if hasattr(func, 'func_code'): # not in Python 3 patched.compat_co_firstlineno = getattr( func, "compat_co_firstlineno", func.func_code.co_firstlineno ) return patched
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __enter__(self): """Perform the patch.""" new, spec, spec_set = self.new, self.spec, self.spec_set autospec, kwargs = self.autospec, self.kwargs new_callable = self.new_callable self.target = self.getter() original, local = self.get_original() if new is DEFAULT and autospec is False: inherit = False if spec_set == True: spec_set = original elif spec == True: # set spec to the object we are replacing spec = original if (spec or spec_set) is not None: if isinstance(original, ClassTypes): # If we're patching out a class and there is a spec inherit = True Klass = MagicMock _kwargs = {} if new_callable is not None: Klass = new_callable elif (spec or spec_set) is not None: if not _callable(spec or spec_set): Klass = NonCallableMagicMock if spec is not None: _kwargs['spec'] = spec if spec_set is not None: _kwargs['spec_set'] = spec_set # add a name to mocks if (isinstance(Klass, type) and issubclass(Klass, NonCallableMock) and self.attribute): _kwargs['name'] = self.attribute _kwargs.update(kwargs) new = Klass(**_kwargs) if inherit and _is_instance_mock(new): # we can only tell if the instance should be callable if the # spec is not a list if (not _is_list(spec or spec_set) and not _instance_callable(spec or spec_set)): Klass = NonCallableMagicMock _kwargs.pop('name') new.return_value = Klass(_new_parent=new, _new_name='()', **_kwargs) elif autospec is not False: # spec is ignored, new *must* be default, spec_set is treated # as a boolean. Should we check spec is not None and that spec_set # is a bool? mocksignature should also not be used. Should we # check this? if new is not DEFAULT: raise TypeError( "autospec creates the mock for you. Can't specify " "autospec and new." ) spec_set = bool(spec_set) if autospec is True: autospec = original new = create_autospec(autospec, spec_set=spec_set, _name=self.attribute, **kwargs) elif kwargs: # can't set keyword args when we aren't creating the mock # XXXX If new is a Mock we could call new.configure_mock(**kwargs) raise TypeError("Can't pass kwargs to a mock we aren't creating") new_attr = new if self.mocksignature: new_attr = mocksignature(original, new) self.temp_original = original self.is_local = local setattr(self.target, self.attribute, new_attr) if self.attribute_name is not None: extra_args = {} if self.new is DEFAULT: extra_args[self.attribute_name] = new for patching in self.additional_patchers: arg = patching.__enter__() if patching.new is DEFAULT: extra_args.update(arg) return extra_args return new
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _get_target(target): try: target, attribute = target.rsplit('.', 1) except (TypeError, ValueError): raise TypeError("Need a valid target to patch. You supplied: %r" % (target,)) getter = lambda: _importer(target) return getter, attribute
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _patch_multiple(target, spec=None, create=False, mocksignature=False, spec_set=None, autospec=False, new_callable=None, **kwargs ): """Perform multiple patches in a single call. It takes the object to be patched (either as an object or a string to fetch the object by importing) and keyword arguments for the patches:: with patch.multiple(settings, FIRST_PATCH='one', SECOND_PATCH='two'): ... Use `DEFAULT` as the value if you want `patch.multiple` to create mocks for you. In this case the created mocks are passed into a decorated function by keyword, and a dictionary is returned when `patch.multiple` is used as a context manager. `patch.multiple` can be used as a decorator, class decorator or a context manager. The arguments `spec`, `spec_set`, `create`, `mocksignature`, `autospec` and `new_callable` have the same meaning as for `patch`. These arguments will be applied to *all* patches done by `patch.multiple`. When used as a class decorator `patch.multiple` honours `patch.TEST_PREFIX` for choosing which methods to wrap. """ if type(target) in (unicode, str): getter = lambda: _importer(target) else: getter = lambda: target if not kwargs: raise ValueError( 'Must supply at least one keyword argument with patch.multiple' ) # need to wrap in a list for python 3, where items is a view items = list(kwargs.items()) attribute, new = items[0] patcher = _patch( getter, attribute, new, spec, create, mocksignature, spec_set, autospec, new_callable, {} ) patcher.attribute_name = attribute for attribute, new in items[1:]: this_patcher = _patch( getter, attribute, new, spec, create, mocksignature, spec_set, autospec, new_callable, {} ) this_patcher.attribute_name = attribute patcher.additional_patchers.append(this_patcher) return patcher
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, in_dict, values=(), clear=False, **kwargs): if isinstance(in_dict, basestring): in_dict = _importer(in_dict) self.in_dict = in_dict # support any argument supported by dict(...) constructor self.values = dict(values) self.values.update(kwargs) self.clear = clear self._original = None
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _inner(*args, **kw): self._patch_dict() try: return f(*args, **kw) finally: self._unpatch_dict()
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def decorate_class(self, klass): for attr in dir(klass): attr_value = getattr(klass, attr) if (attr.startswith(patch.TEST_PREFIX) and hasattr(attr_value, "__call__")): decorator = _patch_dict(self.in_dict, self.values, self.clear) decorated = decorator(attr_value) setattr(klass, attr, decorated) return klass
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _patch_dict(self): values = self.values in_dict = self.in_dict clear = self.clear try: original = in_dict.copy() except AttributeError: # dict like object with no copy method # must support iteration over keys original = {} for key in in_dict: original[key] = in_dict[key] self._original = original if clear: _clear_dict(in_dict) try: in_dict.update(values) except AttributeError: # dict like object with no update method for key in values: in_dict[key] = values[key]
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __exit__(self, *args): """Unpatch the dict.""" self._unpatch_dict() return False
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _clear_dict(in_dict): try: in_dict.clear() except AttributeError: keys = list(in_dict) for key in keys: del in_dict[key]
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _get_method(name, func): "Turns a callable object (like a mock) into a real function" def method(self, *args, **kw): return func(self, *args, **kw) method.__name__ = name return method
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _get_eq(self): def __eq__(other): ret_val = self.__eq__._mock_return_value if ret_val is not DEFAULT: return ret_val return self is other return __eq__
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __ne__(other): if self.__ne__._mock_return_value is not DEFAULT: return DEFAULT return self is not other
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _get_iter(self): def __iter__(): ret_val = self.__iter__._mock_return_value if ret_val is DEFAULT: return iter([]) # if ret_val was already an iterator, then calling iter on it should # return the iterator unchanged return iter(ret_val) return __iter__
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _set_return_value(mock, method, name): fixed = _return_values.get(name, DEFAULT) if fixed is not DEFAULT: method.return_value = fixed return return_calulator = _calculate_return_value.get(name) if return_calulator is not None: try: return_value = return_calulator(mock) except AttributeError: # XXXX why do we return AttributeError here? # set it as a side_effect instead? return_value = AttributeError(name) method.return_value = return_value return side_effector = _side_effect_methods.get(name) if side_effector is not None: method.side_effect = side_effector(mock)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, *args, **kw): _super(MagicMixin, self).__init__(*args, **kw) self._mock_set_magics()
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics()
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def mock_add_spec(self, spec, spec_set=False): """Add a spec to a mock. `spec` can either be an object or a list of strings. Only attributes on the `spec` can be fetched as attributes from the mock. If `spec_set` is True then only attributes on the spec can be set.""" self._mock_add_spec(spec, spec_set) self._mock_set_magics()
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __init__(self, name, parent): self.name = name self.parent = parent
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def create_mock(self): entry = self.name parent = self.parent m = parent._get_child_mock(name=entry, _new_name=entry, _new_parent=parent) setattr(parent, entry, m) _set_return_value(parent, m, entry) return m
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __eq__(self, other): return True
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __repr__(self): return '<ANY>'
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def _format_call_signature(name, args, kwargs): message = '%s(%%s)' % name formatted_args = '' args_string = ', '.join([repr(arg) for arg in args]) kwargs_string = ', '.join([ '%s=%r' % (key, value) for key, value in kwargs.items() ]) if args_string: formatted_args = args_string if kwargs_string: if formatted_args: formatted_args += ', ' formatted_args += kwargs_string return message % formatted_args
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __new__(cls, value=(), name=None, parent=None, two=False, from_kall=True): name = '' args = () kwargs = {} _len = len(value) if _len == 3: name, args, kwargs = value elif _len == 2: first, second = value if isinstance(first, basestring): name = first if isinstance(second, tuple): args = second else: kwargs = second else: args, kwargs = first, second elif _len == 1: value, = value if isinstance(value, basestring): name = value elif isinstance(value, tuple): args = value else: kwargs = value if two: return tuple.__new__(cls, (args, kwargs)) return tuple.__new__(cls, (name, args, kwargs))
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __eq__(self, other): if other is ANY: return True try: len_other = len(other) except TypeError: return False self_name = '' if len(self) == 2: self_args, self_kwargs = self else: self_name, self_args, self_kwargs = self other_name = '' if len_other == 0: other_args, other_kwargs = (), {} elif len_other == 3: other_name, other_args, other_kwargs = other elif len_other == 1: value, = other if isinstance(value, tuple): other_args = value other_kwargs = {} elif isinstance(value, basestring): other_name = value other_args, other_kwargs = (), {} else: other_args = () other_kwargs = value else: # len 2 # could be (name, args) or (name, kwargs) or (args, kwargs) first, second = other if isinstance(first, basestring): other_name = first if isinstance(second, tuple): other_args, other_kwargs = second, {} else: other_args, other_kwargs = (), second else: other_args, other_kwargs = first, second if self_name and other_name != self_name: return False # this order is important for ANY to work! return (other_args, other_kwargs) == (self_args, self_kwargs)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __call__(self, *args, **kwargs): if self.name is None: return _Call(('', args, kwargs), name='()') name = self.name + '()' return _Call((self.name, args, kwargs), name=name, parent=self)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]
def __repr__(self): if not self.from_kall: name = self.name or 'call' if name.startswith('()'): name = 'call%s' % name return name if len(self) == 2: name = 'call' args, kwargs = self else: name, args, kwargs = self if not name: name = 'call' elif not name.startswith('()'): name = 'call.%s' % name else: name = 'call%s' % name return _format_call_signature(name, args, kwargs)
mozilla/popcorn_maker
[ 34, 28, 34, 1, 1334919665 ]