Python unittest.mock 模块,MagicMock() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用unittest.mock.MagicMock()

项目:postgis-t    作者:postgis-t    | 项目源码 | 文件源码
def test_intersection_com_mock_2(self):
        ls = LineString([(1, 1, 9.48024060e+08), (2, 2, 9.49363260e+08),
                         (3, 1, 9.51868860e+08)])

        poly = Polygon([(1, 1), (1, 3), (4, 3), (4, 1), (1, 1)])

        self.traj2.intersection_shapely = MagicMock(return_value=ls)
        response = self.traj2.intersection_shapely(poly)

        ls = np.array(ls)

        trajMock = self.traj2.to_Trajectory(response)
        traj = Trajectory(ls[:, 0], ls[:, 1], ls[:, 2])

        assert (np.array_equal(trajMock.getX(), traj.getX()))
        assert (np.array_equal(trajMock.getY(), traj.getY()))
        assert (np.array_equal(trajMock.getTime(), traj.getTime()))
项目:BioDownloader    作者:biomadeira    | 项目源码 | 文件源码
def test_fetch_from_url_or_retry_post_json(self):
        # mocked requests
        identifier = "1csb, 2pah"
        base_url = c.http_pdbe
        endpoint_url = "api/pdb/entry/summary/"
        response = response_mocker(kwargs={}, base_url=base_url,
                                   endpoint_url=endpoint_url,
                                   content_type='application/octet-stream',
                                   post=True, data=identifier)
        self.fetch_from_url_or_retry = MagicMock(return_value=response)
        url = base_url + endpoint_url + identifier
        r = self.fetch_from_url_or_retry(url, json=True, post=True, data=identifier,
                                         header={'application/octet-stream'},
                                         retry_in=None, wait=0,
                                         n_retries=10, stream=False).json()
        self.assertEqual(r, json.loads('{"data": "some json formatted output"}'))
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_talk_rate_command(self, talk_class_mock, send_rate_mock):
        messaging_event = self.generate_postback('rate talk 1')
        talk_mock = MagicMock(talk_id=1)
        talk_liked_mock = False
        talk_mock.is_liked_by = MagicMock(return_value=False)
        server.db_session.query(talk_class_mock).get = MagicMock(return_value=talk_mock)
        message_handlers.handle_talk_rate_command(messaging_event, self.access_token, server.db_session)
        talk_mock.is_liked_by.assert_called_once_with(
            self.sender_id,
            server.db_session
            )
        send_rate_mock.assert_called_once_with(
            self.access_token,
            self.sender_id,
            talk_mock,
            talk_liked_mock
            )
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_talk_like_command(self, talk_class_mock, send_like_confirmation_mock):
        messaging_event = self.generate_quick_reply('like talk 1')
        talk_mock = MagicMock(talk_id=1)
        talk_mock.revert_like = MagicMock()
        talk_liked_mock = False
        talk_mock.is_liked_by = MagicMock(return_value=talk_liked_mock)
        server.db_session.query(talk_class_mock).get = MagicMock(return_value=talk_mock)
        message_handlers.handle_talk_like_command(messaging_event, self.access_token, server.db_session)
        talk_mock.revert_like.assert_called_once_with(
            self.sender_id,
            server.db_session
            )
        send_like_confirmation_mock.assert_called_once_with(
            self.access_token,
            self.sender_id,
            talk_mock,
            talk_liked_mock
            )
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_schedule_command(self, talk_class_mock, send_schedule_mock):
        messaging_event = self.generate_postback('schedule payload')
        talks_mock = [MagicMock(talk_id=1), MagicMock(talk_id=2)]
        server.db_session.query().all = MagicMock(return_value=talks_mock)
        talk_like_numbers_mock = {}
        for mock_index, talk_mock in enumerate(talks_mock):
            talk_mock.id = mock_index
            talk_mock.count_likes = MagicMock(return_value=1)
            talk_like_numbers_mock[talk_mock.id] = 1
        talk_like_ids_mock = []
        message_handlers.handle_schedule_command(messaging_event, self.access_token, server.db_session)
        send_schedule_mock.assert_called_once_with(
            self.access_token,
            self.sender_id,
            talks_mock,
            talk_like_numbers_mock,
            talk_like_ids_mock  
            )
项目:tts-bug-bounty-dashboard    作者:18F    | 项目源码 | 文件源码
def call_runscheduler(loops=1, mock_call_command=None):
    ctx = {'sleep_count': 0}

    def fake_sleep(seconds):
        ctx['sleep_count'] += 1
        if ctx['sleep_count'] > loops:
            raise KeyboardInterrupt()

    if mock_call_command is None:
        mock_call_command = mock.MagicMock()

    with mock.patch.object(runscheduler, 'call_command', mock_call_command):
        with mock.patch.object(runscheduler, 'logger') as mock_logger:
            with mock.patch('time.sleep', fake_sleep):
                with pytest.raises(KeyboardInterrupt):
                    call_command('runscheduler')
            return mock_call_command, mock_logger
项目:rosie    作者:datasciencebr    | 项目源码 | 文件源码
def test_call(self, mocked_predict, mocked_load):
        mocked_load.return_value = 'model'
        settings = MagicMock()
        settings.UNIQUE_IDS = ['number']
        settings.CLASSIFIERS = {'answer': 42, 'another': 13}
        core = Core(settings, self.adapter)
        core.suspicions = MagicMock()
        core()

        # assert load and predict was called for each classifier
        mocked_load.assert_has_calls((call(42), call(13)), any_order=True)
        mocked_predict.assert_has_calls((
            call('model', 'answer'),
            call('model', 'another')
        ), any_order=True)

        # assert suspicions.xz was created
        expected_path = os.path.join('tmp', 'test', 'suspicions.xz')
        core.suspicions.to_csv.assert_called_once_with(
            expected_path,
            compression='xz',
            encoding='utf-8',
            index=False
        )
项目:hearthscan-bot    作者:d-schmidt    | 项目源码 | 文件源码
def test_AnswerMail_UserOnSpam(self):
        r = MagicMock()
        msg = MagicMock()
        msg.subreddit = None
        msg.author.name = 'user'
        msg.id = 'msgid'
        msg.distinguished = None
        pmUserCache = {'user' : 1234}

        helper = MagicMock()

        # test
        hsbot.answerPM(r, msg, pmUserCache, helper)

        self.assertEqual(r.method_calls, [], 'no reddit calls')
        self.assertEqual(helper.method_calls, [], 'no helper calls')
项目:hearthscan-bot    作者:d-schmidt    | 项目源码 | 文件源码
def test_AnswerMail_Success(self):
        r = MagicMock()

        msg = MagicMock()
        msg.subreddit = None
        msg.author.name = 'user'
        msg.id = 'msgid'
        msg.distinguished = None
        msg.subject = 'sub'
        msg.body = 'body'
        pmUserCache = { }

        helper = MagicMock()
        helper.parseText = MagicMock(return_value=(['card'], 'text'))

        # test
        hsbot.answerPM(r, msg, pmUserCache, helper)

        self.assertTrue('user' in pmUserCache, 'user added to cache')

        self.assertEqual(r.method_calls, [], 'no reddit calls')
        expected = [call.parseText('sub body')]
        self.assertEqual(helper.method_calls, expected, 'parseText')
        expected = [call.reply('text')]
        self.assertEqual(msg.method_calls, expected, 'reply')
项目:SanicMongo    作者:beepaste    | 项目源码 | 文件源码
def test_getattr_with_under(self, *args, **kwrags):
        connection = Mock(spec=core.SanicMongoAgnosticClient)
        delegate = MagicMock()
        delegate.name = 'blabla'
        connection.delegate = delegate
        name = 'blabla'
        db = create_class_with_framework(core.SanicMongoAgnosticDatabase,
                                         asyncio_framework,
                                         self.__module__)(connection, name)

        coll = create_class_with_framework(core.SanicMongoAgnosticCollection,
                                           asyncio_framework,
                                           self.__module__)
        coll = coll(db, name)

        self.assertEqual(coll._get_write_mode, coll.delegate._get_write_mode)
项目:SanicMongo    作者:beepaste    | 项目源码 | 文件源码
def test_getitem(self, *args, **kwargs):
        connection = Mock(spec=core.SanicMongoAgnosticClient)
        delegate = MagicMock()
        delegate.name = 'blabla'
        connection.delegate = delegate
        name = 'blabla'
        db = create_class_with_framework(core.SanicMongoAgnosticDatabase,
                                         asyncio_framework,
                                         self.__module__)(connection, name)

        coll = create_class_with_framework(core.SanicMongoAgnosticCollection,
                                           asyncio_framework,
                                           self.__module__)
        coll = coll(db, name)

        other_coll = coll['other']
        self.assertTrue(isinstance(other_coll, type(coll)))
项目:SanicMongo    作者:beepaste    | 项目源码 | 文件源码
def test_find(self, *args, **kwargs):
        connection = Mock(spec=core.SanicMongoAgnosticClient)
        delegate = MagicMock()
        delegate.name = 'blabla'
        connection.delegate = delegate
        name = 'blabla'
        db = create_class_with_framework(core.SanicMongoAgnosticDatabase,
                                         asyncio_framework,
                                         self.__module__)(connection, name)

        coll = create_class_with_framework(core.SanicMongoAgnosticCollection,
                                           asyncio_framework,
                                           self.__module__)(db, name)
        cursor = create_class_with_framework(core.SanicMongoAgnosticCursor,
                                             asyncio_framework,
                                             self.__module__)
        self.assertIsInstance(coll.find(), cursor)
项目:SanicMongo    作者:beepaste    | 项目源码 | 文件源码
def test_get_item(self, *args, **kwargs):
        connection = Mock(spec=core.SanicMongoAgnosticClient)
        delegate = MagicMock()
        connection.delegate = delegate
        name = 'blabla'
        db = create_class_with_framework(core.SanicMongoAgnosticDatabase,
                                         asyncio_framework,
                                         self.__module__)(connection, name)

        comp_coll = create_class_with_framework(
            core.SanicMongoAgnosticCollection,
            asyncio_framework,
            self.__module__)

        coll = db['bla']
        self.assertTrue(isinstance(coll, comp_coll))
项目:xavier    作者:bepress    | 项目源码 | 文件源码
def test_background_queue():
    publish_event = MagicMock()
    publish_event.return_value = 'aaa'

    task_queue = TaskQueue(publish_event)

    @task_queue.task()
    def funcy():
        global funcy_called
        funcy_called += 1
        return "blah"

    assert funcy() == "blah"

    assert funcy.delay() is True

    event = jsonpickle.dumps((funcy.path, (), {}))

    publish_event.assert_called_once_with(event)

    task_queue.process_event(event)
    assert funcy_called == 2
项目:python-ogn-client    作者:glidernet    | 项目源码 | 文件源码
def test_reset_kill_reconnect(self):
        client = AprsClient(aprs_user='testuser', aprs_filter='')
        client.connect()

        # .run() should be allowed to execute after .connect()
        mock_callback = mock.MagicMock(
            side_effect=lambda raw_msg: client.disconnect())

        self.assertFalse(client._kill)
        client.run(callback=mock_callback, autoreconnect=True)

        # After .disconnect(), client._kill should be True
        self.assertTrue(client._kill)
        self.assertEqual(mock_callback.call_count, 1)

        # After we reconnect, .run() should be able to run again
        mock_callback.reset_mock()
        client.connect()
        client.run(callback=mock_callback, autoreconnect=True)
        self.assertEqual(mock_callback.call_count, 1)
项目:pyaqara    作者:javefang    | 项目源码 | 文件源码
def test_handle_message_iam():
    """Test if a gateway is created and discover_devices is called with gateway IP
    after message "iam" is received"""

    src_addr = "10.10.10.10"
    msg_iam = {
        "cmd": "iam",
        "ip": src_addr,
        "sid": "123456"
    }

    mock_handler = MagicMock()
    client = AqaraClient()
    client.subscribe(mock_handler)

    client.handle_message(msg_iam, src_addr)

    assert len(client.gateways.keys()) == 1
    new_gateway = client.gateways["123456"]
    mock_handler.assert_called_once_with(
        sender=client,
        gateway=new_gateway,
        signal=AQARA_EVENT_NEW_GATEWAY
    )
项目:pyaqara    作者:javefang    | 项目源码 | 文件源码
def test_handle_message_device_list():
    """Test if client maps all sids to the gateway and call gateway.on_devices_discovered"""

    gw_addr = "10.10.10.10"
    gw_sid = "123456"
    msg_get_id_list_ack = {
        "cmd": "get_id_list_ack",
        "sid": gw_sid,
        "data": json.dumps(["1", "2", "3"])
    }

    mock_client = AqaraClient()
    mock_client.read_device = MagicMock()
    mock_gateway = AqaraGateway(mock_client, gw_sid, gw_addr, None)
    mock_client._gateways[gw_sid] = mock_gateway
    mock_gateway.on_devices_discovered = MagicMock()

    mock_client.handle_message(msg_get_id_list_ack, gw_addr)

    mock_gateway.on_devices_discovered.called_once_with(["1", "2", "3"])
    assert len(mock_client._device_to_gw.keys()) == 3
项目:pyaqara    作者:javefang    | 项目源码 | 文件源码
def test_handle_message_heartbeat():
    """Test if the gateway token is updated on a gateway heartbeat"""
    gw_addr = "10.10.10.10"
    gw_sid = "123456"
    mock_client = AqaraClient()
    mock_gateway = AqaraGateway(mock_client, gw_sid, gw_addr, None)
    mock_gateway.on_device_heartbeat = MagicMock()
    mock_client._gateways[gw_sid] = mock_gateway
    mock_client._device_to_gw[gw_sid] = mock_gateway
    msg_heartbeat = {
        "cmd": "heartbeat",
        "model": "gateway",
        "sid": gw_sid,
        "token": "ffffff",
        "data": json.dumps({"ip": gw_addr})
    }

    mock_client.handle_message(msg_heartbeat, gw_addr)

    mock_gateway.on_device_heartbeat.assert_called_once_with(
        "gateway", gw_sid, {"ip": gw_addr}, "ffffff"
    )
