1 //
2 // Copyright (C) 2023 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 #pragma once
18
19 #include <string.h>
20
21 #include <algorithm>
22 #include <string_view>
23
24 #include <gmock/gmock.h>
25 #include "transport.h"
26
27 class MockTransport : public Transport {
28 public:
29 MOCK_METHOD(ssize_t, Read, (void* data, size_t len), (override));
30 MOCK_METHOD(ssize_t, Write, (const void* data, size_t len), (override));
31 MOCK_METHOD(int, Close, (), (override));
32 MOCK_METHOD(int, Reset, (), (override));
33 };
34
35 class RawDataMatcher {
36 public:
RawDataMatcher(const char * data)37 explicit RawDataMatcher(const char* data) : data_(data) {}
RawDataMatcher(std::string_view data)38 explicit RawDataMatcher(std::string_view data) : data_(data) {}
39
MatchAndExplain(std::tuple<const void *,size_t> args,::testing::MatchResultListener *)40 bool MatchAndExplain(std::tuple<const void*, size_t> args,
41 ::testing::MatchResultListener*) const {
42 const void* expected_data = std::get<0>(args);
43 size_t expected_len = std::get<1>(args);
44 if (expected_len != data_.size()) {
45 return false;
46 }
47 return memcmp(expected_data, data_.data(), expected_len) == 0;
48 }
DescribeTo(std::ostream * os)49 void DescribeTo(std::ostream* os) const { *os << "raw data is"; }
DescribeNegationTo(std::ostream * os)50 void DescribeNegationTo(std::ostream* os) const { *os << "raw data is not"; }
51
52 private:
53 std::string_view data_;
54 };
55
56 template <typename T>
RawData(T data)57 static inline ::testing::PolymorphicMatcher<RawDataMatcher> RawData(T data) {
58 return ::testing::MakePolymorphicMatcher(RawDataMatcher(data));
59 }
60
CopyData(const char * source)61 static inline auto CopyData(const char* source) {
62 return [source](void* buffer, size_t size) -> ssize_t {
63 size_t to_copy = std::min(size, strlen(source));
64 memcpy(buffer, source, to_copy);
65 return to_copy;
66 };
67 };
68