mock_connection.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #ifndef LIBHDFSPP_TEST_MOCK_CONNECTION_H_
  19. #define LIBHDFSPP_TEST_MOCK_CONNECTION_H_
  20. #include "common/async_stream.h"
  21. #include <asio/error_code.hpp>
  22. #include <asio/buffer.hpp>
  23. #include <asio/streambuf.hpp>
  24. #include <asio/io_service.hpp>
  25. #include <gmock/gmock.h>
  26. namespace hdfs {
  27. class MockConnectionBase : public AsyncStream{
  28. public:
  29. MockConnectionBase(::asio::io_service *io_service);
  30. virtual ~MockConnectionBase();
  31. typedef std::pair<asio::error_code, std::string> ProducerResult;
  32. void async_read_some(const MutableBuffers &buf,
  33. std::function<void (const asio::error_code & error,
  34. std::size_t bytes_transferred) > handler) override {
  35. if (produced_.size() == 0) {
  36. ProducerResult r = Produce();
  37. if (r.first) {
  38. io_service_->post(std::bind(handler, r.first, 0));
  39. return;
  40. }
  41. asio::mutable_buffers_1 data = produced_.prepare(r.second.size());
  42. asio::buffer_copy(data, asio::buffer(r.second));
  43. produced_.commit(r.second.size());
  44. }
  45. size_t len = std::min(asio::buffer_size(buf), produced_.size());
  46. asio::buffer_copy(buf, produced_.data());
  47. produced_.consume(len);
  48. io_service_->post(std::bind(handler, asio::error_code(), len));
  49. }
  50. void async_write_some(const ConstBuffers &buf,
  51. std::function<void (const asio::error_code & error,
  52. std::size_t bytes_transferred) > handler) override {
  53. // CompletionResult res = OnWrite(buf);
  54. io_service_->post(std::bind(handler, asio::error_code(), asio::buffer_size(buf)));
  55. }
  56. protected:
  57. virtual ProducerResult Produce() = 0;
  58. ::asio::io_service *io_service_;
  59. private:
  60. asio::streambuf produced_;
  61. };
  62. }
  63. #endif