当前位置: 首页>>代码示例>>Python>>正文


Python mock.patch函数代码示例

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


在下文中一共展示了patch函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_ws_connect_deflate_per_message

async def test_ws_connect_deflate_per_message(loop, ws_key, key_data) -> None:
    resp = mock.Mock()
    resp.status = 101
    resp.headers = {
        hdrs.UPGRADE: hdrs.WEBSOCKET,
        hdrs.CONNECTION: hdrs.UPGRADE,
        hdrs.SEC_WEBSOCKET_ACCEPT: ws_key,
        hdrs.SEC_WEBSOCKET_EXTENSIONS: 'permessage-deflate',
    }
    with mock.patch('aiohttp.client.WebSocketWriter') as WebSocketWriter:
        with mock.patch('aiohttp.client.os') as m_os:
            with mock.patch('aiohttp.client.ClientSession.request') as m_req:
                m_os.urandom.return_value = key_data
                m_req.return_value = loop.create_future()
                m_req.return_value.set_result(resp)
                writer = WebSocketWriter.return_value = mock.Mock()
                send = writer.send = make_mocked_coro()

                session = aiohttp.ClientSession(loop=loop)
                resp = await session.ws_connect('http://test.org')

                await resp.send_str('string', compress=-1)
                send.assert_called_with('string', binary=False, compress=-1)

                await resp.send_bytes(b'bytes', compress=15)
                send.assert_called_with(b'bytes', binary=True, compress=15)

                await resp.send_json([{}], compress=-9)
                send.assert_called_with('[{}]', binary=False, compress=-9)

                await session.close()
开发者ID:KeepSafe,项目名称:aiohttp,代码行数:31,代码来源:test_client_ws.py

示例2: setUp

 def setUp(self):
     self.patcher1 = patch("samireland.views.EditableText.objects.create")
     self.patcher2 = patch("samireland.views.EditableText.objects.get")
     self.mock_create = self.patcher1.start()
     self.mock_get = self.patcher2.start()
     self.mock_create.return_value = "EDTEXT"
     self.mock_get.side_effect = EditableText.DoesNotExist
开发者ID:samirelanduk,项目名称:samireland.com,代码行数:7,代码来源:test_views.py

示例3: test_entry_existence

 def test_entry_existence(self, capsys):
     """
     Test recognition of already inserted entries.
     """
     apath = os.path.abspath(os.getcwd())
     sqlpath = os.path.join(apath, "bbarchivist.db")
     with mock.patch('bbarchivist.iniconfig.config_homepath', mock.MagicMock(return_value=apath)):
         try:
             cnxn = sqlite3.connect(sqlpath)
             with cnxn:
                 crsr = cnxn.cursor()
                 crsr.execute("DROP TABLE IF EXISTS Swrelease")
                 reqid = "INTEGER PRIMARY KEY"
                 reqs = "TEXT NOT NULL UNIQUE COLLATE NOCASE"
                 reqs2 = "TEXT"
                 table = "Swrelease(Id {0}, Os {1}, Software {1}, Available {2}, Date {2})".format(
                     *(reqid, reqs, reqs2))
                 crsr.execute("CREATE TABLE IF NOT EXISTS " + table)
         except sqlite3.Error:
             assert False
         assert not bs.check_exists("70.OSVERSION", "80.SWVERSION")
         bs.insert("70.OSVERSION", "80.SWVERSION", "available")
         assert bs.check_exists("70.OSVERSION", "80.SWVERSION")
         with mock.patch("sqlite3.connect", mock.MagicMock(side_effect=sqlite3.Error)):
             bs.check_exists("70.OSVERSION", "80.SWVERSION")
             assert "\n" in capsys.readouterr()[0]
开发者ID:thurask,项目名称:bbarchivist,代码行数:26,代码来源:test_sqlutils.py

示例4: test_midnight_turnover_after_midnight_inside_period

    def test_midnight_turnover_after_midnight_inside_period(self):
        """Test midnight turnover setting before midnight inside period ."""
        test_time = self.hass.config.time_zone.localize(
            datetime(2019, 1, 10, 21, 0, 0)).astimezone(pytz.UTC)
        config = {
            'binary_sensor': [
                {
                    'platform': 'tod',
                    'name': 'Night',
                    'after': '22:00',
                    'before': '5:00'
                },
            ]
        }
        with patch('homeassistant.components.tod.binary_sensor.dt_util.utcnow',
                   return_value=test_time):
            setup_component(self.hass, 'binary_sensor', config)

            state = self.hass.states.get('binary_sensor.night')
            assert state.state == STATE_OFF

            self.hass.block_till_done()

        with patch('homeassistant.components.tod.binary_sensor.dt_util.utcnow',
                   return_value=test_time + timedelta(hours=1)):

            self.hass.bus.fire(ha.EVENT_TIME_CHANGED, {
                ha.ATTR_NOW: test_time + timedelta(hours=1)})

            self.hass.block_till_done()
            state = self.hass.states.get('binary_sensor.night')
            assert state.state == STATE_ON
开发者ID:fbradyirl,项目名称:home-assistant,代码行数:32,代码来源:test_binary_sensor.py

示例5: test_blacklist

 def test_blacklist(self):
     with patch('recommendation.mozlog.middleware.current_app') as app:
         mock_request = self._request(path=LOG_PATH_BLACKLIST[0])
         mock_response = self._response()
         with patch(REQUEST_PATH, mock_request):
             request_summary(mock_response)
         eq_(app.logger.info.call_count, 0)
开发者ID:clouserw,项目名称:universal-search-recommendation,代码行数:7,代码来源:test_middleware.py

示例6: test_zwave_ready_wait

def test_zwave_ready_wait(hass, mock_openzwave):
    """Test that zwave continues after waiting for network ready."""
    # Initialize zwave
    yield from async_setup_component(hass, 'zwave', {'zwave': {}})
    yield from hass.async_block_till_done()

    sleeps = []

    def utcnow():
        return datetime.fromtimestamp(len(sleeps))

    asyncio_sleep = asyncio.sleep

    @asyncio.coroutine
    def sleep(duration, loop=None):
        if duration > 0:
            sleeps.append(duration)
        yield from asyncio_sleep(0)

    with patch('homeassistant.components.zwave.dt_util.utcnow', new=utcnow):
        with patch('asyncio.sleep', new=sleep):
            with patch.object(zwave, '_LOGGER') as mock_logger:
                hass.data[DATA_NETWORK].state = MockNetwork.STATE_STARTED
                hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
                yield from hass.async_block_till_done()

                assert len(sleeps) == const.NETWORK_READY_WAIT_SECS
                assert mock_logger.warning.called
                assert len(mock_logger.warning.mock_calls) == 1
                assert mock_logger.warning.mock_calls[0][1][1] == \
                    const.NETWORK_READY_WAIT_SECS
开发者ID:keatontaylor,项目名称:home-assistant,代码行数:31,代码来源:test_init.py

示例7: 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

示例8: setUp

    def setUp(self):
        super().setUp()

        class props:
            rosdistro = 'indigo'
            catkin_packages = ['my_package']
            source_space = 'src'
            source_subdir = None
            include_roscore = False

        self.properties = props()
        self.project_options = snapcraft.ProjectOptions()

        patcher = mock.patch('snapcraft.repo.Ubuntu')
        self.ubuntu_mock = patcher.start()
        self.addCleanup(patcher.stop)

        patcher = mock.patch(
            'snapcraft.plugins.catkin._find_system_dependencies')
        self.dependencies_mock = patcher.start()
        self.addCleanup(patcher.stop)

        patcher = mock.patch('snapcraft.plugins.catkin._Rosdep')
        self.rosdep_mock = patcher.start()
        self.addCleanup(patcher.stop)
开发者ID:morphis,项目名称:snapcraft,代码行数:25,代码来源:test_plugin_catkin.py

示例9: test_new_object_with_two_webhook_signals

def test_new_object_with_two_webhook_signals(settings):
    settings.WEBHOOKS_ENABLED = True
    project = f.ProjectFactory()
    f.WebhookFactory.create(project=project)
    f.WebhookFactory.create(project=project)

    objects = [
        f.IssueFactory.create(project=project),
        f.TaskFactory.create(project=project),
        f.UserStoryFactory.create(project=project),
        f.WikiPageFactory.create(project=project)
    ]

    response = Mock(status_code=200, headers={}, content="ok")
    response.elapsed.total_seconds.return_value = 100

    for obj in objects:
        with patch("taiga.webhooks.tasks.requests.Session.send", return_value=response) as session_send_mock:
            services.take_snapshot(obj, user=obj.owner, comment="test")
            assert session_send_mock.call_count == 2

    for obj in objects:
        with patch("taiga.webhooks.tasks.requests.Session.send", return_value=response) as session_send_mock:
            services.take_snapshot(obj, user=obj.owner, comment="test")
            assert session_send_mock.call_count == 2

    for obj in objects:
        with patch("taiga.webhooks.tasks.requests.Session.send", return_value=response) as session_send_mock:
            services.take_snapshot(obj, user=obj.owner)
            assert session_send_mock.call_count == 0

    for obj in objects:
        with patch("taiga.webhooks.tasks.requests.Session.send", return_value=response) as session_send_mock:
            services.take_snapshot(obj, user=obj.owner, comment="test", delete=True)
            assert session_send_mock.call_count == 2
开发者ID:74Labs,项目名称:taiga-back,代码行数:35,代码来源:test_webhooks_signals.py

示例10: setUp

    def setUp(self):
        super().setUp()

        class Options:
            build_parameters = []
            kconfigfile = None
            kconfigflavour = None
            kdefconfig = []
            kconfigs = []
            build_attributes = []

        self.options = Options()
        self.project_options = snapcraft.ProjectOptions(
            target_deb_arch=self.deb_arch)

        patcher = mock.patch('snapcraft.internal.common.run')
        self.run_mock = patcher.start()
        self.addCleanup(patcher.stop)

        patcher = mock.patch('snapcraft.ProjectOptions.is_cross_compiling')
        patcher.start()
        self.addCleanup(patcher.stop)

        patcher = mock.patch.dict(os.environ, {})
        self.env_mock = patcher.start()
        self.addCleanup(patcher.stop)