项目:heaviside    作者:jhuapl-boss    | 项目源码 | 文件源码
def test_run_activity_error(self, mCreateSession):
        iSession = MockSession()
        mCreateSession.return_value = (iSession, '123456')
        client = iSession.client('stepfunctions')

        target = mock.MagicMock()
        target.side_effect = ActivityError('error', 'cause')

        task = TaskMixin(process = target)
        task.handle_task('token', None)

        self.assertEqual(task.token, None)
        call = mock.call.send_task_failure(taskToken = 'token',
                                           error = 'error',
                                           cause = 'cause')
        self.assertEqual(client.mock_calls, [call])
项目:heaviside    作者:jhuapl-boss    | 项目源码 | 文件源码
def test_run_exception(self, mCreateSession):
        iSession = MockSession()
        mCreateSession.return_value = (iSession, '123456')
        client = iSession.client('stepfunctions')

        target = mock.MagicMock()
        target.side_effect = BossError('cause')

        task = TaskMixin(process = target)
        task.handle_task('token', None)

        self.assertEqual(task.token, None)
        call = mock.call.send_task_failure(taskToken = 'token',
                                           error = 'BossError',
                                           cause = 'cause')
        self.assertEqual(client.mock_calls, [call])
项目:postgis-t    作者:postgis-t    | 项目源码 | 文件源码
def test_intersection_com_mock(self):
        ls = LineString([(1.5, 1, 9.48024060e+08), (2, 2, 9.49363260e+08),
                         (3, 2, 9.51868860e+08), (4, 3, 9.53208060e+08)])

        poly = Polygon([(1, 1), (1, 3), (4, 3), (4, 1), (1, 1)])

        self.traj.intersection_shapely = MagicMock(return_value=ls)
        response = self.traj.intersection_shapely(poly)

        ls = np.array(ls)
        trajMock = self.traj.to_Trajectory(response)
        traj = Trajectory(ls[:, 0], ls[:, 1], ls[:, 2])

        assert (np.array_equal(trajMock.getX(), traj.getX()))
        assert (np.array_equal(trajMock.getY(), traj.getY()))
        assert (np.array_equal(trajMock.getTime(), traj.getTime()))
项目:EMFT    作者:132nd-etcher    | 项目源码 | 文件源码
def test_multiple_instances():

    # Reset all watchers
    Dummy.prop._watchers = []

    o1 = Dummy()
    o2 = Dummy()

    callback = MagicMock()

    Dummy.prop.add_watcher(callback)

    assert callback.call_count == 0
    o1.prop = 'test'
    assert callback.call_count == 1
    callback.assert_called_with('test')

    o2.prop = 'caribou'
    assert callback.call_count == 2
    callback.assert_called_with('caribou')

    o2.prop = 'caribou'
    assert callback.call_count == 2
项目:kafka-spark-influx-csv-analysis    作者:bwsw    | 项目源码 | 文件源码
def test_getExutor(self, mock_sparksession, mock_kafka_utils):
        mock_context = MagicMock()
        mock_context.addFile.return_value = "test"
        mock_spark = MagicMock()
        mock_spark.sparkContext.return_value = mock_context
        mock_builder = MagicMock()
        mock_builder.getOrCreate.return_value = mock_spark
        mock_sparksession.builder
        mock_sparksession.builder.return_value = mock_builder
        mock_dstream = MagicMock()
        mock_dstream.map.return_value = None
        mock_kafka_utils.createDirectStream.return_value = mock_dstream

        config = Config(CONFIG_PATH)
        factory = ReadFactory(config)
        test_executor = factory.get_executor()

        self.assertIsInstance(test_executor, StreamingExecutor,
                              "When read csv file executor should be instance of BatchExecutable")
项目:flash_services    作者:textbook    | 项目源码 | 文件源码
def test_define_services(uuid4):
    mock_service = mock.MagicMock()
    with mock.patch.dict(SERVICES, {'bar': mock_service}, clear=True):

        result = define_services([{'name': 'bar'}, {'name': 'baz'}])

    uuid4.assert_called_once_with()
    assert result == {uuid4().hex: mock_service.from_config.return_value}
项目:BioDownloader    作者:biomadeira    | 项目源码 | 文件源码
def test_fetch_from_url_or_retry_get_text(self):
        # mocked requests
        identifier = "P00439"
        base_url = c.http_uniprot
        endpoint_url = "{}.fasta".format(identifier)
        response = response_mocker(kwargs={"P00439.fasta"}, base_url=base_url,
                                   endpoint_url="",
                                   content_type='text/plain')
        self.fetch_from_url_or_retry = MagicMock(return_value=response)
        url = base_url + endpoint_url
        r = self.fetch_from_url_or_retry(url, json=True,
                                         header={'text/plain'}).content
        self.assertEqual(str(r, 'utf-8'),
                         "Some text-based content\n spanning multiple lines")
