• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python patch.dict函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中unittest.mock.patch.dict函数的典型用法代码示例。如果您正苦于以下问题:Python dict函数的具体用法?Python dict怎么用?Python dict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了dict函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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']
开发者ID:richlanc,项目名称:KaraKara,代码行数:25,代码来源:test_tag_restrict.py


示例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'}
开发者ID:boced66,项目名称:home-assistant,代码行数:7,代码来源:test_bootstrap.py


示例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,
        }
开发者ID:chilicheech,项目名称:home-assistant,代码行数:59,代码来源:test_config_entries.py


示例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, {})
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:9,代码来源:testwith.py


示例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)
开发者ID:Carreau,项目名称:jupyterhub,代码行数:11,代码来源:test_app.py


示例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"
开发者ID:boced66,项目名称:home-assistant,代码行数:11,代码来源:test_init.py


示例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, {})
开发者ID:40123107,项目名称:2014cda,代码行数:12,代码来源:testwith.py


示例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])
开发者ID:hoxu,项目名称:sanctify,代码行数:14,代码来源:tests.py


示例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)
开发者ID:vilhelmen,项目名称:jupyterhub,代码行数:15,代码来源:test_app.py


示例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())
开发者ID:SmartTeleMax,项目名称:iktomi,代码行数:48,代码来源:base.py


示例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'
    }
开发者ID:tucka,项目名称:home-assistant,代码行数:31,代码来源:test_config_entries.py


示例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
开发者ID:EarthlingRich,项目名称:home-assistant,代码行数:7,代码来源:test_get_accessories.py


示例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
开发者ID:tucka,项目名称:home-assistant,代码行数:60,代码来源:test_config_entries.py


示例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)
开发者ID:cedadev,项目名称:eos-db,代码行数:7,代码来源:test_agent_api.py


示例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)
开发者ID:kayak,项目名称:fireant,代码行数:32,代码来源:test_snowflake.py


示例16: _init_server

 def _init_server(self):
     "Start the notebook server in a separate process"
     self.server_command = command = [sys.executable,
         '-m', 'notebook',
         '--no-browser',
         '--notebook-dir', self.nbdir.name,
         '--NotebookApp.base_url=%s' % self.base_url,
     ]
     # ipc doesn't work on Windows, and darwin has crazy-long temp paths,
     # which run afoul of ipc's maximum path length.
     if sys.platform.startswith('linux'):
         command.append('--KernelManager.transport=ipc')
     self.stream_capturer = c = StreamCapturer()
     c.start()
     env = os.environ.copy()
     env.update(self.env)
     if self.engine == 'phantomjs':
         env['IPYTHON_ALLOW_DRAFT_WEBSOCKETS_FOR_PHANTOMJS'] = '1'
     self.server = subprocess.Popen(command,
         stdout = c.writefd,
         stderr = subprocess.STDOUT,
         cwd=self.nbdir.name,
         env=env,
     )
     with patch.dict('os.environ', {'HOME': self.home.name}):
         runtime_dir = jupyter_runtime_dir()
     self.server_info_file = os.path.join(runtime_dir,
         'nbserver-%i.json' % self.server.pid
     )
     self._wait_for_server()
开发者ID:ACGC,项目名称:notebook,代码行数:30,代码来源:jstest.py


示例17: test_create_account

def test_create_account(hass, client):
    """Test a flow that creates an account."""
    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_create_entry(
                title='Test Entry',
                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()
    data.pop('flow_id')
    assert data == {
        'handler': 'test',
        'title': 'Test Entry',
        'type': 'create_entry',
        'version': 1,
        'description': None,
        'description_placeholders': None,
    }
开发者ID:chilicheech,项目名称:home-assistant,代码行数:31,代码来源:test_config_entries.py


示例18: test_maxFrames_get

    def test_maxFrames_get(self):
        bge = Mock()

        bge.logic.getMaxPhysicsFrame = Mock(return_value=5)
        with patch.dict('sys.modules', {'bge': bge}):
            from mbge import physics
            self.assertEqual(physics.maxFrames, 5)
开发者ID:BlenderMonster,项目名称:Gravitovores,代码行数:7,代码来源:test_physics.py


示例19: test_media_url

 def test_media_url(self):
     filename = 'test'
     # automatic version is set on 15mins granularity.
     mins_granularity = int(int(time.strftime('%M')) / 4) * 4
     time_id = '%s%s' % (time.strftime('%Y%m%d%H%m'), mins_granularity)
     media_id = self.amazon.media_id(filename)
     self.assertEqual('%s/%s' % (time_id, filename), media_id)
     self.assertEqual(
         self.amazon.url_for_media(media_id),
         'https://acname.s3-us-east-1.amazonaws.com/%s' % media_id
     )
     sub = 'test-sub'
     settings = {
         'AMAZON_S3_SUBFOLDER': sub,
         'MEDIA_PREFIX': 'https://acname.s3-us-east-1.amazonaws.com/' + sub
     }
     with patch.dict(self.app.config, settings):
         media_id = self.amazon.media_id(filename)
         self.assertEqual('%s/%s' % (time_id, filename), media_id)
         path = '%s/%s' % (sub, media_id)
         self.assertEqual(
             self.amazon.url_for_media(media_id),
             'https://acname.s3-us-east-1.amazonaws.com/%s' % path
         )
         with patch.object(self.amazon, 'client') as s3:
             self.amazon.get(media_id)
             self.assertTrue(s3.get_object.called)
             self.assertEqual(
                 s3.get_object.call_args[1],
                 dict(Bucket='acname', Key=path)
             )
开发者ID:nistormihai,项目名称:superdesk-core,代码行数:31,代码来源:amazon_media_storage_test.py


示例20: test_get_progress_flow_unauth

async def test_get_progress_flow_unauth(hass, client, hass_admin_user):
    """Test we can can't query the API for result of flow."""
    class TestFlow(core_ce.ConfigFlow):
        async def async_step_user(self, user_input=None):
            schema = OrderedDict()
            schema[vol.Required('username')] = str
            schema[vol.Required('password')] = str

            return self.async_show_form(
                step_id='user',
                data_schema=schema,
                errors={
                    'username': 'Should be unique.'
                }
            )

    with patch.dict(HANDLERS, {'test': TestFlow}):
        resp = await client.post('/api/config/config_entries/flow',
                                 json={'handler': 'test'})

    assert resp.status == 200
    data = await resp.json()

    hass_admin_user.groups = []

    resp2 = await client.get(
        '/api/config/config_entries/flow/{}'.format(data['flow_id']))

    assert resp2.status == 401
开发者ID:chilicheech,项目名称:home-assistant,代码行数:29,代码来源:test_config_entries.py



注:本文中的unittest.mock.patch.dict函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python patch.object函数代码示例发布时间:2022-05-27
下一篇:
Python call.foo函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap