Remove FakeNearbyConnection.

PiperOrigin-RevId: 707200594
This commit is contained in:
Francis Tsui
2024-12-17 12:19:08 -08:00
committed by Copybara-Service
parent 2e027e9524
commit f0caa45bbc
10 changed files with 549 additions and 490 deletions
+8 -3
View File
@@ -361,12 +361,10 @@ cc_library(
name = "test_support",
testonly = True,
srcs = [
"fake_nearby_connection.cc",
"fake_nearby_connections_manager.cc",
"fake_nearby_sharing_service.cc",
],
hdrs = [
"fake_nearby_connection.h",
"fake_nearby_connections_manager.h",
"fake_nearby_sharing_service.h",
],
@@ -441,7 +439,9 @@ cc_test(
size = "small",
srcs = ["paired_key_verification_runner_test.cc"],
deps = [
":connection_types",
":incoming_frame_reader",
":nearby_connection_impl",
":paired_key_verification_runner",
":test_support",
":types",
@@ -553,6 +553,7 @@ cc_test(
deps = [
":attachments",
":connection_types",
":nearby_connection_impl",
":nearby_sharing_service",
":share_session",
":test_support",
@@ -561,7 +562,6 @@ cc_test(
":types",
"//base:casts",
"//internal/analytics:mock_event_logger",
"//internal/auth:auth_status_util",
"//internal/flags:nearby_flags",
"//internal/platform/implementation:signin_attempt",
"//internal/platform/implementation/g3", # fixdeps: keep
@@ -588,6 +588,7 @@ cc_test(
"//sharing/proto:share_cc_proto",
"//sharing/proto:wire_format_cc_proto",
"@com_github_protobuf_matchers//protobuf-matchers",
"@com_google_absl//absl/base:core_headers",
"@com_google_absl//absl/memory",
"@com_google_absl//absl/status",
"@com_google_absl//absl/strings",
@@ -752,6 +753,8 @@ cc_test(
name = "share_session_test",
srcs = ["share_session_test.cc"],
deps = [
":connection_types",
":nearby_connection_impl",
":paired_key_verification_runner",
":share_session",
":test_support",
@@ -800,6 +803,7 @@ cc_test(
deps = [
":attachments",
":connection_types",
":nearby_connection_impl",
":paired_key_verification_runner",
":share_session",
":test_support",
@@ -828,6 +832,7 @@ cc_test(
":attachment_compare",
":attachments",
":connection_types",
":nearby_connection_impl",
":paired_key_verification_runner",
":share_session",
":test_support",
-134
View File
@@ -1,134 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "sharing/fake_nearby_connection.h"
#include <stdint.h>
#include <functional>
#include <optional>
#include <queue>
#include <utility>
#include <vector>
#include "absl/synchronization/mutex.h"
#include "internal/platform/task_runner.h"
#include "sharing/internal/public/logging.h"
namespace nearby {
namespace sharing {
FakeNearbyConnection::FakeNearbyConnection(TaskRunner* task_runner)
: task_runner_(task_runner) {}
FakeNearbyConnection::~FakeNearbyConnection() = default;
void FakeNearbyConnection::Read(
std::function<void(std::optional<std::vector<uint8_t>> bytes)> callback) {
NL_DCHECK(!closed_);
{
absl::MutexLock lock(&read_mutex_);
callback_ = std::move(callback);
}
MaybeRunCallback();
}
void FakeNearbyConnection::Write(std::vector<uint8_t> bytes) {
NL_DCHECK(!closed_);
absl::MutexLock lock(&write_mutex_);
write_data_.push(std::move(bytes));
}
void FakeNearbyConnection::Close() {
NL_DCHECK(!closed_);
closed_ = true;
{
if (task_runner_) {
task_runner_->PostTask([this]() {
absl::MutexLock lock(&disconnect_mutex_);
if (disconnect_listener_) {
std::move(disconnect_listener_)();
}
});
return;
}
absl::MutexLock lock(&disconnect_mutex_);
if (disconnect_listener_) {
std::move(disconnect_listener_)();
}
}
absl::MutexLock lock(&read_mutex_);
if (callback_) {
has_read_callback_been_run_ = true;
auto callback = std::move(callback_);
callback_ = nullptr;
callback(std::nullopt);
}
}
void FakeNearbyConnection::SetDisconnectionListener(
std::function<void()> listener) {
NL_DCHECK(!closed_);
absl::MutexLock lock(&disconnect_mutex_);
disconnect_listener_ = std::move(listener);
}
void FakeNearbyConnection::AppendReadableData(std::vector<uint8_t> bytes) {
NL_DCHECK(!closed_);
if (task_runner_) {
task_runner_->PostTask([this, bytes = std::move(bytes)]() {
{
absl::MutexLock lock(&read_mutex_);
read_data_.push(std::move(bytes));
}
MaybeRunCallback();
});
return;
}
{
absl::MutexLock lock(&read_mutex_);
read_data_.push(std::move(bytes));
}
MaybeRunCallback();
}
std::vector<uint8_t> FakeNearbyConnection::GetWrittenData() {
absl::MutexLock lock(&write_mutex_);
if (write_data_.empty()) return {};
std::vector<uint8_t> bytes = std::move(write_data_.front());
write_data_.pop();
return bytes;
}
bool FakeNearbyConnection::IsClosed() { return closed_; }
void FakeNearbyConnection::MaybeRunCallback() {
NL_DCHECK(!closed_);
std::vector<uint8_t> item;
std::function<void(std::optional<std::vector<uint8_t>> bytes)> callback;
{
absl::MutexLock lock(&read_mutex_);
if (!callback_ || read_data_.empty()) return;
item = std::move(read_data_.front());
read_data_.pop();
callback = std::move(callback_);
callback_ = nullptr;
has_read_callback_been_run_ = true;
}
callback(std::move(item));
}
} // namespace sharing
} // namespace nearby
-75
View File
@@ -1,75 +0,0 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef THIRD_PARTY_NEARBY_SHARING_FAKE_NEARBY_CONNECTION_H_
#define THIRD_PARTY_NEARBY_SHARING_FAKE_NEARBY_CONNECTION_H_
#include <stdint.h>
#include <functional>
#include <optional>
#include <queue>
#include <vector>
#include "absl/base/thread_annotations.h"
#include "absl/synchronization/mutex.h"
#include "internal/platform/task_runner.h"
#include "sharing/nearby_connection.h"
namespace nearby {
namespace sharing {
class FakeNearbyConnection : public NearbyConnection {
public:
explicit FakeNearbyConnection(TaskRunner* task_runner = nullptr);
~FakeNearbyConnection() override;
// NearbyConnection:
void Read(std::function<void(std::optional<std::vector<uint8_t>> bytes)>
callback) override;
void Write(std::vector<uint8_t> bytes) override;
void Close() override;
void SetDisconnectionListener(std::function<void()> listener) override;
void AppendReadableData(std::vector<uint8_t> bytes)
ABSL_LOCKS_EXCLUDED(read_mutex_);
std::vector<uint8_t> GetWrittenData();
bool IsClosed();
bool has_read_callback_been_run() {
absl::MutexLock lock(&read_mutex_);
return has_read_callback_been_run_;
}
private:
void MaybeRunCallback() ABSL_LOCKS_EXCLUDED(read_mutex_);
bool closed_ = false;
TaskRunner* const task_runner_;
absl::Mutex read_mutex_;
bool has_read_callback_been_run_ ABSL_GUARDED_BY(read_mutex_) = false;
std::function<void(std::optional<std::vector<uint8_t>> bytes)> callback_
ABSL_GUARDED_BY(read_mutex_);
std::queue<std::vector<uint8_t>> read_data_ ABSL_GUARDED_BY(read_mutex_);
absl::Mutex write_mutex_;
std::queue<std::vector<uint8_t>> write_data_ ABSL_GUARDED_BY(write_mutex_);
absl::Mutex disconnect_mutex_;
std::function<void()> disconnect_listener_ ABSL_GUARDED_BY(disconnect_mutex_);
};
} // namespace sharing
} // namespace nearby
#endif // THIRD_PARTY_NEARBY_SHARING_FAKE_NEARBY_CONNECTION_H_
+12 -1
View File
@@ -115,12 +115,23 @@ void FakeNearbyConnectionsManager::Connect(
DCHECK(!is_shutdown());
connected_data_usage_ = data_usage;
transport_type_ = transport_type;
connection_endpoint_infos_.emplace(endpoint_id, std::move(endpoint_info));
{
absl::MutexLock lock(&endpoints_mutex_);
connection_endpoint_infos_.emplace(endpoint_id, std::move(endpoint_info));
}
std::move(callback)(connection_, Status::kUnknown);
}
void FakeNearbyConnectionsManager::AcceptConnection(
std::vector<uint8_t> endpoint_info, absl::string_view endpoint_id,
NearbyConnection* connection) {
absl::MutexLock lock(&endpoints_mutex_);
connection_endpoint_infos_.emplace(endpoint_id, std::move(endpoint_info));
}
void FakeNearbyConnectionsManager::Disconnect(absl::string_view endpoint_id) {
DCHECK(!is_shutdown());
absl::MutexLock lock(&endpoints_mutex_);
connection_endpoint_infos_.erase(std::string(endpoint_id));
}
+9 -1
View File
@@ -121,6 +121,7 @@ class FakeNearbyConnectionsManager : public NearbyConnectionsManager {
std::optional<std::vector<uint8_t>> connection_endpoint_info(
absl::string_view endpoint_id) {
absl::MutexLock lock(&endpoints_mutex_);
auto it = connection_endpoint_infos_.find(std::string(endpoint_id));
if (it == connection_endpoint_infos_.end()) return std::nullopt;
@@ -136,6 +137,11 @@ class FakeNearbyConnectionsManager : public NearbyConnectionsManager {
GetUnknownFilePathsToDeleteForTesting();
void AddUnknownFilePathsToDeleteForTesting(std::filesystem::path file_path);
// Add `connection` to list of connections as if it was accepted.
void AcceptConnection(std::vector<uint8_t> endpoint_info,
absl::string_view endpoint_id,
NearbyConnection* connection);
private:
void HandleStartAdvertisingCallback(ConnectionsStatus status);
void HandleStopAdvertisingCallback(ConnectionsStatus status);
@@ -166,8 +172,10 @@ class FakeNearbyConnectionsManager : public NearbyConnectionsManager {
ConnectionsCallback pending_start_advertising_callback_;
std::string custom_save_path_;
absl::Mutex endpoints_mutex_;
// Maps endpoint_id to endpoint_info.
std::map<std::string, std::vector<uint8_t>> connection_endpoint_infos_;
std::map<std::string, std::vector<uint8_t>> connection_endpoint_infos_
ABSL_GUARDED_BY(endpoints_mutex_);
std::map<int64_t, std::weak_ptr<PayloadStatusListener>>
payload_status_listeners_;
+66 -16
View File
@@ -19,6 +19,7 @@
#include <limits>
#include <memory>
#include <optional>
#include <queue>
#include <string>
#include <utility>
#include <vector>
@@ -31,14 +32,15 @@
#include "internal/analytics/mock_event_logger.h"
#include "internal/analytics/sharing_log_matchers.h"
#include "internal/test/fake_clock.h"
#include "internal/test/fake_device_info.h"
#include "internal/test/fake_task_runner.h"
#include "proto/sharing_enums.pb.h"
#include "sharing/analytics/analytics_recorder.h"
#include "sharing/attachment_compare.h" // IWYU pragma: keep
#include "sharing/fake_nearby_connection.h"
#include "sharing/fake_nearby_connections_manager.h"
#include "sharing/file_attachment.h"
#include "sharing/internal/public/logging.h"
#include "sharing/nearby_connection_impl.h"
#include "sharing/nearby_connections_types.h"
#include "sharing/paired_key_verification_runner.h"
#include "sharing/proto/analytics/nearby_sharing_log.pb.h"
@@ -114,7 +116,8 @@ std::unique_ptr<Payload> CreateWifiCredentialsPayload(
class IncomingShareSessionTest : public ::testing::Test {
protected:
IncomingShareSessionTest()
: session_(&clock_, task_runner_, &connections_manager_,
: connection_(device_info_, &connections_manager_, kEndpointId),
session_(&clock_, task_runner_, &connections_manager_,
analytics_recorder_, std::string(kEndpointId), share_target_,
transfer_metadata_callback_.AsStdFunction()) {
CHECK(
@@ -189,8 +192,9 @@ class IncomingShareSessionTest : public ::testing::Test {
ShareTarget share_target_;
MockFunction<void(const IncomingShareSession&, const TransferMetadata&)>
transfer_metadata_callback_;
FakeDeviceInfo device_info_;
FakeNearbyConnectionsManager connections_manager_;
FakeNearbyConnection connection_;
NearbyConnectionImpl connection_;
IncomingShareSession session_;
IntroductionFrame introduction_frame_;
int64_t payload_id1_;
@@ -295,6 +299,8 @@ TEST_F(IncomingShareSessionTest, ProcessIntroductionSuccess) {
TEST_F(IncomingShareSessionTest,
PayloadTransferUpdateCompleteWithWrongPayloadType) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -389,11 +395,15 @@ TEST_F(IncomingShareSessionTest,
.GetWifiCredentialsAttachments()[1]
.is_hidden(),
IsFalse());
EXPECT_THAT(connection_.IsClosed(), IsFalse());
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
}
TEST_F(IncomingShareSessionTest,
PayloadTransferUpdateCompleteWithMissingFilePayloads) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -487,11 +497,15 @@ TEST_F(IncomingShareSessionTest,
.GetWifiCredentialsAttachments()[1]
.is_hidden(),
IsFalse());
EXPECT_THAT(connection_.IsClosed(), IsFalse());
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
}
TEST_F(IncomingShareSessionTest,
PayloadTransferUpdateCompleteWithMissingTextPayloads) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -583,11 +597,15 @@ TEST_F(IncomingShareSessionTest,
.GetWifiCredentialsAttachments()[1]
.is_hidden(),
IsFalse());
EXPECT_THAT(connection_.IsClosed(), IsFalse());
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
}
TEST_F(IncomingShareSessionTest,
PayloadTransferUpdateCompleteWithMissingWifiPayloads) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -680,7 +698,9 @@ TEST_F(IncomingShareSessionTest,
.GetWifiCredentialsAttachments()[1]
.is_hidden(),
IsFalse());
EXPECT_THAT(connection_.IsClosed(), IsFalse());
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
}
TEST_F(IncomingShareSessionTest, GetPayloadFilePaths) {
@@ -742,6 +762,8 @@ TEST_F(IncomingShareSessionTest, GetPayloadFilePaths) {
}
TEST_F(IncomingShareSessionTest, PayloadTransferUpdateCompleteWithSuccess) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -832,10 +854,14 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateCompleteWithSuccess) {
.GetWifiCredentialsAttachments()[1]
.is_hidden(),
IsTrue());
EXPECT_THAT(connection_.IsClosed(), IsFalse());
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
}
TEST_F(IncomingShareSessionTest, PayloadTransferUpdateCancelled) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -888,7 +914,9 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateCancelled) {
EXPECT_THAT(
session_.attachment_container().GetFileAttachments()[1].file_path(),
Eq(file2_path));
EXPECT_THAT(connection_.IsClosed(), IsFalse());
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
}
TEST_F(IncomingShareSessionTest, PayloadTransferUpdateFailed) {
@@ -927,6 +955,8 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateFailed) {
}
TEST_F(IncomingShareSessionTest, PayloadTransferUpdateInProgress) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -973,7 +1003,9 @@ TEST_F(IncomingShareSessionTest, PayloadTransferUpdateInProgress) {
EXPECT_THAT(metadata.has_value(), IsTrue());
EXPECT_THAT(*metadata, HasStatus(TransferMetadata::Status::kInProgress));
EXPECT_THAT(connection_.IsClosed(), IsFalse());
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
}
TEST_F(IncomingShareSessionTest, ReadyForTransferNotConnected) {
@@ -1085,6 +1117,8 @@ TEST_F(IncomingShareSessionTest, AcceptTransferNotReady) {
}
TEST_F(IncomingShareSessionTest, AcceptTransferSuccess) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_THAT(session_.ProcessIntroduction(introduction_frame_),
Eq(std::nullopt));
@@ -1108,6 +1142,13 @@ TEST_F(IncomingShareSessionTest, AcceptTransferSuccess) {
HasEventType(EventType::RECEIVE_ATTACHMENTS_START),
Property(&SharingLog::receive_attachments_start,
HasSessionId(1234)))))));
std::queue<std::vector<uint8_t>> frames_data;
connections_manager_.set_send_payload_callback(
[&](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
frames_data.push(std::move(payload->content.bytes_payload.bytes));
});
EXPECT_THAT(session_.AcceptTransfer([]() {}),
IsTrue());
@@ -1118,7 +1159,7 @@ TEST_F(IncomingShareSessionTest, AcceptTransferSuccess) {
.lock(),
Eq(session_.payload_tracker().lock()));
}
std::vector<uint8_t> frame_data = connection_.GetWrittenData();
std::vector<uint8_t> frame_data = frames_data.front();
Frame frame;
ASSERT_TRUE(frame.ParseFromArray(frame_data.data(), frame_data.size()));
ASSERT_EQ(frame.version(), Frame::V1);
@@ -1156,7 +1197,7 @@ TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultSuccess) {
std::vector<uint8_t> data;
data.resize(frame.ByteSizeLong());
EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue());
connection_.AppendReadableData(std::move(data));
connection_.WriteMessage(std::move(data));
EXPECT_THAT(introduction_received, IsTrue());
}
@@ -1189,7 +1230,7 @@ TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultFail) {
std::vector<uint8_t> data;
data.resize(frame.ByteSizeLong());
EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue());
connection_.AppendReadableData(std::move(data));
connection_.WriteMessage(std::move(data));
EXPECT_THAT(introduction_received, IsFalse());
}
@@ -1222,7 +1263,7 @@ TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultUnable) {
std::vector<uint8_t> data;
data.resize(frame.ByteSizeLong());
EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue());
connection_.AppendReadableData(std::move(data));
connection_.WriteMessage(std::move(data));
EXPECT_THAT(introduction_received, IsTrue());
}
@@ -1255,7 +1296,7 @@ TEST_F(IncomingShareSessionTest, ProcessKeyVerificationResultUnknown) {
std::vector<uint8_t> data;
data.resize(frame.ByteSizeLong());
EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue());
connection_.AppendReadableData(std::move(data));
connection_.WriteMessage(std::move(data));
EXPECT_THAT(introduction_received, IsFalse());
}
@@ -1307,13 +1348,22 @@ TEST_F(IncomingShareSessionTest, SendFailureResponseNotConnected) {
}
TEST_F(IncomingShareSessionTest, SendFailureResponseConnected) {
connections_manager_.AcceptConnection(
/*endpoint_info=*/{}, kEndpointId, &connection_);
session_.OnConnected(&connection_);
EXPECT_CALL(transfer_metadata_callback_,
Call(_, HasStatus(TransferMetadata::Status::kNotEnoughSpace)));
std::queue<std::vector<uint8_t>> frames_data;
connections_manager_.set_send_payload_callback(
[&](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
frames_data.push(std::move(payload->content.bytes_payload.bytes));
});
session_.SendFailureResponse(TransferMetadata::Status::kNotEnoughSpace);
std::vector<uint8_t> frame_data = connection_.GetWrittenData();
std::vector<uint8_t> frame_data = frames_data.front();
Frame frame;
ASSERT_TRUE(frame.ParseFromArray(frame_data.data(), frame_data.size()));
ASSERT_EQ(frame.version(), Frame::V1);
+241 -182
View File
@@ -24,6 +24,7 @@
#include <limits>
#include <memory>
#include <optional>
#include <queue>
#include <string>
#include <utility>
#include <vector>
@@ -32,10 +33,12 @@
#include "gmock/gmock.h"
#include "protobuf-matchers/protocol-buffer-matchers.h"
#include "gtest/gtest.h"
#include "absl/base/thread_annotations.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "absl/synchronization/notification.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
@@ -60,7 +63,6 @@
#include "sharing/constants.h"
#include "sharing/contacts/fake_nearby_share_contact_manager.h"
#include "sharing/contacts/nearby_share_contact_manager_impl.h"
#include "sharing/fake_nearby_connection.h"
#include "sharing/fake_nearby_connections_manager.h"
#include "sharing/fast_initiation/fake_nearby_fast_initiation.h"
#include "sharing/fast_initiation/nearby_fast_initiation_impl.h"
@@ -78,6 +80,7 @@
#include "sharing/internal/test/fake_wifi_adapter.h"
#include "sharing/local_device_data/fake_nearby_share_local_device_data_manager.h"
#include "sharing/local_device_data/nearby_share_local_device_data_manager_impl.h"
#include "sharing/nearby_connection_impl.h"
#include "sharing/nearby_connections_manager.h"
#include "sharing/nearby_connections_types.h"
#include "sharing/nearby_sharing_service.h"
@@ -385,6 +388,11 @@ std::unique_ptr<AttachmentContainer> CreateWifiCredentialAttachments(
class NearbySharingServiceImplTest : public testing::Test {
public:
struct PayloadInfo {
std::unique_ptr<Payload> payload;
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener> listener;
};
NearbySharingServiceImplTest() = default;
~NearbySharingServiceImplTest() override = default;
@@ -419,8 +427,26 @@ class NearbySharingServiceImplTest : public testing::Test {
auto fake_task_runner =
std::make_unique<FakeTaskRunner>(fake_context_.fake_clock(), 1);
sharing_service_task_runner_ = fake_task_runner.get();
connection_ =
std::make_unique<FakeNearbyConnection>(fake_task_runner.get());
fake_nearby_connections_manager_ = new FakeNearbyConnectionsManager();
connection_ = std::make_unique<NearbyConnectionImpl>(
fake_device_info_, fake_nearby_connections_manager_, kEndpointId);
fake_nearby_connections_manager_->set_send_payload_callback(
[this](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
// If there are no listeners, treat it as a control frame.
if (listener.use_count() == 0) {
auto frame = std::make_unique<Frame>();
std::vector<uint8_t> data =
std::move(payload->content.bytes_payload.bytes);
frame->ParseFromArray(data.data(), data.size());
absl::MutexLock lock(&connection_output_mutex_);
frames_data_.push(std::move(frame));
} else {
absl::MutexLock lock(&connection_output_mutex_);
written_payloads_.push(PayloadInfo(std::move(payload), listener));
}
});
SetBluetoothIsPresent(true);
SetBluetoothIsPowered(true);
SetScreenLocked(false);
@@ -432,6 +458,9 @@ class NearbySharingServiceImplTest : public testing::Test {
}
void TearDown() override {
if (connection_) {
connection_.reset();
}
Shutdown();
NearbyFlags::GetInstance().OverrideBoolFlagValue(
config_package_nearby::nearby_sharing_feature::kEnableMediumWifiLan,
@@ -453,7 +482,6 @@ class NearbySharingServiceImplTest : public testing::Test {
std::unique_ptr<NearbySharingServiceImpl> CreateService(
std::unique_ptr<FakeTaskRunner> task_runner) {
fake_nearby_connections_manager_ = new FakeNearbyConnectionsManager();
return std::make_unique<NearbySharingServiceImpl>(
std::move(task_runner), &fake_context_, mock_sharing_platform_,
absl::WrapUnique(fake_nearby_connections_manager_),
@@ -507,6 +535,13 @@ class NearbySharingServiceImplTest : public testing::Test {
FlushTesting();
}
void ReceiveMessageFromConnection(std::vector<uint8_t> bytes) {
sharing_service_task_runner_->PostTask([this, bytes]() {
connection_->WriteMessage(bytes);
});
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kWaitTimeout));
}
void FastForward(absl::Duration duration) {
fake_context_.fake_clock()->FastForward(duration);
FlushTesting();
@@ -517,6 +552,14 @@ class NearbySharingServiceImplTest : public testing::Test {
FlushTesting();
}
void StartIncomingConnection() {
std::vector<uint8_t> endpoint_info = CreateTestEndpointInfo();
fake_nearby_connections_manager_->AcceptConnection(
endpoint_info, kEndpointId, connection_.get());
service_->OnIncomingConnection(kEndpointId, endpoint_info,
connection_.get());
}
NearbySharingService::StatusCodes RegisterSendSurface(
TransferUpdateCallback* transfer_callback,
ShareTargetDiscoveredCallback* discovery_callback, SendSurfaceState state,
@@ -693,9 +736,7 @@ class NearbySharingServiceImplTest : public testing::Test {
v1_frame->set_allocated_paired_key_encryption(paired_key_encryption_frame);
std::vector<uint8_t> encryption_bytes(frame.ByteSizeLong());
frame.SerializeToArray(encryption_bytes.data(), encryption_bytes.size());
connection_->AppendReadableData(encryption_bytes);
FlushTesting();
ReceiveMessageFromConnection(std::move(encryption_bytes));
Frame result_frame;
result_frame.set_version(Frame::V1);
@@ -706,9 +747,7 @@ class NearbySharingServiceImplTest : public testing::Test {
paired_key_result_frame->set_status(status);
std::vector<uint8_t> result_bytes(result_frame.ByteSizeLong());
result_frame.SerializeToArray(result_bytes.data(), result_bytes.size());
connection_->AppendReadableData(result_bytes);
FlushTesting();
ReceiveMessageFromConnection(std::move(result_bytes));
}
std::vector<uint8_t> CreateTestEndpointInfo(uint8_t vendor_id = kVendorId) {
@@ -728,25 +767,21 @@ class NearbySharingServiceImplTest : public testing::Test {
}
std::vector<uint8_t> bytes(frame->ByteSizeLong());
frame->SerializeToArray(bytes.data(), bytes.size());
connection_->AppendReadableData(bytes);
FlushTesting();
ReceiveMessageFromConnection(std::move(bytes));
}
void SendConnectionResponse(ConnectionResponseFrame::Status status) {
std::unique_ptr<Frame> frame = GetConnectionResponseFrame(status);
std::vector<uint8_t> bytes(frame->ByteSizeLong());
frame->SerializeToArray(bytes.data(), bytes.size());
connection_->AppendReadableData(bytes);
FlushTesting();
ReceiveMessageFromConnection(std::move(bytes));
}
void SendCancel() {
std::unique_ptr<Frame> frame = GetCancelFrame();
std::vector<uint8_t> bytes(frame->ByteSizeLong());
frame->SerializeToArray(bytes.data(), bytes.size());
connection_->AppendReadableData(bytes);
FlushTesting();
ReceiveMessageFromConnection(std::move(bytes));
}
int64_t SetUpIncomingConnection(
@@ -754,7 +789,6 @@ class NearbySharingServiceImplTest : public testing::Test {
bool for_self_share = false) {
fake_nearby_connections_manager_->SetRawAuthenticationToken(kEndpointId,
GetToken());
SetUpIntroductionFrameDecoder(/*return_empty_introduction_frame=*/false);
int64_t share_target_id;
@@ -788,8 +822,7 @@ class NearbySharingServiceImplTest : public testing::Test {
SetUpBackgroundReceiveSurface(callback);
}
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true, for_self_share);
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kWaitTimeout));
@@ -860,22 +893,31 @@ class NearbySharingServiceImplTest : public testing::Test {
return discovered_target_id;
}
Frame GetWrittenFrame() {
std::unique_ptr<Frame> GetWrittenFrame() {
EXPECT_TRUE(
sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
std::vector<uint8_t> data = connection_->GetWrittenData();
Frame frame;
frame.ParseFromArray(data.data(), data.size());
absl::MutexLock lock(&connection_output_mutex_);
std::unique_ptr<Frame> frame = std::move(frames_data_.front());
frames_data_.pop();
return frame;
}
PayloadInfo GetWrittenPayload() {
EXPECT_TRUE(
sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
absl::MutexLock lock(&connection_output_mutex_);
PayloadInfo info = std::move(written_payloads_.front());
written_payloads_.pop();
return info;
}
bool ExpectPairedKeyEncryptionFrame() {
Frame frame = GetWrittenFrame();
if (!frame.has_v1()) {
std::unique_ptr<Frame> frame = GetWrittenFrame();
if (!frame->has_v1()) {
return false;
}
if (!frame.v1().has_paired_key_encryption()) {
if (!frame->v1().has_paired_key_encryption()) {
return false;
}
@@ -883,12 +925,12 @@ class NearbySharingServiceImplTest : public testing::Test {
}
bool ExpectPairedKeyResultFrame() {
Frame frame = GetWrittenFrame();
if (!frame.has_v1()) {
std::unique_ptr<Frame> frame = GetWrittenFrame();
if (!frame->has_v1()) {
return false;
}
if (!frame.v1().has_paired_key_result()) {
if (!frame->v1().has_paired_key_result()) {
return false;
}
@@ -896,16 +938,16 @@ class NearbySharingServiceImplTest : public testing::Test {
}
bool ExpectConnectionResponseFrame(ConnectionResponseFrame::Status status) {
Frame frame = GetWrittenFrame();
if (!frame.has_v1()) {
std::unique_ptr<Frame> frame = GetWrittenFrame();
if (!frame->has_v1()) {
return false;
}
if (!frame.v1().has_connection_response()) {
if (!frame->v1().has_connection_response()) {
return false;
}
if (status != frame.v1().connection_response().status()) {
if (status != frame->v1().connection_response().status()) {
return false;
}
@@ -913,25 +955,25 @@ class NearbySharingServiceImplTest : public testing::Test {
}
std::optional<IntroductionFrame> ExpectIntroductionFrame() {
Frame frame = GetWrittenFrame();
if (!frame.has_v1()) {
std::unique_ptr<Frame> frame = GetWrittenFrame();
if (!frame->has_v1()) {
return std::nullopt;
}
if (!frame.v1().has_introduction()) {
if (!frame->v1().has_introduction()) {
return std::nullopt;
}
return frame.v1().introduction();
return frame->v1().introduction();
}
bool ExpectCancelFrame() {
Frame frame = GetWrittenFrame();
if (!frame.has_v1()) {
std::unique_ptr<Frame> frame = GetWrittenFrame();
if (!frame->has_v1()) {
return false;
}
if (frame.v1().type() != V1Frame::CANCEL) {
if (frame->v1().type() != V1Frame::CANCEL) {
return false;
}
@@ -1003,25 +1045,8 @@ class NearbySharingServiceImplTest : public testing::Test {
}
}
struct PayloadInfo {
int64_t payload_id;
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener> listener;
};
PayloadInfo AcceptAndSendPayload(
MockTransferUpdateCallback& transfer_callback, int64_t share_target_id) {
PayloadInfo info = {};
fake_nearby_connections_manager_->set_send_payload_callback(
[&](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
ASSERT_TRUE(payload->content.is_bytes());
std::vector<uint8_t> bytes = payload->content.bytes_payload.bytes;
EXPECT_EQ(kTextPayload, std::string(bytes.begin(), bytes.end()));
info.payload_id = payload->id;
info.listener = listener;
});
// We're now waiting for the remote device to respond with the accept
// result.
ExpectTransferUpdates(transfer_callback, share_target_id,
@@ -1029,7 +1054,10 @@ class NearbySharingServiceImplTest : public testing::Test {
// Kick off send process by accepting the transfer from the remote device.
SendConnectionResponse(ConnectionResponseFrame::ACCEPT);
FlushTesting();
PayloadInfo info = GetWrittenPayload();
EXPECT_EQ(kTextPayload,
std::string(info.payload->content.bytes_payload.bytes.begin(),
info.payload->content.bytes_payload.bytes.end()));
return info;
}
@@ -1044,7 +1072,7 @@ class NearbySharingServiceImplTest : public testing::Test {
[] {});
auto payload_transfer_update = std::make_unique<PayloadTransferUpdate>(
info.payload_id, PayloadStatus::kSuccess,
info.payload->id, PayloadStatus::kSuccess,
/*total_bytes=*/strlen(kTextPayload),
/*bytes_transferred=*/strlen(kTextPayload));
if (auto listener = info.listener.lock()) {
@@ -1193,6 +1221,8 @@ class NearbySharingServiceImplTest : public testing::Test {
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
// connection has been closed, destroy it like the real connections manager.
connection_.reset();
EXPECT_FALSE(fake_nearby_connections_manager_->has_incoming_payloads());
// Remove test file.
@@ -1248,7 +1278,7 @@ class NearbySharingServiceImplTest : public testing::Test {
FakeNearbyShareCertificateManager::Factory certificate_manager_factory_;
std::unique_ptr<FakeNearbyFastInitiation::Factory>
nearby_fast_initiation_factory_;
std::unique_ptr<FakeNearbyConnection> connection_;
std::unique_ptr<NearbyConnectionImpl> connection_;
StrictMock<MockAppInfo>* mock_app_info_ = nullptr;
std::unique_ptr<analytics::AnalyticsRecorder> analytics_recorder_;
std::unique_ptr<NearbySharingServiceImpl> service_;
@@ -1256,6 +1286,11 @@ class NearbySharingServiceImplTest : public testing::Test {
std::function<void()> expect_transfer_updates_callback_;
FakeTaskRunner* sharing_service_task_runner_ = nullptr;
bool is_shutdown_ = false;
absl::Mutex connection_output_mutex_;
std::queue<std::unique_ptr<Frame>> frames_data_
ABSL_GUARDED_BY(connection_output_mutex_);
std::queue<PayloadInfo> written_payloads_
ABSL_GUARDED_BY(connection_output_mutex_);
};
struct ValidSendSurfaceTestData {
@@ -1586,7 +1621,9 @@ TEST_F(NearbySharingServiceImplTest,
int64_t share_target_id = SetUpIncomingConnection(callback);
ScopedReceiveSurface r(service_.get(), &callback);
AcceptConnection(callback, share_target_id, kEndpointId);
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
MockTransferUpdateCallback send_callback;
MockShareTargetDiscoveredCallback discovery_callback;
@@ -2436,8 +2473,7 @@ TEST_F(NearbySharingServiceImplTest, IncomingConnectionClosedAfterShutdown) {
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
Shutdown();
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout);
}
@@ -2461,9 +2497,12 @@ TEST_F(NearbySharingServiceImplTest,
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
sharing_service_task_runner_->PostTask([this]() { connection_->Close(); });
StartIncomingConnection();
sharing_service_task_runner_->PostTask([this]() {
connection_->Close();
// FakeNearbyConnectionsManager does not delete the connection on close.
connection_.reset();
});
sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout);
}
@@ -2475,17 +2514,28 @@ TEST_F(NearbySharingServiceImplTest,
SetConnectionType(ConnectionType::kWifi);
NiceMock<MockTransferUpdateCallback> callback;
EXPECT_CALL(callback, OnTransferUpdate(testing::_, testing::_, testing::_))
.Times(0);
.WillOnce(testing::Invoke([](const ShareTarget& share_target,
const AttachmentContainer& container,
TransferMetadata metadata) {
EXPECT_TRUE(metadata.is_final_status());
EXPECT_EQ(TransferMetadata::Status::kFailed,
metadata.status());
}));
SetUpKeyVerification(/*is_incoming=*/true,
service::proto::PairedKeyResultFrame::SUCCESS);
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
sharing_service_task_runner_->PostTask([this]() {
connection_->Close();
// FakeNearbyConnectionsManager does not delete the connection on close.
connection_.reset();
});
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
}
TEST_F(NearbySharingServiceImplTest, IncomingConnectionEmptyIntroductionFrame) {
@@ -2517,8 +2567,7 @@ TEST_F(NearbySharingServiceImplTest, IncomingConnectionEmptyIntroductionFrame) {
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
// Check data written to connection_.
@@ -2561,18 +2610,21 @@ TEST_F(NearbySharingServiceImplTest,
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/false);
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, IncomingConnectionTimedOut) {
NiceMock<MockTransferUpdateCallback> callback;
SetUpIncomingConnection(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
EXPECT_CALL(callback, OnTransferUpdate(testing::_, testing::_, testing::_))
.WillOnce(testing::Invoke([](const ShareTarget& share_target,
@@ -2586,7 +2638,9 @@ TEST_F(NearbySharingServiceImplTest, IncomingConnectionTimedOut) {
// Waits for delay to close connection.
FastForward(kIncomingRejectionDelay);
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest,
@@ -2603,7 +2657,11 @@ TEST_F(NearbySharingServiceImplTest,
EXPECT_EQ(metadata.status(), TransferMetadata::Status::kFailed);
}));
sharing_service_task_runner_->PostTask([this]() { connection_->Close(); });
sharing_service_task_runner_->PostTask([this]() {
connection_->Close();
// FakeNearbyConnectionsManager does not delete the connection on close.
connection_.reset();
});
sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout);
}
@@ -2631,8 +2689,7 @@ TEST_F(NearbySharingServiceImplTest, IncomingConnectionOutOfStorage) {
file_metadata->set_id(123);
std::vector<uint8_t> bytes(frame.ByteSizeLong());
frame.SerializeToArray(bytes.data(), bytes.size());
connection_->AppendReadableData(std::move(bytes));
FlushTesting();
ReceiveMessageFromConnection(std::move(bytes));
SetConnectionType(ConnectionType::kWifi);
NiceMock<MockTransferUpdateCallback> callback;
@@ -2658,8 +2715,7 @@ TEST_F(NearbySharingServiceImplTest, IncomingConnectionOutOfStorage) {
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
ResetDiskSpace();
@@ -2694,8 +2750,7 @@ TEST_F(NearbySharingServiceImplTest, IncomingConnectionFileSizeOverflow) {
file2_metadata->set_id(124);
std::vector<uint8_t> bytes(frame.ByteSizeLong());
frame.SerializeToArray(bytes.data(), bytes.size());
connection_->AppendReadableData(std::move(bytes));
FlushTesting();
ReceiveMessageFromConnection(std::move(bytes));
SetConnectionType(ConnectionType::kWifi);
NiceMock<MockTransferUpdateCallback> callback;
@@ -2719,8 +2774,7 @@ TEST_F(NearbySharingServiceImplTest, IncomingConnectionFileSizeOverflow) {
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
}
@@ -2762,13 +2816,14 @@ TEST_F(NearbySharingServiceImplTest,
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, AcceptInvalidShareTarget) {
@@ -2795,7 +2850,9 @@ TEST_F(NearbySharingServiceImplTest, AcceptValidShareTarget) {
EXPECT_TRUE(ExpectConnectionResponseFrame(
service::proto::ConnectionResponseFrame::ACCEPT));
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, AcceptValidShareTargetPayloadSuccessful) {
@@ -2876,6 +2933,7 @@ TEST_F(NearbySharingServiceImplTest,
EXPECT_TRUE(
success_notification.WaitForNotificationWithTimeout(kWaitTimeout));
FlushTesting();
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
@@ -2921,7 +2979,7 @@ TEST_F(NearbySharingServiceImplTest, AcceptValidShareTargetPayloadFailed) {
EXPECT_TRUE(
failure_notification.WaitForNotificationWithTimeout(kWaitTimeout));
FlushTesting();
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
@@ -2966,10 +3024,6 @@ TEST_F(NearbySharingServiceImplTest, AcceptValidShareTargetPayloadCancelled) {
}
EXPECT_TRUE(
failure_notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
EXPECT_FALSE(fake_nearby_connections_manager_->has_incoming_payloads());
// File deletion runs in a ThreadPool.
@@ -3017,7 +3071,9 @@ TEST_F(NearbySharingServiceImplTest, RejectValidShareTarget) {
EXPECT_TRUE(ExpectConnectionResponseFrame(ConnectionResponseFrame::REJECT));
FastForward(kIncomingRejectionDelay + kDelta);
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest,
@@ -3054,14 +3110,14 @@ TEST_F(NearbySharingServiceImplTest,
SetUpForegroundReceiveSurface(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest,
@@ -3103,14 +3159,14 @@ TEST_F(NearbySharingServiceImplTest,
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_TRUE(fake_nearby_connections_manager_->IsAdvertising());
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest,
@@ -3128,17 +3184,14 @@ TEST_F(NearbySharingServiceImplTest,
// Ensures that introduction is never received for failed key verification.
std::string intro = "introduction_frame";
std::vector<uint8_t> bytes(intro.begin(), intro.end());
connection_->AppendReadableData(bytes);
FlushTesting();
ReceiveMessageFromConnection(std::move(bytes));
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
EXPECT_CALL(callback,
OnTransferUpdate(
testing::_, testing::_,
nearby::sharing::HasStatus(
TransferMetadata::Status::kDeviceAuthenticationFailed)));
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
@@ -3146,7 +3199,9 @@ TEST_F(NearbySharingServiceImplTest,
// are processed prior to checking if connection is closed.
EXPECT_TRUE(
sharing_service_task_runner_->SyncWithTimeout(absl::Milliseconds(200)));
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest,
@@ -3161,23 +3216,25 @@ TEST_F(NearbySharingServiceImplTest,
// Ensures that introduction is never received for empty auth token.
std::string intro = "introduction_frame";
std::vector<uint8_t> bytes(intro.begin(), intro.end());
connection_->AppendReadableData(bytes);
FlushTesting();
ReceiveMessageFromConnection(std::move(bytes));
EXPECT_CALL(*mock_app_info_, SetActiveFlag());
service_->OnIncomingConnection(kEndpointId, CreateTestEndpointInfo(),
connection_.get());
StartIncomingConnection();
ProcessLatestPublicCertificateDecryption(/*expected_num_calls=*/1,
/*success=*/true);
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, RegisterReceiveSurfaceAlreadyReceiving) {
NiceMock<MockTransferUpdateCallback> callback;
SetUpIncomingConnection(callback);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
EXPECT_EQ(
RegisterReceiveSurface(
@@ -3395,7 +3452,9 @@ TEST_P(NearbySharingServiceImplSendFailureTest, SendTextRemoteFailure) {
SendConnectionResponse(GetParam().response_status);
EXPECT_TRUE(reject_notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, SendFileWithEmptyPath) {
@@ -3445,7 +3504,9 @@ TEST_P(NearbySharingServiceImplSendFailureTest, SendFilesRemoteFailure) {
SendConnectionResponse(GetParam().response_status);
EXPECT_TRUE(reject_notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, SendTextDisconnectTimeout) {
@@ -3510,12 +3571,14 @@ TEST_F(NearbySharingServiceImplTest, SendTextDisconnectTimeout) {
// Forward time until we send the disconnect request to Nearby
FastForward(kOutgoingDisconnectionDelay);
// Disconnect timeout calls FakeConnection::Close which does not call
// ConnectionsManager::Disconnect, so the FakeConnectionsManager still thinks
// the connection is open.
EXPECT_TRUE(
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
// FakeNearbyConnectionsManager does not destroy the connection.
sharing_service_task_runner_->PostTask([this]() {
connection_.reset();
});
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
account_manager().SetAccount(std::nullopt);
}
@@ -3537,25 +3600,19 @@ TEST_F(NearbySharingServiceImplTest, SendTextSuccessClosedConnection) {
.has_value());
// Call disconnect on the connection early before the timeout has passed.
sharing_service_task_runner_->PostTask([this]() { connection_->Close(); });
sharing_service_task_runner_->PostTask([this]() {
connection_->Close();
// FakeNearbyConnectionsManager does not destroy the connection.
connection_.reset();
});
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
// FakeConnection::Close does not call ConnectionsManager::Disconnect, so
// the FakeConnectionsManager still thinks the connection is open.
// Expect that we haven't called disconnect again as the endpoint is already
// disconnected.
EXPECT_TRUE(
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
// Make sure the scheduled disconnect callback does nothing.
FastForward(kOutgoingDisconnectionDelay);
// The disconnection_timeout_alarm should have been cancelled, so
// ConnectionsManager::Disconnect should not have been called.
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, SendFilesSuccess) {
@@ -3594,19 +3651,6 @@ TEST_F(NearbySharingServiceImplTest, SendFilesSuccess) {
EXPECT_EQ(test_data.size(), static_cast<size_t>(meta.size()));
EXPECT_EQ(meta.type(), FileMetadata::UNKNOWN);
// Expect the file payload to be sent in the end.
absl::Notification payload_notification;
fake_nearby_connections_manager_->set_send_payload_callback(
[&](std::unique_ptr<nearby::sharing::Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
ASSERT_TRUE(payload->content.is_file());
std::filesystem::path file = payload->content.file_payload.file.path;
ASSERT_TRUE(std::filesystem::exists(file));
payload_notification.Notify();
});
// We're now waiting for the remote device to respond with the accept
// result.
absl::Notification accept_notification;
@@ -3618,8 +3662,12 @@ TEST_F(NearbySharingServiceImplTest, SendFilesSuccess) {
SendConnectionResponse(ConnectionResponseFrame::ACCEPT);
EXPECT_TRUE(accept_notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_TRUE(
payload_notification.WaitForNotificationWithTimeout(kWaitTimeout));
// Expect the file payload to be sent in the end.
PayloadInfo info = GetWrittenPayload();
ASSERT_TRUE(info.payload->content.is_file());
std::filesystem::path file = info.payload->content.file_payload.file.path;
ASSERT_TRUE(std::filesystem::exists(file));
}
TEST_F(NearbySharingServiceImplTest, SendWifiCredentialsSuccess) {
@@ -3659,23 +3707,6 @@ TEST_F(NearbySharingServiceImplTest, SendWifiCredentialsSuccess) {
EXPECT_EQ(meta.security_type(),
service::proto::WifiCredentialsMetadata::WPA_PSK);
// Expect the wifi credential payload to be sent in the end.
absl::Notification payload_notification;
fake_nearby_connections_manager_->set_send_payload_callback(
[&](std::unique_ptr<nearby::sharing::Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
ASSERT_TRUE(payload->content.is_bytes());
std::vector<uint8_t> bytes = payload->content.bytes_payload.bytes;
nearby::sharing::service::proto::WifiCredentials wifi_credentials;
ASSERT_TRUE(
wifi_credentials.ParseFromArray(bytes.data(), bytes.size()));
EXPECT_EQ(wifi_credentials.password(), "password");
EXPECT_FALSE(wifi_credentials.hidden_ssid());
payload_notification.Notify();
});
// We're now waiting for the remote device to respond with the accept
// result.
absl::Notification accept_notification;
@@ -3687,8 +3718,15 @@ TEST_F(NearbySharingServiceImplTest, SendWifiCredentialsSuccess) {
SendConnectionResponse(ConnectionResponseFrame::ACCEPT);
EXPECT_TRUE(accept_notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_TRUE(
payload_notification.WaitForNotificationWithTimeout(kWaitTimeout));
// Expect the wifi credential payload to be sent in the end.
PayloadInfo info = GetWrittenPayload();
ASSERT_TRUE(info.payload->content.is_bytes());
std::vector<uint8_t> bytes = info.payload->content.bytes_payload.bytes;
nearby::sharing::service::proto::WifiCredentials wifi_credentials;
ASSERT_TRUE(wifi_credentials.ParseFromArray(bytes.data(), bytes.size()));
EXPECT_EQ(wifi_credentials.password(), "password");
EXPECT_FALSE(wifi_credentials.hidden_ssid());
}
TEST_F(NearbySharingServiceImplTest, CancelSenderInitiator) {
@@ -3717,7 +3755,7 @@ TEST_F(NearbySharingServiceImplTest, CancelSenderInitiator) {
EXPECT_EQ(metadata.status(), TransferMetadata::Status::kCancelled);
}));
EXPECT_FALSE(
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload_id));
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload->id));
// The initiator of the cancellation explicitly calls Cancel().
service_->Cancel(
target_id, [&](NearbySharingServiceImpl::StatusCodes status_code) {
@@ -3726,7 +3764,7 @@ TEST_F(NearbySharingServiceImplTest, CancelSenderInitiator) {
});
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_TRUE(
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload_id));
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload->id));
// After the TransferMetadata::Status::kCancelled update, we expect other
// classes to unregister the send surface.
@@ -3736,9 +3774,13 @@ TEST_F(NearbySharingServiceImplTest, CancelSenderInitiator) {
// then wait a few seconds before disconnecting to allow for processing on the
// other device.
EXPECT_TRUE(ExpectCancelFrame());
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
FastForward(kInitiatorCancelDelay);
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, CancelSenderNoninitiator) {
@@ -3761,16 +3803,19 @@ TEST_F(NearbySharingServiceImplTest, CancelSenderNoninitiator) {
notification.Notify();
}));
EXPECT_FALSE(
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload_id));
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload->id));
// The non-initiator of the cancellation processes a cancellation frame from
// the initiator.
SendCancel();
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
EXPECT_TRUE(
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload_id));
fake_nearby_connections_manager_->WasPayloadCanceled(info.payload->id));
// The non-initiator should close the connection immediately
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, CancelReceiverInitiator) {
@@ -3812,9 +3857,13 @@ TEST_F(NearbySharingServiceImplTest, CancelReceiverInitiator) {
// then wait a few seconds before disconnecting to allow for processing on the
// other device.
ASSERT_TRUE(ExpectCancelFrame());
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
FastForward(kInitiatorCancelDelay);
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, CancelReceiverNoninitiator) {
@@ -3841,11 +3890,14 @@ TEST_F(NearbySharingServiceImplTest, CancelReceiverNoninitiator) {
// the initiator.
SendCancel();
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(kWaitTimeout));
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
EXPECT_TRUE(
fake_nearby_connections_manager_->WasPayloadCanceled(kFilePayloadId));
// The non-initiator should close the connection immediately
EXPECT_TRUE(connection_->IsClosed());
EXPECT_FALSE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest,
@@ -3999,6 +4051,7 @@ TEST_F(NearbySharingServiceImplTest,
auto endpoint_info_rotated =
fake_nearby_connections_manager_->advertising_endpoint_info();
EXPECT_NE(endpoint_info_initial, endpoint_info_rotated);
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
}
TEST_F(NearbySharingServiceImplTest, OrderedEndpointDiscoveryEvents) {
@@ -4708,7 +4761,11 @@ TEST_F(NearbySharingServiceImplTest, SelfShareAutoAccept) {
ExpectPairedKeyResultFrame();
ExpectConnectionResponseFrame(ConnectionResponseFrame::ACCEPT);
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
FlushTesting();
}
TEST_F(NearbySharingServiceImplTest, SelfShareNoAutoAcceptInForeground) {
@@ -4732,7 +4789,9 @@ TEST_F(NearbySharingServiceImplTest, SelfShareNoAutoAcceptInForeground) {
ExpectPairedKeyResultFrame();
ExpectConnectionResponseFrame(ConnectionResponseFrame::ACCEPT);
EXPECT_FALSE(connection_->IsClosed());
EXPECT_TRUE(
fake_nearby_connections_manager_->connection_endpoint_info(kEndpointId)
.has_value());
}
TEST_F(NearbySharingServiceImplTest, ObserveAccountLoginAndLogout) {
@@ -4925,9 +4984,9 @@ TEST_F(NearbySharingServiceImplTest,
DeviceVisibility::DEVICE_VISIBILITY_SELF_SHARE);
NearbySharingService::StatusCodes result = RegisterReceiveSurface(
&callback, NearbySharingService::ReceiveSurfaceState::kBackground);
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
EXPECT_EQ(result, NearbySharingService::StatusCodes::kOk);
ScopedReceiveSurface r(service_.get(), &callback);
EXPECT_TRUE(sharing_service_task_runner_->SyncWithTimeout(kTaskWaitTimeout));
EXPECT_TRUE(fake_nearby_connections_manager_->IsAdvertising());
}
+85 -35
View File
@@ -30,14 +30,15 @@
#include "internal/analytics/sharing_log_matchers.h"
#include "internal/network/url.h"
#include "internal/test/fake_clock.h"
#include "internal/test/fake_device_info.h"
#include "internal/test/fake_task_runner.h"
#include "sharing/analytics/analytics_recorder.h"
#include "sharing/attachment_container.h"
#include "sharing/certificates/test_util.h"
#include "sharing/common/nearby_share_enums.h"
#include "sharing/fake_nearby_connection.h"
#include "sharing/fake_nearby_connections_manager.h"
#include "sharing/file_attachment.h"
#include "sharing/nearby_connection_impl.h"
#include "sharing/nearby_connections_manager.h"
#include "sharing/nearby_connections_types.h"
#include "sharing/nearby_file_handler.h"
@@ -117,7 +118,7 @@ class OutgoingShareSessionTest : public ::testing::Test {
session_.InitiateSendAttachments(std::move(attachment_container));
}
void ConnectionSuccess(FakeNearbyConnection* connection) {
void ConnectionSuccess(NearbyConnection* connection) {
EXPECT_CALL(mock_event_logger_,
Log(Matcher<const SharingLog&>(
AllOf((HasCategory(EventCategory::SENDING_EVENT),
@@ -137,6 +138,7 @@ class OutgoingShareSessionTest : public ::testing::Test {
transfer_metadata_callback_;
OutgoingShareSession session_;
FakeNearbyConnectionsManager connections_manager_;
FakeDeviceInfo device_info_;
TextAttachment text1_;
TextAttachment text2_;
FileAttachment file1_;
@@ -284,11 +286,17 @@ TEST_F(OutgoingShareSessionTest, ConnectNoDisableWifiHotspot) {
std::vector<uint8_t> bluetooth_mac_address = {5, 6, 7, 8};
file1_.set_size(1000000); // 1MB
InitSendAttachments(CreateDefaultAttachmentContainer());
NearbyConnectionImpl nearby_connection(device_info_, &connections_manager_,
kEndpointId);
connections_manager_.set_nearby_connection(&nearby_connection);
session_.Connect(endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/false,
[](NearbyConnection* connection, Status status) {});
session_.Connect(
endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/false,
[&nearby_connection](NearbyConnection* connection, Status status) {
EXPECT_THAT(connection, Eq(&nearby_connection));
});
EXPECT_THAT(connections_manager_.connected_data_usage(),
Eq(nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE));
@@ -305,11 +313,17 @@ TEST_F(OutgoingShareSessionTest, ConnectDisableWifiHotspot) {
std::vector<uint8_t> bluetooth_mac_address = {5, 6, 7, 8};
file1_.set_size(1000000); // 1MB
InitSendAttachments(CreateDefaultAttachmentContainer());
NearbyConnectionImpl nearby_connection(device_info_, &connections_manager_,
kEndpointId);
connections_manager_.set_nearby_connection(&nearby_connection);
session_.Connect(endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/true,
[](NearbyConnection* connection, Status status) {});
session_.Connect(
endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/true,
[&nearby_connection](NearbyConnection* connection, Status status) {
EXPECT_THAT(connection, Eq(&nearby_connection));
});
EXPECT_THAT(connections_manager_.connected_data_usage(),
Eq(nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE));
@@ -326,11 +340,16 @@ TEST_F(OutgoingShareSessionTest, OnConnectResultSuccessLogsSessionDuration) {
session_.set_session_id(1234);
std::vector<uint8_t> endpoint_info = {1, 2, 3, 4};
std::vector<uint8_t> bluetooth_mac_address = {5, 6, 7, 8};
session_.Connect(endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/false,
[](NearbyConnection* connection, Status status) {});
NearbyConnectionImpl nearby_connection(device_info_, &connections_manager_,
kEndpointId);
connections_manager_.set_nearby_connection(&nearby_connection);
session_.Connect(
endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/false,
[&nearby_connection](NearbyConnection* connection, Status status) {
EXPECT_THAT(connection, Eq(&nearby_connection));
});
fake_clock_.FastForward(absl::Seconds(10));
EXPECT_CALL(
mock_event_logger_,
@@ -344,8 +363,7 @@ TEST_F(OutgoingShareSessionTest, OnConnectResultSuccessLogsSessionDuration) {
SharingLogHasStatus(
EstablishConnectionStatus::CONNECTION_STATUS_SUCCESS)))))));
FakeNearbyConnection connection;
EXPECT_THAT(session_.OnConnectResult(&connection, Status::kSuccess),
EXPECT_THAT(session_.OnConnectResult(&nearby_connection, Status::kSuccess),
IsTrue());
}
@@ -354,7 +372,6 @@ TEST_F(OutgoingShareSessionTest, OnConnectResultFailureLogsSessionDuration) {
session_.set_session_id(1234);
std::vector<uint8_t> endpoint_info = {1, 2, 3, 4};
std::vector<uint8_t> bluetooth_mac_address = {5, 6, 7, 8};
session_.Connect(endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/false,
@@ -388,7 +405,8 @@ TEST_F(OutgoingShareSessionTest, SendIntroductionWithoutPayloads) {
TEST_F(OutgoingShareSessionTest, SendIntroductionSuccess) {
InitSendAttachments(CreateDefaultAttachmentContainer());
session_.set_session_id(1234);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
ConnectionSuccess(&connection);
std::vector<NearbyFileHandler::FileInfo> file_infos;
file_infos.push_back({
@@ -404,10 +422,16 @@ TEST_F(OutgoingShareSessionTest, SendIntroductionSuccess) {
(HasCategory(EventCategory::SENDING_EVENT),
HasEventType(EventType::SEND_INTRODUCTION),
Property(&SharingLog::send_introduction, HasSessionId(1234)))))));
std::vector<uint8_t> frame_data;
connections_manager_.set_send_payload_callback(
[&](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
frame_data = std::move(payload->content.bytes_payload.bytes);
});
EXPECT_THAT(session_.SendIntroduction([]() {}), IsTrue());
std::vector<uint8_t> frame_data = connection.GetWrittenData();
Frame frame;
ASSERT_THAT(frame.ParseFromArray(frame_data.data(), frame_data.size()),
IsTrue());
@@ -462,7 +486,8 @@ TEST_F(OutgoingShareSessionTest, SendIntroductionTimeout) {
std::vector<WifiCredentialsAttachment>{});
InitSendAttachments(std::move(container));
session_.set_session_id(1234);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
ConnectionSuccess(&connection);
session_.CreateTextPayloads();
EXPECT_CALL(
@@ -489,7 +514,8 @@ TEST_F(OutgoingShareSessionTest, SendIntroductionTimeoutCancelled) {
std::vector<WifiCredentialsAttachment>{});
InitSendAttachments(std::move(container));
session_.set_session_id(1234);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
ConnectionSuccess(&connection);
session_.CreateTextPayloads();
EXPECT_CALL(
@@ -525,7 +551,8 @@ TEST_F(OutgoingShareSessionTest, AcceptTransferNotConnected) {
}
TEST_F(OutgoingShareSessionTest, AcceptTransferNotReady) {
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
session_.set_session_id(1234);
ConnectionSuccess(&connection);
@@ -540,7 +567,8 @@ TEST_F(OutgoingShareSessionTest, AcceptTransferSuccess) {
std::vector<WifiCredentialsAttachment>{});
InitSendAttachments(std::move(container));
session_.set_session_id(1234);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
ConnectionSuccess(&connection);
session_.CreateTextPayloads();
EXPECT_CALL(
@@ -572,7 +600,7 @@ TEST_F(OutgoingShareSessionTest, AcceptTransferSuccess) {
std::vector<uint8_t> data;
data.resize(frame.ByteSizeLong());
EXPECT_THAT(frame.SerializeToArray(data.data(), data.size()), IsTrue());
connection.AppendReadableData(std::move(data));
connection.WriteMessage(std::move(data));
EXPECT_THAT(connection_response_received, IsTrue());
}
@@ -631,7 +659,8 @@ TEST_F(OutgoingShareSessionTest, HandleConnectionResponseTimeoutResponse) {
TEST_F(OutgoingShareSessionTest, HandleConnectionResponseAcceptResponse) {
ConnectionResponseFrame response;
response.set_status(ConnectionResponseFrame::ACCEPT);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
session_.set_session_id(1234);
ConnectionSuccess(&connection);
EXPECT_CALL(transfer_metadata_callback_,
@@ -692,7 +721,8 @@ TEST_F(OutgoingShareSessionTest, SendPayloadsDisableCancellationOptimization) {
HasEventType(EventType::SEND_ATTACHMENTS_START),
Property(&SharingLog::send_attachments_start,
HasSessionId(1234)))))));
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
ConnectionSuccess(&connection);
session_.SendPayloads(
@@ -735,7 +765,8 @@ TEST_F(OutgoingShareSessionTest, SendPayloadsEnableCancellationOptimization) {
HasEventType(EventType::SEND_ATTACHMENTS_START),
Property(&SharingLog::send_attachments_start,
HasSessionId(1234)))))));
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
ConnectionSuccess(&connection);
session_.SendPayloads(
@@ -779,7 +810,8 @@ TEST_F(OutgoingShareSessionTest, SendNextPayload) {
HasEventType(EventType::SEND_ATTACHMENTS_START),
Property(&SharingLog::send_attachments_start,
HasSessionId(1234)))))));
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
ConnectionSuccess(&connection);
session_.SendPayloads(
@@ -816,7 +848,8 @@ TEST_F(OutgoingShareSessionTest, SendNextPayload) {
}
TEST_F(OutgoingShareSessionTest, ProcessKeyVerificationResultFail) {
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
session_.set_session_id(1234);
ConnectionSuccess(&connection);
session_.SetTokenForTests("1234");
@@ -832,7 +865,8 @@ TEST_F(OutgoingShareSessionTest, ProcessKeyVerificationResultFail) {
}
TEST_F(OutgoingShareSessionTest, ProcessKeyVerificationResultSuccess) {
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
session_.set_session_id(1234);
ConnectionSuccess(&connection);
session_.SetTokenForTests("1234");
@@ -848,7 +882,8 @@ TEST_F(OutgoingShareSessionTest, ProcessKeyVerificationResultSuccess) {
}
TEST_F(OutgoingShareSessionTest, DelayCompleteMetadataReceiverDisconnect) {
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
session_.set_session_id(1234);
ConnectionSuccess(&connection);
TransferMetadata complete_metadata =
@@ -866,9 +901,20 @@ TEST_F(OutgoingShareSessionTest, DelayCompleteMetadataReceiverDisconnect) {
}
TEST_F(OutgoingShareSessionTest, DelayCompleteMetadataDisconnectTimeout) {
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
session_.set_session_id(1234);
std::vector<uint8_t> endpoint_info = {1, 2, 3, 4};
std::vector<uint8_t> bluetooth_mac_address = {5, 6, 7, 8};
session_.Connect(
endpoint_info, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
/*disable_wifi_hotspot=*/false,
[&](NearbyConnection* connection, Status status) {});
ConnectionSuccess(&connection);
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsTrue());
TransferMetadata complete_metadata =
TransferMetadataBuilder()
.set_status(TransferMetadata::Status::kComplete)
@@ -879,7 +925,10 @@ TEST_F(OutgoingShareSessionTest, DelayCompleteMetadataDisconnectTimeout) {
session_.DelayCompleteMetadata(complete_metadata);
session_.DisconnectionTimeout();
EXPECT_THAT(connection.IsClosed(), IsTrue());
// Verify that connection is closed.
EXPECT_THAT(
connections_manager_.connection_endpoint_info(kEndpointId).has_value(),
IsFalse());
}
TEST_F(OutgoingShareSessionTest, UpdateSessionForDedupWithCertificate) {
@@ -912,7 +961,8 @@ TEST_F(OutgoingShareSessionTest, UpdateSessionForDedupWithoutCertificate) {
TEST_F(OutgoingShareSessionTest, UpdateSessionForDedupConnectedIsNoOp) {
auto share_target_org = session_.share_target();
FakeNearbyConnection connection;
NearbyConnectionImpl connection(device_info_, &connections_manager_,
kEndpointId);
session_.set_session_id(1234);
ConnectionSuccess(&connection);
ShareTarget share_target2{
+34 -15
View File
@@ -20,6 +20,7 @@
#include <list>
#include <memory>
#include <optional>
#include <queue>
#include <tuple>
#include <utility>
#include <vector>
@@ -30,15 +31,18 @@
#include "absl/time/time.h"
#include "internal/platform/task_runner.h"
#include "internal/test/fake_clock.h"
#include "internal/test/fake_device_info.h"
#include "internal/test/fake_task_runner.h"
#include "proto/sharing_enums.pb.h"
#include "sharing/certificates/fake_nearby_share_certificate_manager.h"
#include "sharing/certificates/nearby_share_decrypted_public_certificate.h"
#include "sharing/certificates/test_util.h"
#include "sharing/fake_nearby_connection.h"
#include "sharing/fake_nearby_connections_manager.h"
#include "sharing/incoming_frames_reader.h"
#include "sharing/internal/public/logging.h"
#include "sharing/nearby_connection.h"
#include "sharing/nearby_connection_impl.h"
#include "sharing/nearby_connections_types.h"
#include "sharing/proto/enums.pb.h"
#include "sharing/proto/rpc_resources.pb.h"
#include "sharing/proto/wire_format.pb.h"
@@ -51,6 +55,7 @@ using V1Frame = ::nearby::sharing::service::proto::V1Frame;
using PairedKeyResultFrame =
::nearby::sharing::service::proto::PairedKeyResultFrame;
using ::nearby::sharing::proto::DeviceVisibility;
using ::nearby::sharing::service::proto::Frame;
using PairedKeyVerificationResult =
PairedKeyVerificationRunner::PairedKeyVerificationResult;
using ::location::nearby::proto::sharing::OSType;
@@ -183,7 +188,20 @@ class PairedKeyVerificationRunnerTest : public testing::Test {
};
PairedKeyVerificationRunnerTest()
: frames_reader_(fake_task_runner_, &connection_) {}
: connection_(fake_device_info_, &fake_connections_manager_,
"test_enpoint_id"),
frames_reader_(fake_task_runner_, &connection_) {
fake_connections_manager_.set_send_payload_callback(
[this](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
auto frame = std::make_unique<Frame>();
std::vector<uint8_t> data =
std::move(payload->content.bytes_payload.bytes);
frame->ParseFromArray(data.data(), data.size());
frames_data_.push(std::move(frame));
});
}
void SetUp() override {
GetFakeClock()->FastForward(absl::Minutes(15));
@@ -296,25 +314,23 @@ class PairedKeyVerificationRunnerTest : public testing::Test {
std::move(callback)(std::move(frame));
})));
}
nearby::sharing::service::proto::Frame GetWrittenFrame() {
std::vector<uint8_t> data = connection_.GetWrittenData();
nearby::sharing::service::proto::Frame frame;
frame.ParseFromArray(data.data(), data.size());
std::unique_ptr<Frame> GetWrittenFrame() {
std::unique_ptr<Frame> frame = std::move(frames_data_.front());
frames_data_.pop();
return frame;
}
void ExpectPairedKeyEncryptionFrameSent() {
nearby::sharing::service::proto::Frame frame = GetWrittenFrame();
ASSERT_TRUE(frame.has_v1());
ASSERT_TRUE(frame.v1().has_paired_key_encryption());
std::unique_ptr<Frame> frame = GetWrittenFrame();
ASSERT_TRUE(frame->has_v1());
ASSERT_TRUE(frame->v1().has_paired_key_encryption());
}
void ExpectPairedKeyResultFrameSent(PairedKeyResultFrame::Status status) {
nearby::sharing::service::proto::Frame frame = GetWrittenFrame();
ASSERT_TRUE(frame.has_v1());
ASSERT_TRUE(frame.v1().has_paired_key_result());
EXPECT_EQ(status, frame.v1().paired_key_result().status());
std::unique_ptr<Frame> frame = GetWrittenFrame();
ASSERT_TRUE(frame->has_v1());
ASSERT_TRUE(frame->v1().has_paired_key_result());
EXPECT_EQ(status, frame->v1().paired_key_result().status());
}
FakeClock* GetFakeClock() { return &fake_clock_; }
@@ -322,9 +338,12 @@ class PairedKeyVerificationRunnerTest : public testing::Test {
private:
FakeClock fake_clock_;
FakeTaskRunner fake_task_runner_ {&fake_clock_, 1};
FakeNearbyConnection connection_;
FakeDeviceInfo fake_device_info_;
FakeNearbyConnectionsManager fake_connections_manager_;
NearbyConnectionImpl connection_;
testing::NiceMock<MockIncomingFramesReader> frames_reader_;
FakeNearbyShareCertificateManager certificate_manager_;
std::queue<std::unique_ptr<Frame>> frames_data_;
};
TEST_F(PairedKeyVerificationRunnerTest,
+94 -28
View File
@@ -15,6 +15,8 @@
#include "sharing/share_session.h"
#include <cstdint>
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
@@ -28,12 +30,14 @@
#include "absl/time/time.h"
#include "internal/analytics/mock_event_logger.h"
#include "internal/test/fake_clock.h"
#include "internal/test/fake_device_info.h"
#include "internal/test/fake_task_runner.h"
#include "sharing/analytics/analytics_recorder.h"
#include "sharing/certificates/fake_nearby_share_certificate_manager.h"
#include "sharing/fake_nearby_connection.h"
#include "sharing/fake_nearby_connections_manager.h"
#include "sharing/nearby_connection.h"
#include "sharing/nearby_connection_impl.h"
#include "sharing/nearby_connections_types.h"
#include "sharing/paired_key_verification_runner.h"
#include "sharing/share_target.h"
#include "sharing/transfer_metadata.h"
@@ -76,7 +80,16 @@ class TestShareSession : public ShareSession {
return connections_manager_;
}
FakeDeviceInfo& device_info() { return device_info_; }
void SetNearbyConnection(NearbyConnection* connection) {
std::vector<uint8_t> endpoint_info = {1, 2, 3, 4};
std::vector<uint8_t> bluetooth_mac_address = {5, 6, 7, 8};
connections_manager_.Connect(
endpoint_info, kEndpointId, bluetooth_mac_address,
nearby::sharing::proto::DataUsage::ONLINE_DATA_USAGE,
TransportType::kHighQuality,
[&](NearbyConnection* connection, Status status) {});
SetConnection(connection);
}
@@ -88,6 +101,7 @@ class TestShareSession : public ShareSession {
FakeClock fake_clock_;
FakeTaskRunner fake_task_runner_{&fake_clock_, 1};
FakeNearbyConnectionsManager connections_manager_;
FakeDeviceInfo device_info_;
nearby::analytics::MockEventLogger mock_event_logger_;
analytics::AnalyticsRecorder analytics_recorder_{/*vendor_id=*/0,
&mock_event_logger_};
@@ -138,7 +152,8 @@ TEST(ShareSessionTest, SetDisconnectStatus) {
TEST(ShareSessionTest, OnConnectedSucceeds) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
EXPECT_EQ(session.connection(), &connection);
@@ -146,13 +161,21 @@ TEST(ShareSessionTest, OnConnectedSucceeds) {
TEST(ShareSessionTest, IncomingRunPairedKeyVerificationSuccess) {
FakeNearbyShareCertificateManager certificate_manager;
FakeNearbyConnection connection;
std::vector<uint8_t> token = {0, 1, 2, 3, 4, 5};
ShareTarget share_target;
share_target.is_incoming = true;
TestShareSession session(std::string(kEndpointId), share_target);
session.connections_manager().SetRawAuthenticationToken(kEndpointId, token);
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
std::queue<std::vector<uint8_t>> frames_data;
session.connections_manager().set_send_payload_callback(
[&](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
frames_data.push(std::move(payload->content.bytes_payload.bytes));
});
absl::Notification notification;
PairedKeyVerificationRunner::PairedKeyVerificationResult verification_result;
@@ -183,7 +206,7 @@ TEST(ShareSessionTest, IncomingRunPairedKeyVerificationSuccess) {
->mutable_paired_key_encryption()
->set_signed_data("signed_data");
std::string in_encryption_buffer = in_encryption_frame.SerializeAsString();
connection.AppendReadableData(std::vector<uint8_t>(
connection.WriteMessage(std::vector<uint8_t>(
in_encryption_buffer.begin(), in_encryption_buffer.end()));
// Receive PairedKeyResultFrame from remote device.
nearby::sharing::service::proto::Frame in_result_frame;
@@ -193,17 +216,29 @@ TEST(ShareSessionTest, IncomingRunPairedKeyVerificationSuccess) {
in_result_frame.mutable_v1()->mutable_paired_key_result()->set_status(
nearby::sharing::service::proto::PairedKeyResultFrame::SUCCESS);
std::string in_result_buffer = in_result_frame.SerializeAsString();
connection.AppendReadableData(
connection.WriteMessage(
std::vector<uint8_t>(in_result_buffer.begin(), in_result_buffer.end()));
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(absl::Seconds(1)));
EXPECT_EQ(frames_data.size(), 2);
// Check that PairedKeyEncryptionFrame is sent.
std::vector<uint8_t> data = connection.GetWrittenData();
std::vector<uint8_t> data = frames_data.front();
nearby::sharing::service::proto::Frame out_encryption_frame;
ASSERT_TRUE(out_encryption_frame.ParseFromArray(data.data(), data.size()));
ASSERT_TRUE(out_encryption_frame.has_v1());
ASSERT_TRUE(out_encryption_frame.v1().has_paired_key_encryption());
EXPECT_TRUE(notification.WaitForNotificationWithTimeout(absl::Seconds(1)));
// Check that PairedKeyResultFrame is sent.
frames_data.pop();
std::vector<uint8_t> data2 = frames_data.front();
nearby::sharing::service::proto::Frame out_result_frame;
ASSERT_TRUE(out_result_frame.ParseFromArray(data2.data(), data2.size()));
ASSERT_TRUE(out_result_frame.has_v1());
ASSERT_TRUE(out_result_frame.v1().has_paired_key_result());
ASSERT_EQ(out_result_frame.v1().paired_key_result().status(),
nearby::sharing::service::proto::PairedKeyResultFrame::UNABLE);
// Remote PairedKeyEncryptionFrame failed verification.
EXPECT_EQ(verification_result,
PairedKeyVerificationRunner::PairedKeyVerificationResult::kUnable);
@@ -223,9 +258,10 @@ TEST(ShareSessionTest, OnDisconnect) {
}
TEST(ShareSessionTest, CancelPayloads) {
FakeNearbyConnection connection;
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
session.SetAttachmentPayloadId(1, 2);
session.SetAttachmentPayloadId(3, 4);
@@ -239,12 +275,20 @@ TEST(ShareSessionTest, CancelPayloads) {
TEST(ShareSessionTest, WriteResponseFrame) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
std::queue<std::vector<uint8_t>> frames_data;
session.connections_manager().set_send_payload_callback(
[&](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
frames_data.push(std::move(payload->content.bytes_payload.bytes));
});
session.WriteResponseFrame(ConnectionResponseFrame::REJECT);
std::vector<uint8_t> frame_data = connection.GetWrittenData();
std::vector<uint8_t> frame_data = frames_data.front();
Frame frame;
ASSERT_TRUE(frame.ParseFromArray(frame_data.data(), frame_data.size()));
ASSERT_EQ(frame.version(), Frame::V1);
@@ -256,12 +300,20 @@ TEST(ShareSessionTest, WriteResponseFrame) {
TEST(ShareSessionTest, WriteCancelFrame) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
std::queue<std::vector<uint8_t>> frames_data;
session.connections_manager().set_send_payload_callback(
[&](std::unique_ptr<Payload> payload,
std::weak_ptr<NearbyConnectionsManager::PayloadStatusListener>
listener) {
frames_data.push(std::move(payload->content.bytes_payload.bytes));
});
session.WriteCancelFrame();
std::vector<uint8_t> frame_data = connection.GetWrittenData();
std::vector<uint8_t> frame_data = frames_data.front();
Frame frame;
ASSERT_TRUE(frame.ParseFromArray(frame_data.data(), frame_data.size()));
ASSERT_EQ(frame.version(), Frame::V1);
@@ -271,7 +323,8 @@ TEST(ShareSessionTest, WriteCancelFrame) {
TEST(ShareSessionTest, HandleKeyVerificationResultFail) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
session.SetTokenForTests("9876");
@@ -286,7 +339,8 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareSuccess) {
ShareTarget share_target;
share_target.for_self_share = true;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
session.SetTokenForTests("9876");
@@ -301,7 +355,8 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareSuccess) {
TEST(ShareSessionTest, HandleKeyVerificationResultNotSelfShareSuccess) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
session.SetTokenForTests("9876");
@@ -318,7 +373,8 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareUnable) {
ShareTarget share_target;
share_target.for_self_share = true;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
session.SetTokenForTests("9876");
@@ -333,7 +389,8 @@ TEST(ShareSessionTest, HandleKeyVerificationResultSelfShareUnable) {
TEST(ShareSessionTest, HandleKeyVerificationResultNotSelfShareUnable) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
session.SetTokenForTests("9876");
@@ -348,7 +405,8 @@ TEST(ShareSessionTest, HandleKeyVerificationResultNotSelfShareUnable) {
TEST(ShareSessionTest, HandleKeyVerificationResultUnknown) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
session.SetTokenForTests("9876");
@@ -372,32 +430,40 @@ TEST(ShareSessionTest, AbortNotConnected) {
TEST(ShareSessionTest, AbortConnected) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
bool disconnected = false;
connection.SetDisconnectionListener(
[&disconnected]() { disconnected = true; });
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
EXPECT_TRUE(session.connections_manager()
.connection_endpoint_info(kEndpointId)
.has_value());
EXPECT_CALL(session, InvokeTransferUpdateCallback(AllOf(
HasStatus(TransferMetadata::Status::kNotEnoughSpace),
IsFinalStatus())));
session.Abort(TransferMetadata::Status::kNotEnoughSpace);
EXPECT_TRUE(disconnected);
// Verify that the connection is closed.
EXPECT_FALSE(session.connections_manager()
.connection_endpoint_info(kEndpointId)
.has_value());
}
TEST(ShareSessionTest, Disconnect) {
ShareTarget share_target;
TestShareSession session(std::string(kEndpointId), share_target);
FakeNearbyConnection connection;
bool disconnected = false;
connection.SetDisconnectionListener(
[&disconnected]() { disconnected = true; });
NearbyConnectionImpl connection(session.device_info(),
&session.connections_manager(), kEndpointId);
session.SetNearbyConnection(&connection);
EXPECT_TRUE(session.connections_manager()
.connection_endpoint_info(kEndpointId)
.has_value());
session.Disconnect();
EXPECT_TRUE(disconnected);
// Verify that the connection is closed.
EXPECT_FALSE(session.connections_manager()
.connection_endpoint_info(kEndpointId)
.has_value());
}
TEST(ShareSessionTest, DisconnectNotConnected) {