开发者ID:cholcombe973,项目名称:snapcraft,代码行数:26,代码来源:test_kbuild.py

示例11: test__common_submit

def test__common_submit(tmpdir, db):
    from Ganga.Core import BackendError
    j = Job()
    j.id = 0
    j.backend = db
    db._parent = j

    name = str(tmpdir.join('submit_script'))
    with open(name, 'w') as fd:
        fd.write(script_template.replace('###PARAMETRIC_INPUTDATA###', str([['a'], ['b']])))

    with patch('GangaDirac.Lib.Backends.DiracBase.execute', return_value={}):
        db.id = 1234
        db.actualCE = 'test'
        db.status = 'test'
        with pytest.raises(BackendError):
            db._common_submit(name)

        assert db.id is None, 'id not None'
        assert db.actualCE is None, 'actualCE not None'
        assert db.status is None, 'status not None'

    with patch('GangaDirac.Lib.Backends.DiracBase.execute', return_value={'OK': True, 'Value': 12345}) as execute:
        assert db._common_submit(name)

        execute.assert_called_once_with("execfile('%s')" % name)

        assert db.id == 12345, 'id not set'

    with patch('GangaDirac.Lib.Backends.DiracBase.execute', return_value={'OK': True, 'Value': [123, 456]}):
        with patch.object(db, '_setup_bulk_subjobs') as _setup_bulk_subjobs:
            db._common_submit(name)
            _setup_bulk_subjobs.assert_called_once_with([123, 456], name)
开发者ID:MannyMoo,项目名称:ganga,代码行数:33,代码来源:TestDiracBase.py

示例12: setUp

 def setUp(self):
     warnings.simplefilter("ignore", Warning)
     self.readListFromSettingsMock = patch('ReText.window.readListFromSettings', return_value=[]).start()
     self.writeListToSettingsMock  = patch('ReText.window.writeListToSettings').start()
     self.writeToSettingsMock      = patch('ReText.window.writeToSettings').start()
     self.globalSettingsMock       = patch('ReText.window.globalSettings', MagicMock(**ReText.configOptions)).start()
     self.fileSystemWatcherMock    = patch('ReText.window.QFileSystemWatcher').start()
开发者ID:ahnan4arch,项目名称:retext,代码行数:7,代码来源:test_window.py

示例13: test_webhook_action_test

def test_webhook_action_test(client, data):
    url1 = reverse('webhooks-test', kwargs={"pk": data.webhook1.pk})
    url2 = reverse('webhooks-test', kwargs={"pk": data.webhook2.pk})
    blocked_url = reverse('webhooks-test', kwargs={"pk": data.blocked_webhook.pk})

    users = [
        None,
        data.registered_user,
        data.project_owner
    ]

    with mock.patch('taiga.webhooks.tasks._send_request') as _send_request_mock:
        _send_request_mock.return_value = data.webhooklog1
        results = helper_test_http_method(client, 'post', url1, None, users)
        assert results == [404, 404, 200]
        assert _send_request_mock.called is True

    with mock.patch('taiga.webhooks.tasks._send_request') as _send_request_mock:
        _send_request_mock.return_value = data.webhooklog1
        results = helper_test_http_method(client, 'post', url2, None, users)
        assert results == [404, 404, 404]
        assert _send_request_mock.called is False

    with mock.patch('taiga.webhooks.tasks._send_request') as _send_request_mock:
        _send_request_mock.return_value = data.webhooklog1
        results = helper_test_http_method(client, 'post', blocked_url, None, users)
        assert results == [404, 404, 451]
        assert _send_request_mock.called is False
开发者ID:shreeshreee,项目名称:taiga-back,代码行数:28,代码来源:test_webhooks_resources.py

示例14: test_edit_post

 def test_edit_post(self):
     perm = Permission.objects.get(codename='change_milestone') 
     self.admin.user_permissions.add(perm)
     with patch('traq.projects.forms.MilestoneForm.is_valid', return_value=True) as data:
         with patch('traq.projects.forms.MilestoneForm.save', return_value=True):
             response = self.client.post(reverse('milestones-edit', args=[self.milestone.pk,]))
     self.assertTrue(response.status_code, 302)
开发者ID:PSU-OIT-ARC,项目名称:traq,代码行数:7,代码来源:test_views.py

示例15: test_random_song

 def test_random_song(self):
     with mock.patch("pubbot.squeezecenter.receivers.command") as command:
         with mock.patch("random.choice") as choice:
             choice.side_effect = lambda x: x[0]
             r = receivers.random_song(None, content='random')
         command.assert_called_with("playlist loadtracks track.titlesearch=A")
     self.assertEqual(r['had_side_effect'], True)
开发者ID:pubbothq,项目名称:pubbot,代码行数:7,代码来源:test_receivers.py


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