项目:BioDownloader    作者:biomadeira    | 项目源码 | 文件源码
def test_fetch_from_url_or_retry_get_json(self):
        # mocked requests
        identifier = "2pah"
        base_url = c.http_pdbe
        endpoint_url = "api/pdb/entry/summary/"
        response = response_mocker(kwargs={identifier}, base_url=base_url,
                                   endpoint_url=endpoint_url,
                                   content_type='application/json')
        self.fetch_from_url_or_retry = MagicMock(return_value=response)
        url = base_url + endpoint_url + identifier
        r = self.fetch_from_url_or_retry(url, json=True,
                                         header={'application/json'}).json()
        self.assertEqual(r, json.loads('{"data": "some json formatted output"}'))
项目:BioDownloader    作者:biomadeira    | 项目源码 | 文件源码
def test_fetch_from_url_or_retry_get_binary(self):
        # mocked requests
        identifier = "P00439"
        base_url = c.http_uniprot
        endpoint_url = "{}.fasta".format(identifier)
        response = response_mocker(kwargs={"P00439.fasta"}, base_url=base_url,
                                   endpoint_url="",
                                   content_type='application/octet-stream')
        self.fetch_from_url_or_retry = MagicMock(return_value=response)
        url = base_url + endpoint_url
        r = self.fetch_from_url_or_retry(url, json=True,
                                         header={'application/octet-stream'},
                                         retry_in=None, wait=0,
                                         n_retries=10, stream=False).content
        self.assertEqual(r, b"Some other binary stuff...")
项目:BioDownloader    作者:biomadeira    | 项目源码 | 文件源码
def test_fetch_from_url_or_retry_get_404(self):
        # mocked requests
        identifier = "P00439"
        base_url = c.http_uniprot
        endpoint_url = "{}.fasta".format(identifier)
        response = response_mocker(kwargs={"P00439.fasta"}, base_url=base_url,
                                   endpoint_url="",
                                   content_type='text/plain', status=404)
        self.fetch_from_url_or_retry = MagicMock(return_value=response)
        url = base_url + endpoint_url
        r = self.fetch_from_url_or_retry(url, json=True, header={'text/plain'},
                                         retry_in=None, wait=0,
                                         n_retries=10, stream=False)
        self.assertEqual(r.status_code, 404)
        self.assertFalse(r.ok)
项目:PlasoScaffolder    作者:ClaudiaSaxer    | 项目源码 | 文件源码
def testCreateSQLQueryModelWithUserInputNoError(self):
    """test method CreateEventModelWithUserInput"""

    fake_execution = fake_sqlite_query_execution.SQLQueryExecution(
        sql_query_data.SQLQueryData(has_error=False)
    )
    sql_query = 'SELECT createdDate FROM Users ORDER BY createdDate'
    name = 'Contact'
    with tempfile.TemporaryDirectory() as tmpdir:
      path = os.path.join(tmpdir, 'testfile')
      pathlib.Path(path).touch()

      output_handler = output_handler_file.OutputHandlerFile(
          path, file_handler.FileHandler(),
          confirm=True, confirm_amount_same=2, prompt_info=name)
      plugin_helper = fake_sqlite_plugin_helper.FakeSQLitePluginHelper(
          folder_exists=True)
      controller = sqlite_controller.SQLiteController(output_handler,
                                                      plugin_helper)
      controller.GetTimestamps = mock.MagicMock(return_value=([], []))
      actual = controller._CreateSQLQueryModelWithUserInput(sql_query, False,
                                                            fake_execution)
      prompt_output_actual = self._ReadFromFile(path)
      prompt_output_expected = (
          'The SQL query was ok.'
          'Do you want to name the query parse row:  ?'
          'Does the event  need customizing?'
          'Enter columns that are customizable [columnName,aliasName...] '
          'or [abort]'
          'Added: Failed: Contact'
          'Do you want to add more columns that are customizable?')

      expected = sql_query_model.SQLQueryModel(
          sql_query, name, [], [], False, 0)
      self.assertEqual(actual.name, '')
      self.assertEqual(expected.query, actual.query)
      self.assertEqual(prompt_output_expected, prompt_output_actual)
项目:PlasoScaffolder    作者:ClaudiaSaxer    | 项目源码 | 文件源码
def testCreateSQLQueryModelWithUserInputWithExamplesAndFourDataExamples(self):
    """test method CreateEventModelWithUserInput with examples"""

    fake_execution = fake_sqlite_query_execution.SQLQueryExecution(
        sql_query_data.SQLQueryData(
            has_error=False, data=['first', 'second', 'third', 'fourth'],
            columns=[type('columns', (object,), {'sql_column': 'id'}),
                     type('columns', (object,), {'sql_column': 'name'})])
    )
    sql_query = 'SELECT id from Users'
    name = 'Contact'
    with tempfile.TemporaryDirectory() as tmpdir:
      path = os.path.join(tmpdir, 'testfile')
      pathlib.Path(path).touch()

      output_handler = output_handler_file.OutputHandlerFile(
          path, file_handler.FileHandler(),
          confirm=True, confirm_amount_same=2, prompt_info=name)
      plugin_helper = fake_sqlite_plugin_helper.FakeSQLitePluginHelper(
          folder_exists=True)
      controller = sqlite_controller.SQLiteController(output_handler,
                                                      plugin_helper)
      controller.GetTimestamps = mock.MagicMock(return_value=([], []))
      actual = controller._CreateSQLQueryModelWithUserInput(sql_query, True,
                                                            fake_execution)
      prompt_output_actual = self._ReadFromFile(path)
      prompt_output_expected = ('Your query output could look like this.'
                                '[\'id\', \'name\']'
                                'first'
                                'second'
                                'third'
                                'Do you want to add this query?'
                                'Do you want to name the query parse row:  ?'
                                'Does the event  need customizing?')

      expected = sql_query_model.SQLQueryModel(sql_query, name, [], [], False,
                                               0)

      self.assertEqual(actual.name, '')
      self.assertEqual(expected.query, actual.query)
      self.assertEqual(prompt_output_expected, prompt_output_actual)
项目:PlasoScaffolder    作者:ClaudiaSaxer    | 项目源码 | 文件源码
def testCreateSQLQueryModelWithUserInputWithExamplesAndTwoDataExamples(self):
    """test method CreateEventModelWithUserInput with examples"""

    fake_execution = fake_sqlite_query_execution.SQLQueryExecution(
        sql_query_data.SQLQueryData(
            has_error=False, data=['first', 'second'],
            columns=[type('columns', (object,), {'sql_column': 'id'}),
                     type('columns', (object,), {'sql_column': 'name'})])
    )
    sql_query = 'SELECT id from Users'
    name = 'Contact'
    with tempfile.TemporaryDirectory() as tmpdir:
      path = os.path.join(tmpdir, 'testfile')
      pathlib.Path(path).touch()

      output_handler = output_handler_file.OutputHandlerFile(
          path, file_handler.FileHandler(),
          confirm=True, confirm_amount_same=2, prompt_info=name)
      plugin_helper = fake_sqlite_plugin_helper.FakeSQLitePluginHelper(
          folder_exists=True)
      controller = sqlite_controller.SQLiteController(output_handler,
                                                      plugin_helper)
      controller.GetTimestamps = mock.MagicMock(return_value=([], []))
      actual = controller._CreateSQLQueryModelWithUserInput(sql_query, True,
                                                            fake_execution)
      prompt_output_actual = self._ReadFromFile(path)
      prompt_output_expected = ('Your query output could look like this.'
                                '[\'id\', \'name\']'
                                'first'
                                'second'
                                'Do you want to add this query?'
                                'Do you want to name the query parse row:  ?'
                                'Does the event  need customizing?')

      expected = sql_query_model.SQLQueryModel(
          sql_query, name, [], [], False, 0)

      self.assertEqual(actual.name, '')
      self.assertEqual(expected.query, actual.query)
      self.assertEqual(prompt_output_expected, prompt_output_actual)
项目:PlasoScaffolder    作者:ClaudiaSaxer    | 项目源码 | 文件源码
def testCreateSQLQueryModelWithUserInputWithExamplesAndOneDataExamples(self):
    """test method CreateEventModelWithUserInput with examples"""

    fake_execution = fake_sqlite_query_execution.SQLQueryExecution(
        sql_query_data.SQLQueryData(
            has_error=False, data=['first'],
            columns=[type('columns', (object,), {'sql_column': 'id'}),
                     type('columns', (object,), {'sql_column': 'name'})])
    )
    sql_query = 'SELECT id from Users'
    name = 'Contact'
    with tempfile.TemporaryDirectory() as tmpdir:
      path = os.path.join(tmpdir, 'testfile')
      pathlib.Path(path).touch()

      output_handler = output_handler_file.OutputHandlerFile(
          path, file_handler.FileHandler(),
          confirm=True, confirm_amount_same=2, prompt_info=name)
      plugin_helper = fake_sqlite_plugin_helper.FakeSQLitePluginHelper(
          folder_exists=True)
      controller = sqlite_controller.SQLiteController(output_handler,
                                                      plugin_helper)
      controller.GetTimestamps = mock.MagicMock(return_value=([], []))
      actual = controller._CreateSQLQueryModelWithUserInput(sql_query, True,
                                                            fake_execution)
      prompt_output_actual = self._ReadFromFile(path)
      prompt_output_expected = ('Your query output could look like this.'
                                '[\'id\', \'name\']'
                                'first'
                                'Do you want to add this query?'
                                'Do you want to name the query parse row:  ?'
                                'Does the event  need customizing?')

      expected = sql_query_model.SQLQueryModel(sql_query, name, [], [], False,
                                               0)

      self.assertEqual(actual.name, '')
      self.assertEqual(expected.query, actual.query)
      self.assertEqual(prompt_output_expected, prompt_output_actual)
