How to use _dump_function_call method in autotest

Best Python code snippet using autotest_python

mock.py

Source:mock.py Github

copy

Full Screen

...108 if key not in dargs:109 return False110 return True111 def __str__(self):112 return _dump_function_call(self.symbol, self.args, self.dargs)113class function_mapping(base_mapping):114 def __init__(self, symbol, return_val, *args, **dargs):115 super(function_mapping, self).__init__(symbol, return_val, *args,116 **dargs)117 def and_return(self, return_obj):118 self.return_obj = return_obj119 def and_raises(self, error):120 self.error = error121class function_any_args_mapping(function_mapping):122 """A mock function mapping that doesn't verify its arguments."""123 def match(self, *args, **dargs):124 return True125class mock_function(object):126 def __init__(self, symbol, default_return_val=None,127 record=None, playback=None):128 self.default_return_val = default_return_val129 self.num_calls = 0130 self.args = []131 self.dargs = []132 self.symbol = symbol133 self.record = record134 self.playback = playback135 self.__name__ = symbol136 def __call__(self, *args, **dargs):137 self.num_calls += 1138 self.args.append(args)139 self.dargs.append(dargs)140 if self.playback:141 return self.playback(self.symbol, *args, **dargs)142 else:143 return self.default_return_val144 def expect_call(self, *args, **dargs):145 mapping = function_mapping(self.symbol, None, *args, **dargs)146 if self.record:147 self.record(mapping)148 return mapping149 def expect_any_call(self):150 """Like expect_call but don't give a hoot what arguments are passed."""151 mapping = function_any_args_mapping(self.symbol, None)152 if self.record:153 self.record(mapping)154 return mapping155class mask_function(mock_function):156 def __init__(self, symbol, original_function, default_return_val=None,157 record=None, playback=None):158 super(mask_function, self).__init__(symbol,159 default_return_val,160 record, playback)161 self.original_function = original_function162 def run_original_function(self, *args, **dargs):163 return self.original_function(*args, **dargs)164class mock_class(object):165 def __init__(self, cls, name, default_ret_val=None,166 record=None, playback=None):167 self.__name = name168 self.__record = record169 self.__playback = playback170 for symbol in dir(cls):171 if symbol.startswith("_"):172 continue173 orig_symbol = getattr(cls, symbol)174 if callable(orig_symbol):175 f_name = "%s.%s" % (self.__name, symbol)176 func = mock_function(f_name, default_ret_val,177 self.__record, self.__playback)178 setattr(self, symbol, func)179 else:180 setattr(self, symbol, orig_symbol)181 def __repr__(self):182 return '<mock_class: %s>' % self.__name183class mock_god(object):184 NONEXISTENT_ATTRIBUTE = object()185 def __init__(self, debug=False, fail_fast=True, ut=None):186 """187 With debug=True, all recorded method calls will be printed as188 they happen.189 With fail_fast=True, unexpected calls will immediately cause an190 exception to be raised. With False, they will be silently recorded and191 only reported when check_playback() is called.192 """193 self.recording = collections.deque()194 self.errors = []195 self._stubs = []196 self._debug = debug197 self._fail_fast = fail_fast198 self._ut = ut199 def set_fail_fast(self, fail_fast):200 self._fail_fast = fail_fast201 def create_mock_class_obj(self, cls, name, default_ret_val=None):202 record = self.__record_call203 playback = self.__method_playback204 errors = self.errors205 class cls_sub(cls):206 cls_count = 0207 # overwrite the initializer208 def __init__(self, *args, **dargs):209 pass210 @classmethod211 def expect_new(typ, *args, **dargs):212 obj = typ.make_new(*args, **dargs)213 mapping = base_mapping(name, obj, *args, **dargs)214 record(mapping)215 return obj216 def __new__(typ, *args, **dargs):217 return playback(name, *args, **dargs)218 @classmethod219 def make_new(typ, *args, **dargs):220 obj = super(cls_sub, typ).__new__(typ, *args,221 **dargs)222 typ.cls_count += 1223 obj_name = "%s_%s" % (name, typ.cls_count)224 for symbol in dir(obj):225 if (symbol.startswith("__") and226 symbol.endswith("__")):227 continue228 if isinstance(getattr(typ, symbol, None), property):229 continue230 orig_symbol = getattr(obj, symbol)231 if callable(orig_symbol):232 f_name = ("%s.%s" %233 (obj_name, symbol))234 func = mock_function(f_name,235 default_ret_val,236 record,237 playback)238 setattr(obj, symbol, func)239 else:240 setattr(obj, symbol,241 orig_symbol)242 return obj243 return cls_sub244 def create_mock_class(self, cls, name, default_ret_val=None):245 """246 Given something that defines a namespace cls (class, object,247 module), and a (hopefully unique) name, will create a248 mock_class object with that name and that possessess all249 the public attributes of cls. default_ret_val sets the250 default_ret_val on all methods of the cls mock.251 """252 return mock_class(cls, name, default_ret_val,253 self.__record_call, self.__method_playback)254 def create_mock_function(self, symbol, default_return_val=None):255 """256 create a mock_function with name symbol and default return257 value of default_ret_val.258 """259 return mock_function(symbol, default_return_val,260 self.__record_call, self.__method_playback)261 def mock_up(self, obj, name, default_ret_val=None):262 """263 Given an object (class instance or module) and a registration264 name, then replace all its methods with mock function objects265 (passing the orignal functions to the mock functions).266 """267 for symbol in dir(obj):268 if symbol.startswith("__"):269 continue270 orig_symbol = getattr(obj, symbol)271 if callable(orig_symbol):272 f_name = "%s.%s" % (name, symbol)273 func = mask_function(f_name, orig_symbol,274 default_ret_val,275 self.__record_call,276 self.__method_playback)277 setattr(obj, symbol, func)278 def stub_with(self, namespace, symbol, new_attribute):279 original_attribute = getattr(namespace, symbol,280 self.NONEXISTENT_ATTRIBUTE)281 # You only want to save the original attribute in cases where it is282 # directly associated with the object in question. In cases where283 # the attribute is actually inherited via some sort of hierarchy284 # you want to delete the stub (restoring the original structure)285 attribute_is_inherited = (hasattr(namespace, '__dict__') and286 symbol not in namespace.__dict__)287 if attribute_is_inherited:288 original_attribute = self.NONEXISTENT_ATTRIBUTE289 newstub = (namespace, symbol, original_attribute, new_attribute)290 self._stubs.append(newstub)291 setattr(namespace, symbol, new_attribute)292 def stub_function(self, namespace, symbol):293 mock_attribute = self.create_mock_function(symbol)294 self.stub_with(namespace, symbol, mock_attribute)295 def stub_class_method(self, cls, symbol):296 mock_attribute = self.create_mock_function(symbol)297 self.stub_with(cls, symbol, staticmethod(mock_attribute))298 def stub_class(self, namespace, symbol):299 attr = getattr(namespace, symbol)300 mock_class = self.create_mock_class_obj(attr, symbol)301 self.stub_with(namespace, symbol, mock_class)302 def stub_function_to_return(self, namespace, symbol, object_to_return):303 """Stub out a function with one that always returns a fixed value.304 @param namespace The namespace containing the function to stub out.305 @param symbol The attribute within the namespace to stub out.306 @param object_to_return The value that the stub should return whenever307 it is called.308 """309 self.stub_with(namespace, symbol,310 lambda *args, **dargs: object_to_return)311 def _perform_unstub(self, stub):312 namespace, symbol, orig_attr, new_attr = stub313 if orig_attr == self.NONEXISTENT_ATTRIBUTE:314 delattr(namespace, symbol)315 else:316 setattr(namespace, symbol, orig_attr)317 def unstub(self, namespace, symbol):318 for stub in reversed(self._stubs):319 if (namespace, symbol) == (stub[0], stub[1]):320 self._perform_unstub(stub)321 self._stubs.remove(stub)322 return323 raise StubNotFoundError()324 def unstub_all(self):325 self._stubs.reverse()326 for stub in self._stubs:327 self._perform_unstub(stub)328 self._stubs = []329 def __method_playback(self, symbol, *args, **dargs):330 if self._debug:331 print >> sys.__stdout__, (' * Mock call: ' +332 _dump_function_call(symbol, args, dargs))333 if len(self.recording) != 0:334 func_call = self.recording[0]335 if func_call.symbol != symbol:336 msg = ("Unexpected call: %s\nExpected: %s"337 % (_dump_function_call(symbol, args, dargs),338 func_call))339 self._append_error(msg)340 return None341 if not func_call.match(*args, **dargs):342 msg = ("Incorrect call: %s\nExpected: %s"343 % (_dump_function_call(symbol, args, dargs),344 func_call))345 self._append_error(msg)346 return None347 # this is the expected call so pop it and return348 self.recording.popleft()349 if func_call.error:350 raise func_call.error351 else:352 return func_call.return_obj353 else:354 msg = ("unexpected call: %s"355 % (_dump_function_call(symbol, args, dargs)))356 self._append_error(msg)357 return None358 def __record_call(self, mapping):359 self.recording.append(mapping)360 def _append_error(self, error):361 if self._debug:362 print >> sys.__stdout__, ' *** ' + error363 if self._fail_fast:364 raise CheckPlaybackError(error)365 self.errors.append(error)366 def check_playback(self):367 """368 Report any errors that were encounterd during calls369 to __method_playback().370 """371 if len(self.errors) > 0:372 if self._debug:373 print '\nPlayback errors:'374 for error in self.errors:375 print >> sys.__stdout__, error376 if self._ut:377 self._ut.fail('\n'.join(self.errors))378 raise CheckPlaybackError379 elif len(self.recording) != 0:380 errors = []381 for func_call in self.recording:382 error = "%s not called" % (func_call,)383 errors.append(error)384 print >> sys.__stdout__, error385 if self._ut:386 self._ut.fail('\n'.join(errors))387 raise CheckPlaybackError388 self.recording.clear()389 def mock_io(self):390 """Mocks and saves the stdout & stderr output"""391 self.orig_stdout = sys.stdout392 self.orig_stderr = sys.stderr393 self.mock_streams_stdout = StringIO.StringIO('')394 self.mock_streams_stderr = StringIO.StringIO('')395 sys.stdout = self.mock_streams_stdout396 sys.stderr = self.mock_streams_stderr397 def unmock_io(self):398 """Restores the stdout & stderr, and returns both399 output strings"""400 sys.stdout = self.orig_stdout401 sys.stderr = self.orig_stderr402 values = (self.mock_streams_stdout.getvalue(),403 self.mock_streams_stderr.getvalue())404 self.mock_streams_stdout.close()405 self.mock_streams_stderr.close()406 return values407def _arg_to_str(arg):408 if isinstance(arg, argument_comparator):409 return str(arg)410 return repr(arg)411def _dump_function_call(symbol, args, dargs):412 arg_vec = []413 for arg in args:414 arg_vec.append(_arg_to_str(arg))415 for key, val in dargs.iteritems():416 arg_vec.append("%s=%s" % (key, _arg_to_str(val)))...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run autotest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful