本文整理汇总了Python中_pytest.monkeypatch.MonkeyPatch.setattr方法的典型用法代码示例。如果您正苦于以下问题:Python MonkeyPatch.setattr方法的具体用法?Python MonkeyPatch.setattr怎么用?Python MonkeyPatch.setattr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类_pytest.monkeypatch.MonkeyPatch
的用法示例。
在下文中一共展示了MonkeyPatch.setattr方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _prepare
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def _prepare(self):
self.counters = {}
basename = None
cli_tempdir_basename = self.config.getvalue('tempdir_basename')
if cli_tempdir_basename is not None:
basename = cli_tempdir_basename
else:
# Let's see if we have a pytest_tempdir_basename hook implementation
basename = self.config.hook.pytest_tempdir_basename()
if basename is None:
# If by now, basename is still None, use the current directory name
basename = os.path.basename(py.path.local().strpath) # pylint: disable=no-member
mpatch = MonkeyPatch()
temproot = py.path.local.get_temproot() # pylint: disable=no-member
# Let's get the full real path to the tempdir
tempdir = temproot.join(basename).realpath()
if tempdir.exists():
# If it exists, it's a stale tempdir. Remove it
log.warning('Removing stale tempdir: %s', tempdir.strpath)
tempdir.remove(rec=True, ignore_errors=True)
# Make sure the tempdir is created
tempdir.ensure(dir=True)
# Store a reference the tempdir for cleanup purposes when ending the test
# session
mpatch.setattr(self.config, '_tempdir', self, raising=False)
# Register the cleanup actions
self.config._cleanup.extend([
mpatch.undo,
self._clean_up_tempdir
])
self.tempdir = tempdir
示例2: test_eth_ticker
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def test_eth_ticker(
empty_proxy: PaywalledProxy,
session: Session,
sender_privkey: str,
receiver_privkey: str,
monkeypatch: MonkeyPatch
):
def get_patched(*args, **kwargs):
body = {
'mid': '682.435', 'bid': '682.18', 'ask': '682.69', 'last_price': '683.16',
'low': '532.97', 'high': '684.0', 'volume': '724266.25906224',
'timestamp': '1513167820.721733'
}
return jsonify(body)
monkeypatch.setattr(PaywalledProxyUrl, 'get', get_patched)
ETHTickerProxy(receiver_privkey, proxy=empty_proxy)
ticker = ETHTickerClient(sender_privkey, session=session, poll_interval=0.5)
def post():
ticker.close()
assert ticker.pricevar.get() == '683.16 USD'
assert len(session.client.get_open_channels()) == 0
ticker.success = True
session.close_channel_on_exit = True
ticker.success = False
ticker.root.after(1500, post)
ticker.run()
assert ticker.success
示例3: test_issue156_undo_staticmethod
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def test_issue156_undo_staticmethod(Sample):
monkeypatch = MonkeyPatch()
monkeypatch.setattr(Sample, "hello", None)
assert Sample.hello is None
monkeypatch.undo()
assert Sample.hello()
示例4: test_client_private_key_path
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def test_client_private_key_path(
patched_contract,
monkeypatch: MonkeyPatch,
sender_privkey: str,
tmpdir: LocalPath,
web3: Web3,
channel_manager_address: str
):
def check_permission_safety_patched(path: str):
return True
monkeypatch.setattr(
microraiden.utils.private_key,
'check_permission_safety',
check_permission_safety_patched
)
privkey_file = tmpdir.join('private_key.txt')
privkey_file.write(sender_privkey)
with pytest.raises(AssertionError):
Client(
private_key='0xthis_is_not_a_private_key',
channel_manager_address=channel_manager_address,
web3=web3
)
with pytest.raises(AssertionError):
Client(
private_key='0xcorrect_length_but_still_not_a_private_key_12345678901234567',
channel_manager_address=channel_manager_address,
web3=web3
)
with pytest.raises(AssertionError):
Client(
private_key='/nonexisting/path',
channel_manager_address=channel_manager_address,
web3=web3
)
Client(
private_key=sender_privkey,
channel_manager_address=channel_manager_address,
web3=web3
)
Client(
private_key=sender_privkey[2:],
channel_manager_address=channel_manager_address,
web3=web3
)
Client(
private_key=str(tmpdir.join('private_key.txt')),
channel_manager_address=channel_manager_address,
web3=web3
)
示例5: pytest_configure
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def pytest_configure(config):
"""Create a TempdirFactory and attach it to the config object.
This is to comply with existing plugins which expect the handler to be
available at pytest_configure time, but ideally should be moved entirely
to the tmpdir_factory session fixture.
"""
mp = MonkeyPatch()
t = TempdirFactory(config)
config._cleanup.extend([mp.undo, t.finish])
mp.setattr(config, '_tmpdirhandler', t, raising=False)
mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
示例6: pytest_configure
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def pytest_configure(self, config):
if not config.getoption('ast_as_python'):
return
mp = MonkeyPatch()
mp.setattr(
'_pytest.assertion.rewrite.rewrite_asserts',
make_replacement_rewrite_asserts(self.store))
# written pyc files will bypass our patch, so disable reading them
mp.setattr(
'_pytest.assertion.rewrite._read_pyc',
lambda source, pyc, trace=None: None)
config._cleanup.append(mp.undo)
示例7: block_unmocked_requests
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def block_unmocked_requests():
"""
Prevents requests from being made unless they are mocked.
Helps avoid inadvertent dependencies on external resources during the test run.
"""
def mocked_send(*args, **kwargs):
raise RuntimeError('Tests must mock all HTTP requests!')
# The standard monkeypatch fixture cannot be used with session scope:
# https://github.com/pytest-dev/pytest/issues/363
monkeypatch = MonkeyPatch()
# Monkeypatching here since any higher level would break responses:
# https://github.com/getsentry/responses/blob/0.5.1/responses.py#L295
monkeypatch.setattr('requests.adapters.HTTPAdapter.send', mocked_send)
yield monkeypatch
monkeypatch.undo()
示例8: test_delattr
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def test_delattr():
class A(object):
x = 1
monkeypatch = MonkeyPatch()
monkeypatch.delattr(A, "x")
assert not hasattr(A, "x")
monkeypatch.undo()
assert A.x == 1
monkeypatch = MonkeyPatch()
monkeypatch.delattr(A, "x")
pytest.raises(AttributeError, "monkeypatch.delattr(A, 'y')")
monkeypatch.delattr(A, "y", raising=False)
monkeypatch.setattr(A, "x", 5, raising=False)
assert A.x == 5
monkeypatch.undo()
assert A.x == 1
示例9: test_delattr
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def test_delattr():
class A:
x = 1
monkeypatch = MonkeyPatch()
monkeypatch.delattr(A, 'x')
assert not hasattr(A, 'x')
monkeypatch.undo()
assert A.x == 1
monkeypatch = MonkeyPatch()
monkeypatch.delattr(A, 'x')
pytest.raises(AttributeError, "monkeypatch.delattr(A, 'y')")
monkeypatch.delattr(A, 'y', raising=False)
monkeypatch.setattr(A, 'x', 5, raising=False)
assert A.x == 5
monkeypatch.undo()
assert A.x == 1
示例10: pytest_configure
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def pytest_configure(config):
"""Create a TempdirFactory and attach it to the config object.
This is to comply with existing plugins which expect the handler to be
available at pytest_configure time, but ideally should be moved entirely
to the tmpdir_factory session fixture.
"""
mp = MonkeyPatch()
tmppath_handler = TempPathFactory.from_config(config)
t = TempdirFactory(tmppath_handler)
config._cleanup.append(mp.undo)
mp.setattr(config, "_tmp_path_factory", tmppath_handler, raising=False)
mp.setattr(config, "_tmpdirhandler", t, raising=False)
mp.setattr(pytest, "ensuretemp", t.ensuretemp, raising=False)
示例11: TestRelatedFieldHTMLCutoff
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
class TestRelatedFieldHTMLCutoff(APISimpleTestCase):
def setUp(self):
self.queryset = MockQueryset([
MockObject(pk=i, name=str(i)) for i in range(0, 1100)
])
self.monkeypatch = MonkeyPatch()
def test_no_settings(self):
# The default is 1,000, so sans settings it should be 1,000 plus one.
for many in (False, True):
field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
many=many)
options = list(field.iter_options())
assert len(options) == 1001
assert options[-1].display_text == "More than 1000 items..."
def test_settings_cutoff(self):
self.monkeypatch.setattr(relations, "api_settings",
MockApiSettings(2, "Cut Off"))
for many in (False, True):
field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
many=many)
options = list(field.iter_options())
assert len(options) == 3 # 2 real items plus the 'Cut Off' item.
assert options[-1].display_text == "Cut Off"
def test_settings_cutoff_none(self):
# Setting it to None should mean no limit; the default limit is 1,000.
self.monkeypatch.setattr(relations, "api_settings",
MockApiSettings(None, "Cut Off"))
for many in (False, True):
field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
many=many)
options = list(field.iter_options())
assert len(options) == 1100
def test_settings_kwargs_cutoff(self):
# The explicit argument should override the settings.
self.monkeypatch.setattr(relations, "api_settings",
MockApiSettings(2, "Cut Off"))
for many in (False, True):
field = serializers.PrimaryKeyRelatedField(queryset=self.queryset,
many=many,
html_cutoff=100)
options = list(field.iter_options())
assert len(options) == 101
assert options[-1].display_text == "Cut Off"
示例12: test_setattr
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
def test_setattr():
class A(object):
x = 1
monkeypatch = MonkeyPatch()
pytest.raises(AttributeError, "monkeypatch.setattr(A, 'notexists', 2)")
monkeypatch.setattr(A, "y", 2, raising=False)
assert A.y == 2
monkeypatch.undo()
assert not hasattr(A, "y")
monkeypatch = MonkeyPatch()
monkeypatch.setattr(A, "x", 2)
assert A.x == 2
monkeypatch.setattr(A, "x", 3)
assert A.x == 3
monkeypatch.undo()
assert A.x == 1
A.x = 5
monkeypatch.undo() # double-undo makes no modification
assert A.x == 5
示例13: Copyright
# 需要导入模块: from _pytest.monkeypatch import MonkeyPatch [as 别名]
# 或者: from _pytest.monkeypatch.MonkeyPatch import setattr [as 别名]
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
"""Monkeypatching fixtures."""
from _pytest.monkeypatch import MonkeyPatch
mp = MonkeyPatch()
class FakeJob(object):
id = 'FAKE_JOB_ID'
mp.setattr('rq.get_current_job', lambda: FakeJob())