项目:PlasoScaffolder    作者:ClaudiaSaxer    | 项目源码 | 文件源码
def testSqlQuery(self):
    """test method after getting the source path from the user"""
    with tempfile.TemporaryDirectory() as tmpdir:
      path = os.path.join(tmpdir, 'testfile')
      pathlib.Path(path).touch()

      output_handler = output_handler_file.OutputHandlerFile(
          path, file_handler.FileHandler(), confirm=False)
      plugin_helper = fake_sqlite_plugin_helper.FakeSQLitePluginHelper()
      controller = sqlite_controller.SQLiteController(output_handler,
                                                      plugin_helper)

      controller._CreateSQLQueryModelWithUserInput = mock.MagicMock(
          return_value=sql_query_data.SQLQueryData(
              data='test', has_error=False, error_message=None))

      actual = controller.SQLQuery(None, None, True)

      prompt_output_actual = self._ReadFromFile(path)

      prompt_output_expected = ('Please write your SQL script for the plugin'
                                'Do you want to add another Query?')

      self.assertEqual(len(actual), 1)
      self.assertEqual(actual[0].data, 'test')
      self.assertEqual(actual[0].has_error, False)
      self.assertEqual(actual[0].error_message, None)
      self.assertEqual(prompt_output_actual, prompt_output_expected)
项目:PlasoScaffolder    作者:ClaudiaSaxer    | 项目源码 | 文件源码
def testSqlQueryWithAbort(self):
    """test method after getting the source path from the user using abort"""
    with tempfile.TemporaryDirectory() as tmpdir:
      path = os.path.join(tmpdir, 'testfile')
      pathlib.Path(path).touch()

      output_handler = output_handler_file.OutputHandlerFile(
          path, file_handler.FileHandler(), prompt_info='abort', confirm=True,
          confirm_amount_same=2)
      plugin_helper = fake_sqlite_plugin_helper.FakeSQLitePluginHelper()
      controller = sqlite_controller.SQLiteController(output_handler,
                                                      plugin_helper)

      controller._CreateSQLQueryModelWithUserInput = mock.MagicMock(
          return_value=sql_query_model.SQLQueryModel(
              'query', 'name', None, None, True, 0))

      actual = controller.SQLQuery(None, None, True)

      prompt_output_actual = self._ReadFromFile(path)
      prompt_output_expected = (
          'Please write your SQL script for the plugin'
          'Do you want to add another Query?'
          'Please write your SQL script for the plugin [\'abort\' to continue]')

      self.assertEqual(len(actual), 1)
      self.assertEqual(actual[0].query, 'query')
      self.assertEqual(prompt_output_actual, prompt_output_expected)
项目:PlasoScaffolder    作者:ClaudiaSaxer    | 项目源码 | 文件源码
def testSqlQueryMultiple(self):
    """test method after getting the source path from the user"""
    with tempfile.TemporaryDirectory() as tmpdir:
      path = os.path.join(tmpdir, 'testfile')
      pathlib.Path(path).touch()

      output_handler = output_handler_file.OutputHandlerFile(
          path, file_handler.FileHandler(), confirm=True, confirm_amount_same=2)
      plugin_helper = fake_sqlite_plugin_helper.FakeSQLitePluginHelper()
      controller = sqlite_controller.SQLiteController(output_handler,
                                                      plugin_helper)

      controller._CreateSQLQueryModelWithUserInput = mock.MagicMock(
          return_value=sql_query_data.SQLQueryData(
              data='test', has_error=False, error_message=None))

      actual = controller.SQLQuery(None, None, True)

      prompt_output_expected = (
          'Please write your SQL script for the plugin'
          'Do you want to add another Query?'
          'Please write your SQL script for the plugin [\'abort\' to continue]'
          'Do you want to add another Query?'
          'Please write your SQL script for the plugin [\'abort\' to continue]'
          'Do you want to add another Query?'
      )
      prompt_output_actual = self._ReadFromFile(path)

    self.assertEqual(len(actual), 3)
    self.assertEqual(actual[0].data, 'test')
    self.assertEqual(actual[0].has_error, False)
    self.assertEqual(actual[0].error_message, None)
    self.assertEqual(actual[1].data, 'test')
    self.assertEqual(actual[1].has_error, False)
    self.assertEqual(actual[1].error_message, None)
    self.assertEqual(actual[2].data, 'test')
    self.assertEqual(actual[2].has_error, False)
    self.assertEqual(actual[2].error_message, None)

    self.assertEqual(prompt_output_actual, prompt_output_expected)
