How to use _copy_func_details method in autotest

Best Python code snippet using autotest_python Github


Full Screen

1# Copyright 2017 Cloudbase Solutions Srl2# All Rights Reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License"); you may5# not use this file except in compliance with the License. You may obtain6# a copy of the License at7#8# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT12# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the13# License for the specific language governing permissions and limitations14# under the License.15import functools16from unittest import mock17import fixtures18def _lazy_autospec_method(mocked_method, original_method, eat_self):19 if mocked_method._mock_check_sig.__dict__.get('autospeced'):20 return21 _lazy_autospec = mock.create_autospec(original_method)22 if eat_self:23 # consume self argument.24 _lazy_autospec = functools.partial(_lazy_autospec, None)25 def _autospeced(*args, **kwargs):26 _lazy_autospec(*args, **kwargs)27 # _mock_check_sig is called by the mock's __call__ method.28 # which means that if a method is not called, _autospeced is not29 # called.30 _autospeced.__dict__['autospeced'] = True31 mocked_method._mock_check_sig = _autospeced32class _AutospecMockMixin(object):33 """Mock object that lazily autospecs the given spec's methods."""34 def __init__(self, *args, **kwargs):35 super(_AutospecMockMixin, self).__init__(*args, **kwargs)36 autospec = kwargs.get('autospec')37 self.__dict__['_autospec'] = autospec38 _mock_methods = self.__dict__['_mock_methods']39 if _mock_methods:40 # this will allow us to be able to set _mock_check_sig if41 # the spec_set argument has been given.42 _mock_methods.append('_mock_check_sig')43 # callable mocks with autospecs (e.g.: the given autospec is a class)44 # should have their return values autospeced as well.45 if autospec:46 self.return_value.__dict__['_autospec'] = autospec47 def __getattr__(self, name):48 attr = super(_AutospecMockMixin, self).__getattr__(name)49 original_spec = self.__dict__['_autospec']50 if not original_spec:51 return attr52 if not hasattr(original_spec, name):53 raise AttributeError(name)54 # check if the original attribute is callable, and the mock was not55 # autospeced already.56 original_attr = getattr(original_spec, name)57 if callable(original_attr):58 # lazily autospec callable attribute.59 eat_self = mock._must_skip(60 original_spec, name,61 isinstance(original_spec, type)62 )63 _lazy_autospec_method(attr, original_attr, eat_self)64 return attr65class _AutospecMock(_AutospecMockMixin, mock.Mock):66 pass67class _AutospecMagicMock(_AutospecMockMixin, mock.MagicMock):68 pass69class MockAutospecFixture(fixtures.Fixture):70 """A fixture to add / fix the autospec feature into the mock library.71 The current version of the mock library has a few unaddressed issues, which72 can lead to erroneous unit tests, and can hide actual issues. This fixture73 is to be removed once these issues have been addressed in the mock library.74 Issue addressed by the fixture:75 * mocked method's signature checking:76 - - mock can only accept a spec object / class, and it makes sure that78 that attribute exists, but it does not check whether the given79 attribute is callable, or if its signature is respected in any way.80 - adds autospec argument. If the autospec argument is given, the81 mocked method's signature is also checked.82 """83 def setUp(self):84 super(MockAutospecFixture, self).setUp()85 # patch both external and internal usage of Mock / MagicMock.86 self.useFixture(87 fixtures.MonkeyPatch(88 'unittest.mock.Mock',89 _AutospecMock))90 self.useFixture(91 fixtures.MonkeyPatch(92 'unittest.mock.MagicMock',93 _AutospecMagicMock))94class _patch(mock._patch):95 """Patch class with working autospec functionality.96 Currently, mock.patch functionality doesn't handle the autospec parameter97 properly (the self argument is not consumed, causing assertions to fail).98 Until the issue is addressed in the mock library, this should be used99 instead.100 """102 def __enter__(self):103 # NOTE(claudiub): we're doing the autospec checks here so unit tests104 # have a chance to set up mocks in advance (e.g.: mocking platform105 # specific libraries, which would cause the patch to fail otherwise).106 # By default, autospec is None. We will consider it as True.107 autospec = True if self.autospec is None else self.autospec108 # in some cases, autospec cannot be set to True.109 skip_autospec = (getattr(self, attr) for attr in110 ['new_callable', 'create', 'spec'])111 # NOTE(claudiub): The "new" argument is always mock.DEFAULT, unless112 # explicitly set otherwise.113 if is not mock.DEFAULT or any(skip_autospec):114 # cannot autospec if new, new_callable, or create arguments given.115 autospec = False116 elif self.attribute:117 target = getattr(self.getter(), self.attribute, None)118 if isinstance(target, mock.Mock):119 # NOTE(claudiub): shouldn't autospec already mocked targets.120 # this can cause some issues. There are quite a few tests121 # which patch mocked methods.122 autospec = False123 # NOTE(claudiub): reset the self.autospec property, so we can handle124 # the autospec scenario ourselves.125 self.autospec = None126 if autospec:127 target = self.getter()128 original_attr = getattr(target, self.attribute)129 eat_self = mock._must_skip(130 target,131 self.attribute,132 isinstance(target, type)133 )134 new = super(_patch, self).__enter__()135 # NOTE(claudiub): mock.patch.multiple will cause new to be a136 # dict.137 mocked_method = (new[self.attribute] if isinstance(new, dict)138 else new)139 _lazy_autospec_method(mocked_method, original_attr, eat_self)140 return new141 else:142 return super(_patch, self).__enter__()143def _safe_attribute_error_wrapper(func):144 def wrapper(*args, **kwargs):145 try:146 return func(*args, **kwargs)147 except AttributeError:148 pass149 return wrapper150def patch_mock_module():151 """Replaces the mock.patch class."""152 mock._patch = _patch153 # NOTE(claudiub): mock cannot autospec partial functions properly,154 # especially those created by LazyLoader objects (scheduler client),155 # as it will try to copy the partial function's __name__ (which they do156 # not have).157 mock._copy_func_details = _safe_attribute_error_wrapper(...

Full Screen

Full Screen Github


Full Screen

...45 if mock is None:46 mock = mock_module.Mock()47 signature, func = mock_module._getsignature(func, skipfirst)48 checker = eval("lambda %s: None" % signature)49 mock_module._copy_func_details(func, checker)50 def funcopy(*args, **kwargs):51 checker(*args, **kwargs)52 return mock(*args, **kwargs)53 if not hasattr(mock_module, '_setup_func'):54 # compatibility with mock < 0.855 funcopy.mock = mock56 else:57 mock_module._setup_func(funcopy, mock)58 if static:59 funcopy = staticmethod(funcopy)60 return funcopy61mock_module.mocksignature = _patched_mocksignature62def get_data_path(file_name):63 return os.path.join(DATA_DIR, file_name)...

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:


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?