本文整理汇总了Python中unittest.mock.patch.dict函数的典型用法代码示例。如果您正苦于以下问题:Python dict函数的具体用法?Python dict怎么用?Python dict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dict函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_search_tags_silent_forced
def test_search_tags_silent_forced(app, settings, tracks, tracks_volume):
assert settings['karakara.search.tag.silent_forced'] == []
assert settings['karakara.search.tag.silent_hidden'] == []
data = app.get('/search_list/.json').json['data']
assert len(data['trackids']) == 19
# Test silent_forced - restrict down to 'category:anime' tracks
# - t1 and t2 are the only two tracks tags as anime
with patch.dict(settings, {'karakara.search.tag.silent_forced': ['category:anime']}):
assert settings['karakara.search.tag.silent_forced'] == ['category:anime']
data = app.get('/search_list/.json').json['data']
assert len(data['trackids']) == 2
assert 't1' in data['trackids']
# Test silent_hidden - hide tracks with tag 'category:anime'
# - t1 and t2 are the only two tracks tags as anime they should be hidden in the response
with patch.dict(settings, {'karakara.search.tag.silent_hidden': ['category:anime']}):
assert settings['karakara.search.tag.silent_hidden'] == ['category:anime']
data = app.get('/search_list/.json').json['data']
assert len(data['trackids']) == 17
assert 't1' not in data['trackids']
assert not settings['karakara.search.tag.silent_forced']
assert not settings['karakara.search.tag.silent_hidden']
示例2: test_load_hassio
async def test_load_hassio(hass):
"""Test that we load Hass.io component."""
with patch.dict(os.environ, {}, clear=True):
assert bootstrap._get_components(hass, {}) == set()
with patch.dict(os.environ, {'HASSIO': '1'}):
assert bootstrap._get_components(hass, {}) == {'hassio'}
示例3: test_two_step_flow
def test_two_step_flow(hass, client):
"""Test we can finish a two step flow."""
set_component(
hass, 'test',
MockModule('test', async_setup_entry=mock_coro_func(True)))
class TestFlow(core_ce.ConfigFlow):
VERSION = 1
@asyncio.coroutine
def async_step_user(self, user_input=None):
return self.async_show_form(
step_id='account',
data_schema=vol.Schema({
'user_title': str
}))
@asyncio.coroutine
def async_step_account(self, user_input=None):
return self.async_create_entry(
title=user_input['user_title'],
data={'secret': 'account_token'}
)
with patch.dict(HANDLERS, {'test': TestFlow}):
resp = yield from client.post('/api/config/config_entries/flow',
json={'handler': 'test'})
assert resp.status == 200
data = yield from resp.json()
flow_id = data.pop('flow_id')
assert data == {
'type': 'form',
'handler': 'test',
'step_id': 'account',
'data_schema': [
{
'name': 'user_title',
'type': 'string'
}
],
'description_placeholders': None,
'errors': None
}
with patch.dict(HANDLERS, {'test': TestFlow}):
resp = yield from client.post(
'/api/config/config_entries/flow/{}'.format(flow_id),
json={'user_title': 'user-title'})
assert resp.status == 200
data = yield from resp.json()
data.pop('flow_id')
assert data == {
'handler': 'test',
'type': 'create_entry',
'title': 'user-title',
'version': 1,
'description': None,
'description_placeholders': None,
}
示例4: test_dict_context_manager
def test_dict_context_manager(self):
foo = {}
with patch.dict(foo, {'a': 'b'}):
self.assertEqual(foo, {'a': 'b'})
self.assertEqual(foo, {})
with self.assertRaises(NameError), patch.dict(foo, {'a': 'b'}):
self.assertEqual(foo, {'a': 'b'})
raise NameError('Konrad')
self.assertEqual(foo, {})
示例5: test_cookie_secret_env
def test_cookie_secret_env(tmpdir):
hub = MockHub(cookie_secret_file=str(tmpdir.join('cookie_secret')))
with patch.dict(os.environ, {'JPY_COOKIE_SECRET': 'not hex'}):
with pytest.raises(ValueError):
hub.init_secrets()
with patch.dict(os.environ, {'JPY_COOKIE_SECRET': 'abc123'}):
hub.init_secrets()
assert hub.cookie_secret == binascii.a2b_hex('abc123')
assert not os.path.exists(hub.cookie_secret_file)
示例6: test_setup_hassio_no_additional_data
def test_setup_hassio_no_additional_data(hass, aioclient_mock):
"""Test setup with API push default data."""
with patch.dict(os.environ, MOCK_ENVIRON), \
patch.dict(os.environ, {'HASSIO_TOKEN': "123456"}):
result = yield from async_setup_component(hass, 'hassio', {
'hassio': {},
})
assert result
assert aioclient_mock.call_count == 3
assert aioclient_mock.mock_calls[-1][3]['X-HASSIO-KEY'] == "123456"
示例7: test_dict_context_manager
def test_dict_context_manager(self):
foo = {}
with patch.dict(foo, {"a": "b"}):
self.assertEqual(foo, {"a": "b"})
self.assertEqual(foo, {})
with self.assertRaises(NameError):
with patch.dict(foo, {"a": "b"}):
self.assertEqual(foo, {"a": "b"})
raise NameError("Konrad")
self.assertEqual(foo, {})
示例8: test_wrapper_workspace
def test_wrapper_workspace(check_call, makedirs):
with patch.dict(os.environ, {'PROJECT_NAME': 'unittestproject', 'JOB_NAME': 'unittestjob'}):
sanctify.wrapper_workspace(['--project', '--', 'job.sh'])
workspace = os.path.expanduser('~/.sanctify/workspace/project/unittestproject')
eq_(workspace, makedirs.call_args[0][0])
eq_(['job.sh'], check_call.call_args[0][0])
eq_(workspace, check_call.call_args[1]['cwd'])
with patch.dict(os.environ, {'PROJECT_NAME': 'unittestproject', 'JOB_NAME': 'unittestjob'}):
sanctify.wrapper_workspace(['--job', '--', 'job.sh'])
eq_(os.path.expanduser('~/.sanctify/workspace/job/unittestproject/unittestjob'), makedirs.call_args[0][0])
eq_(['job.sh'], check_call.call_args[0][0])
示例9: test_cookie_secret_env
def test_cookie_secret_env(tmpdir, request):
kwargs = {'cookie_secret_file': str(tmpdir.join('cookie_secret'))}
ssl_enabled = getattr(request.module, "ssl_enabled", False)
if ssl_enabled:
kwargs['internal_certs_location'] = str(tmpdir)
hub = MockHub(**kwargs)
with patch.dict(os.environ, {'JPY_COOKIE_SECRET': 'not hex'}):
with pytest.raises(ValueError):
hub.init_secrets()
with patch.dict(os.environ, {'JPY_COOKIE_SECRET': 'abc123'}):
hub.init_secrets()
assert hub.cookie_secret == binascii.a2b_hex('abc123')
assert not os.path.exists(hub.cookie_secret_file)
示例10: test_autocomplete
def test_autocomplete(self):
class TestCommand(Cli):
def command_avocado(self, kwarg):
pass
argv = 'manage.py'
test_cmd = TestCommand()
with patch.dict('os.environ', {'IKTOMI_AUTO_COMPLETE':'1',
'COMP_WORDS':argv,
'COMP_CWORD':'1' }):
out = get_io()
with patch.object(sys, 'stdout', out):
with self.assertRaises(SystemExit):
manage(dict(fruit=test_cmd), argv.split())
self.assertEqual(u'fruit fruit:', out.getvalue())
argv = 'manage.py fr'
test_cmd = TestCommand()
with patch.dict('os.environ', {'IKTOMI_AUTO_COMPLETE':'1',
'COMP_WORDS':argv,
'COMP_CWORD':'1' }):
out = get_io()
with patch.object(sys, 'stdout', out):
with self.assertRaises(SystemExit):
manage(dict(fruit=test_cmd), argv.split())
self.assertEqual(u'fruit fruit:', out.getvalue())
argv = 'manage.py fruit:'
test_cmd = TestCommand()
with patch.dict('os.environ', {'IKTOMI_AUTO_COMPLETE':'1',
'COMP_WORDS':argv.replace(":", " : "),
'COMP_CWORD':'2' }):
out = get_io()
with patch.object(sys, 'stdout', out):
with self.assertRaises(SystemExit):
manage(dict(fruit=test_cmd), argv.split())
self.assertEqual(u'avocado', out.getvalue())
argv = 'manage.py fruit:av'
test_cmd = TestCommand()
with patch.dict('os.environ', {'IKTOMI_AUTO_COMPLETE':'1',
'COMP_WORDS':argv.replace(":", " : "),
'COMP_CWORD':'3' }):
out = get_io()
with patch.object(sys, 'stdout', out):
with self.assertRaises(SystemExit):
manage(dict(fruit=test_cmd), argv.split())
self.assertEqual(u'avocado', out.getvalue())
示例11: test_add_entry_calls_setup_entry
def test_add_entry_calls_setup_entry(hass, manager):
"""Test we call setup_config_entry."""
mock_setup_entry = MagicMock(return_value=mock_coro(True))
loader.set_component(
'comp',
MockModule('comp', async_setup_entry=mock_setup_entry))
class TestFlow(data_entry_flow.FlowHandler):
VERSION = 1
@asyncio.coroutine
def async_step_init(self, user_input=None):
return self.async_create_entry(
title='title',
data={
'token': 'supersecret'
})
with patch.dict(config_entries.HANDLERS, {'comp': TestFlow, 'beer': 5}):
yield from manager.flow.async_init('comp')
yield from hass.async_block_till_done()
assert len(mock_setup_entry.mock_calls) == 1
p_hass, p_entry = mock_setup_entry.mock_calls[0][1]
assert p_hass is hass
assert p_entry.data == {
'token': 'supersecret'
}
示例12: test_type_covers
def test_type_covers(type_name, entity_id, state, attrs):
"""Test if cover types are associated correctly."""
mock_type = Mock()
with patch.dict(TYPES, {type_name: mock_type}):
entity_state = State(entity_id, state, attrs)
get_accessory(None, None, entity_state, 2, {})
assert mock_type.called
示例13: test_saving_and_loading
def test_saving_and_loading(hass):
"""Test that we're saving and loading correctly."""
class TestFlow(data_entry_flow.FlowHandler):
VERSION = 5
@asyncio.coroutine
def async_step_init(self, user_input=None):
return self.async_create_entry(
title='Test Title',
data={
'token': 'abcd'
}
)
with patch.dict(config_entries.HANDLERS, {'test': TestFlow}):
yield from hass.config_entries.flow.async_init('test')
class Test2Flow(data_entry_flow.FlowHandler):
VERSION = 3
@asyncio.coroutine
def async_step_init(self, user_input=None):
return self.async_create_entry(
title='Test 2 Title',
data={
'username': 'bla'
}
)
json_path = 'homeassistant.util.json.open'
with patch('homeassistant.config_entries.HANDLERS.get',
return_value=Test2Flow), \
patch.object(config_entries, 'SAVE_DELAY', 0):
yield from hass.config_entries.flow.async_init('test')
with patch(json_path, mock_open(), create=True) as mock_write:
# To trigger the call_later
yield from asyncio.sleep(0, loop=hass.loop)
# To execute the save
yield from hass.async_block_till_done()
# Mock open calls are: open file, context enter, write, context leave
written = mock_write.mock_calls[2][1][0]
# Now load written data in new config manager
manager = config_entries.ConfigEntries(hass, {})
with patch('os.path.isfile', return_value=True), \
patch(json_path, mock_open(read_data=written), create=True):
yield from manager.async_load()
# Ensure same order
for orig, loaded in zip(hass.config_entries.async_entries(),
manager.async_entries()):
assert orig.version == loaded.version
assert orig.domain == loaded.domain
assert orig.title == loaded.title
assert orig.data == loaded.data
assert orig.source == loaded.source
示例14: test_env_token_badfile
def test_env_token_badfile(self):
""" If I try to reference a bad secretfile in the environment it should complain,
even if a valid secretfile is specified in the config file.
This should apply to the token secret too.
"""
with patch.dict('os.environ', {'authtkt_secretfile': "NOT_A_REAL_FILE_12345"}):
self.assertRaises(FileNotFoundError, get_app, test_ini)
示例15: test_connect_with_pkey
def test_connect_with_pkey(self, mock_serialization):
mock_snowflake = Mock(name='mock_snowflake')
mock_connector = mock_snowflake.connector
mock_pkey = mock_serialization.load_pem_private_key.return_value = Mock(name='pkey')
# need to patch this here so it can be imported in the function scope
with patch.dict('sys.modules', snowflake=mock_snowflake):
mock_connector.connect.return_value = 'OK'
snowflake = SnowflakeDatabase(user='test_user',
private_key_data='abcdefg',
private_key_password='1234',
account='test_account',
database='test_database')
result = snowflake.connect()
with self.subTest('returns connection'):
self.assertEqual('OK', result)
with self.subTest('connects with credentials'):
mock_serialization.load_pem_private_key.assert_called_once_with(b'abcdefg',
b'1234',
backend=ANY)
with self.subTest('connects with credentials'):
mock_connector.connect.assert_called_once_with(user='test_user',
password=None,
account='test_account',
database='test_database',
private_key=mock_pkey.private_bytes.return_value,
region=None,
warehouse=None)