项目:python-devtools    作者:samuelcolvin    | 项目源码 | 文件源码
def test_call_args_py35():
    m = MagicMock()
    m(1, 2, 3, a=4)
    v = pformat(m.call_args)

    assert v == """\
_Call(
    (1, 2, 3),
    {'a': 4},
)"""
项目:python-devtools    作者:samuelcolvin    | 项目源码 | 文件源码
def test_call_args_py36():
    m = MagicMock()
    m(1, 2, 3, a=4)
    v = pformat(m.call_args)

    assert v == """\
_Call(
    _fields=(1, 2, 3),
    {'a': 4},
)"""
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def setUp(self):
        self.db_session = MagicMock()
        self.like_mock = MagicMock()
        self.user_id = 1
        self.talk_id = 1
        self.talk = Talk(id=self.talk_id)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_set_like(self, like_class_mock):
        like_class_mock.return_value = self.like_mock
        self.talk.is_liked_by = MagicMock(return_value=False)
        self.talk.set_like(self.user_id, self.db_session)
        like_class_mock.assert_called_once_with(user_facebook_id=self.user_id, talk_id=self.talk_id)
        self.db_session.add.assert_called_once_with(self.like_mock)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_unset_like(self):
        self.talk.is_liked_by = MagicMock(return_value=True)
        scalar_mock = MagicMock(return_value=self.like_mock)
        self.db_session.query().filter_by().scalar = scalar_mock
        self.talk.unset_like(self.user_id, self.db_session)
        self.db_session.delete.assert_called_once_with(self.like_mock)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def setUp(self):
        self.access_token = 1
        self.sender_id = 'USER_ID'

        server.app.config['ACCESS_TOKEN'] = self.access_token
        self.app = server.app.test_client()
        server.engine = MagicMock()
        server.Session = MagicMock()
        server.db_session = MagicMock()
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_talk_info_command_gets_called(self, message_handlers_mock):
        message_handlers_mock.handle_talk_info_command = MagicMock()
        known_input = self.generate_postback('info talk 1')
        self.app.post('/', data=json.dumps(known_input), content_type='application/json')
        number_of_calls = message_handlers_mock.handle_talk_info_command.call_count
        self.assertEqual(number_of_calls, 1)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_talk_like_command_gets_called(self, message_handlers_mock):
        message_handlers_mock.handle_talk_like_command = MagicMock()
        known_input = self.generate_quick_reply('like talk 1')
        self.app.post('/', data=json.dumps(known_input), content_type='application/json')
        number_of_calls = message_handlers_mock.handle_talk_like_command.call_count
        self.assertEqual(number_of_calls, 1)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_no_ask_question_url_postback_gets_called(self, message_handlers_mock):
        message_handlers_mock.handle_no_ask_question_url_postback = MagicMock()
        known_input = self.generate_postback('ask question no url')
        self.app.post('/', data=json.dumps(known_input), content_type='application/json')
        number_of_calls = message_handlers_mock.handle_no_ask_question_url_postback.call_count
        self.assertEqual(number_of_calls, 1)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_schedule_command_gets_called(self, message_handlers_mock):
        message_handlers_mock.handle_schedule_command = MagicMock()
        known_input = self.generate_quick_reply('schedule payload')
        self.app.post('/', data=json.dumps(known_input), content_type='application/json')
        number_of_calls = message_handlers_mock.handle_schedule_command.call_count
        self.assertEqual(number_of_calls, 1)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_speaker_auth_gets_called(self, message_handlers_mock):
        message_handlers_mock.handle_speaker_auth = MagicMock()
        known_input = self.generate_simple_text_message()
        self.app.post('/', data=json.dumps(known_input), content_type='application/json')
        number_of_calls = message_handlers_mock.handle_speaker_auth.call_count
        self.assertEqual(number_of_calls, 1)
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def setUp(self):
        self.access_token = 1
        self.sender_id = 'USER_ID'
        server.app.config['ACCESS_TOKEN'] = self.access_token
        server.engine = MagicMock()
        server.Session = MagicMock()
        server.db_session = MagicMock()
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def test_handle_speaker_auth(self, speaker_class_mock, send_authentication_confirmation_mock):
        messaging_event = self.generate_simple_text_message()
        speaker_mock = MagicMock()
        server.db_session.query().filter_by().scalar = MagicMock(return_value=speaker_mock)
        speaker_mock.page_scoped_id = None
        speaker_mock.name = 'asdaf'
        message_handlers.handle_speaker_auth(messaging_event, self.access_token, server.db_session)
        send_authentication_confirmation_mock.assert_called_once_with(
            self.access_token, 
            self.sender_id,
            speaker_mock.name
            )
项目:meetup-facebook-bot    作者:Stark-Mountain    | 项目源码 | 文件源码
def create_mockup_talk(self):
        talk_mock = MagicMock(id=1, title=1, speaker_facebook_id=1)
        talk_mock.is_liked_by = MagicMock(return_value=False)
        return talk_mock