blob: a1054df027427908077ae2ccf57193bf49701703 [file] [log] [blame]
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -08001// Copyright 2021 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
15#include <algorithm>
16#include <chrono>
17#include <filesystem>
18#include <fstream>
19#include <string>
20#include <thread>
21
22#include "gtest/gtest.h"
23#include "pw_assert/check.h"
24#include "pw_bytes/array.h"
25#include "pw_log/log.h"
26#include "pw_rpc/integration_testing.h"
27#include "pw_status/status.h"
28#include "pw_sync/binary_semaphore.h"
29#include "pw_thread_stl/options.h"
30#include "pw_transfer/client.h"
31#include "pw_transfer_test/test_server.raw_rpc.pb.h"
32
33namespace pw::transfer {
34namespace {
35
36using namespace std::chrono_literals;
37
38// TODO(hepler): Use more iterations when the pw_transfer synchronization issues
39// that make this flaky are fixed.
40constexpr int kIterations = 1;
41
42constexpr auto kData512 = bytes::Initialized<512>([](size_t i) { return i; });
43constexpr auto kData8192 = bytes::Initialized<8192>([](size_t i) { return i; });
44
45std::filesystem::path directory;
46
47// Reads the file that represents the transfer with the specific ID.
48std::string GetContent(uint32_t transfer_id) {
49 std::ifstream stream(directory / std::to_string(transfer_id),
50 std::ios::binary | std::ios::ate);
51 std::string contents(stream.tellg(), '\0');
52
53 stream.seekg(0, std::ios::beg);
54 PW_CHECK(stream.read(contents.data(), contents.size()));
55
56 return contents;
57}
58
59// Drops the null terminator from a string literal.
60template <size_t kLengthWithNull>
61ConstByteSpan AsByteSpan(const char (&data)[kLengthWithNull]) {
62 constexpr size_t kLength = kLengthWithNull - 1;
63 PW_CHECK_INT_EQ('\0', data[kLength], "Expecting null for last character");
64 return std::as_bytes(std::span(data, kLength));
65}
66
67constexpr ConstByteSpan AsByteSpan(ConstByteSpan data) { return data; }
68
Alexei Frolov22ee1142022-02-03 13:59:01 -080069thread::Options& TransferThreadOptions() {
70 static thread::stl::Options options;
71 return options;
72}
73
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -080074// Test fixture for pw_transfer tests. Clears the transfer files before and
75// after each test.
76class TransferIntegration : public ::testing::Test {
77 protected:
78 TransferIntegration()
Alexei Frolov22ee1142022-02-03 13:59:01 -080079 : transfer_thread_(chunk_buffer_, encode_buffer_),
80 system_thread_(TransferThreadOptions(), transfer_thread_),
81 client_(rpc::integration_test::client(),
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -080082 rpc::integration_test::kChannelId,
Alexei Frolov22ee1142022-02-03 13:59:01 -080083 transfer_thread_,
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -080084 256),
85 test_server_client_(rpc::integration_test::client(),
Alexei Frolov22ee1142022-02-03 13:59:01 -080086 rpc::integration_test::kChannelId) {
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -080087 ClearFiles();
88 }
89
90 ~TransferIntegration() {
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -080091 ClearFiles();
Alexei Frolov22ee1142022-02-03 13:59:01 -080092 transfer_thread_.Terminate();
93 system_thread_.join();
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -080094 }
95
96 // Sets the content of a transfer ID and returns a MemoryReader for that data.
97 template <typename T>
98 void SetContent(uint32_t transfer_id, const T& content) {
99 const ConstByteSpan data = AsByteSpan(content);
100 std::ofstream stream(directory / std::to_string(transfer_id),
101 std::ios::binary);
102 PW_CHECK(
103 stream.write(reinterpret_cast<const char*>(data.data()), data.size()));
104
105 sync::BinarySemaphore reload_complete;
106 rpc::RawUnaryReceiver call = test_server_client_.ReloadTransferFiles(
107 {}, [&reload_complete](ConstByteSpan, Status) {
108 reload_complete.release();
109 });
110 PW_CHECK(reload_complete.try_acquire_for(3s));
111 }
112
113 auto OnCompletion() {
114 return [this](Status status) {
115 last_status_ = status;
116 completed_.release();
117 };
118 }
119
120 // Checks that a read transfer succeeded and that the data matches the
121 // expected data.
122 void ExpectReadData(ConstByteSpan expected) {
123 ASSERT_EQ(WaitForCompletion(), OkStatus());
124 ASSERT_EQ(expected.size(), read_buffer_.size());
125
126 EXPECT_TRUE(std::equal(read_buffer_.begin(),
127 read_buffer_.end(),
128 std::as_bytes(std::span(expected)).begin()));
129 }
130
131 // Checks that a write transfer succeeded and that the written contents match.
132 void ExpectWriteData(uint32_t transfer_id, ConstByteSpan expected) {
133 ASSERT_EQ(WaitForCompletion(), OkStatus());
134
135 const std::string written = GetContent(transfer_id);
136 ASSERT_EQ(expected.size(), written.size());
137
138 ConstByteSpan bytes = std::as_bytes(std::span(written));
139 EXPECT_TRUE(std::equal(bytes.begin(), bytes.end(), expected.begin()));
140 }
141
142 // Waits for the transfer to complete and returns the status.
143 Status WaitForCompletion() {
144 PW_CHECK(completed_.try_acquire_for(3s));
145 return last_status_;
146 }
147
148 // Exact match the size of kData8192 to test filling the receiving buffer.
149 stream::MemoryWriterBuffer<kData8192.size()> read_buffer_;
150
151 Client& client() { return client_; }
152
153 private:
154 static void ClearFiles() {
155 for (const auto& entry : std::filesystem::directory_iterator(directory)) {
156 if (!entry.is_regular_file()) {
157 continue;
158 }
159
160 if (const std::string name = entry.path().filename().string();
161 std::all_of(name.begin(), name.end(), [](char c) {
162 return std::isdigit(c);
163 })) {
164 PW_LOG_DEBUG("Clearing transfer file %s", name.c_str());
165 std::filesystem::remove(entry.path());
166 }
167 }
168 }
169
Alexei Frolov22ee1142022-02-03 13:59:01 -0800170 std::byte chunk_buffer_[512];
171 std::byte encode_buffer_[512];
172 transfer::Thread<2, 2> transfer_thread_;
173 thread::Thread system_thread_;
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -0800174
175 Client client_;
176
177 pw_rpc::raw::TestServer::Client test_server_client_;
178 Status last_status_ = Status::Unknown();
179 sync::BinarySemaphore completed_;
Wyatt Hepler6f6b6a12021-11-24 13:45:48 -0800180};
181
182TEST_F(TransferIntegration, Read_UnknownId) {
183 SetContent(123, "hello");
184
185 ASSERT_EQ(OkStatus(), client().Read(456, read_buffer_, OnCompletion()));
186
187 EXPECT_EQ(Status::NotFound(), WaitForCompletion());
188}
189
190#define PW_TRANSFER_TEST_READ(name, content) \
191 TEST_F(TransferIntegration, Read_##name) { \
192 for (int i = 0; i < kIterations; ++i) { \
193 const ConstByteSpan data = AsByteSpan(content); \
194 SetContent(__LINE__, data); \
195 ASSERT_EQ(OkStatus(), \
196 client().Read(__LINE__, read_buffer_, OnCompletion())); \
197 ExpectReadData(data); \
198 read_buffer_.clear(); \
199 } \
200 } \
201 static_assert(true, "Semicolons are required")
202
203PW_TRANSFER_TEST_READ(Empty, "");
204PW_TRANSFER_TEST_READ(SingleByte_1, "\0");
205PW_TRANSFER_TEST_READ(SingleByte_2, "?");
206PW_TRANSFER_TEST_READ(SmallData, "hunter2");
207PW_TRANSFER_TEST_READ(LargeData, kData512);
208
209TEST_F(TransferIntegration, Write_UnknownId) {
210 constexpr std::byte kData[] = {std::byte{0}, std::byte{1}, std::byte{2}};
211 stream::MemoryReader reader(kData);
212
213 ASSERT_EQ(OkStatus(), client().Write(99, reader, OnCompletion()));
214 EXPECT_EQ(Status::NotFound(), WaitForCompletion());
215
216 SetContent(99, "something");
217 ASSERT_EQ(OkStatus(), client().Write(100, reader, OnCompletion()));
218 EXPECT_EQ(Status::NotFound(), WaitForCompletion());
219}
220
221#define PW_TRANSFER_TEST_WRITE(name, content) \
222 TEST_F(TransferIntegration, Write_##name) { \
223 for (int i = 0; i < kIterations; ++i) { \
224 SetContent(__LINE__, "This is junk data that should be overwritten!"); \
225 const ConstByteSpan data = AsByteSpan(content); \
226 stream::MemoryReader reader(data); \
227 ASSERT_EQ(OkStatus(), client().Write(__LINE__, reader, OnCompletion())); \
228 ExpectWriteData(__LINE__, data); \
229 } \
230 } \
231 static_assert(true, "Semicolons are required")
232
233PW_TRANSFER_TEST_WRITE(Empty, "");
234PW_TRANSFER_TEST_WRITE(SingleByte_1, "\0");
235PW_TRANSFER_TEST_WRITE(SingleByte_2, "?");
236PW_TRANSFER_TEST_WRITE(SmallData, "hunter2");
237PW_TRANSFER_TEST_WRITE(LargeData, kData512);
238
239} // namespace
240} // namespace pw::transfer
241
242int main(int argc, char* argv[]) {
243 if (!pw::rpc::integration_test::InitializeClient(argc, argv, "PORT DIRECTORY")
244 .ok()) {
245 return 1;
246 }
247
248 if (argc != 3) {
249 PW_LOG_INFO("Usage: %s PORT DIRECTORY", argv[0]);
250 return 1;
251 }
252
253 pw::transfer::directory = argv[2];
254
255 return RUN_ALL_TESTS();
256}