1 // Copyright 2020 The Pigweed Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 4 // use this file except in compliance with the License. You may obtain a copy of 5 // the License at 6 // 7 // https://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 12 // License for the specific language governing permissions and limitations under 13 // the License. 14 #pragma once 15 16 #include <cstdint> 17 #include <cstring> 18 #include <span> 19 20 #include "pw_rpc/internal/method.h" 21 #include "pw_rpc/internal/method_union.h" 22 #include "pw_rpc/internal/packet.h" 23 #include "pw_rpc/server_context.h" 24 #include "pw_status/status_with_size.h" 25 26 namespace pw::rpc::internal { 27 28 // This is a fake RPC method implementation for testing only. It stores the 29 // channel ID, request, and payload buffer, and optionally provides a response. 30 class TestMethod : public Method { 31 public: TestMethod(uint32_t id)32 constexpr TestMethod(uint32_t id) 33 : Method(id, InvokeForTest), last_channel_id_(0) {} 34 last_channel_id()35 uint32_t last_channel_id() const { return last_channel_id_; } last_request()36 const Packet& last_request() const { return last_request_; } 37 set_response(std::span<const std::byte> payload)38 void set_response(std::span<const std::byte> payload) { response_ = payload; } set_status(Status status)39 void set_status(Status status) { response_status_ = status; } 40 41 private: InvokeForTest(const Method & method,ServerCall & call,const Packet & request)42 static void InvokeForTest(const Method& method, 43 ServerCall& call, 44 const Packet& request) { 45 const auto& test_method = static_cast<const TestMethod&>(method); 46 test_method.last_channel_id_ = call.channel().id(); 47 test_method.last_request_ = request; 48 } 49 50 // Make these mutable so they can be set in the Invoke method, which is const. 51 // The Method class is used exclusively in tests. Having these members mutable 52 // allows tests to verify that the Method is invoked correctly. 53 mutable uint32_t last_channel_id_; 54 mutable Packet last_request_; 55 56 std::span<const std::byte> response_; 57 Status response_status_; 58 }; 59 60 class TestMethodUnion : public MethodUnion { 61 public: TestMethodUnion(TestMethod && method)62 constexpr TestMethodUnion(TestMethod&& method) : impl_({.test = method}) {} 63 method()64 constexpr const Method& method() const { return impl_.method; } test_method()65 constexpr const TestMethod& test_method() const { return impl_.test; } 66 67 private: 68 union { 69 Method method; 70 TestMethod test; 71 } impl_; 72 }; 73 74 } // namespace pw::rpc::internal 75