blob: 8f7f896a220e14f7517a8689fab2be6a28c45622 [file] [log] [blame]
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/lib/fsl/socket/files.h"
#include <fcntl.h>
#include <lib/zx/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "src/lib/files/file.h"
#include "src/lib/files/scoped_temp_dir.h"
#include "src/lib/fsl/socket/strings.h"
#include "src/lib/testing/loop_fixture/test_loop_fixture.h"
namespace fsl {
namespace {
using SockAndFileTest = ::gtest::TestLoopFixture;
TEST_F(SockAndFileTest, CopyToFileDescriptor) {
files::ScopedTempDir tmp_dir;
std::string tmp_file;
tmp_dir.NewTempFile(&tmp_file);
fbl::unique_fd destination(open(tmp_file.c_str(), O_WRONLY));
EXPECT_TRUE(destination.is_valid());
bool success;
CopyToFileDescriptor(
fsl::WriteStringToSocket("Hello"), std::move(destination), dispatcher(),
[&success](bool success_value, fbl::unique_fd fd) { success = success_value; });
RunLoopUntilIdle();
EXPECT_TRUE(success);
std::string content;
EXPECT_TRUE(files::ReadFileToString(tmp_file, &content));
EXPECT_EQ("Hello", content);
}
TEST_F(SockAndFileTest, CopyFromFileDescriptor) {
files::ScopedTempDir tmp_dir;
std::string tmp_file;
tmp_dir.NewTempFile(&tmp_file);
files::WriteFile(tmp_file, "Hello", 5);
fbl::unique_fd source(open(tmp_file.c_str(), O_RDONLY));
EXPECT_TRUE(source.is_valid());
zx::socket socket1, socket2;
EXPECT_EQ(ZX_OK, zx::socket::create(0u, &socket1, &socket2));
bool success;
CopyFromFileDescriptor(
std::move(source), std::move(socket1), dispatcher(),
[&success](bool success_value, fbl::unique_fd fd) { success = success_value; });
RunLoopUntilIdle();
EXPECT_TRUE(success);
std::string content;
EXPECT_TRUE(fsl::BlockingCopyToString(std::move(socket2), &content));
EXPECT_EQ("Hello", content);
}
} // namespace
} // namespace fsl