psemek/libs/io/tests/file.cpp

90 lines
2 KiB
C++

#include <psemek/test/test.hpp>
#include <psemek/io/file_stream.hpp>
#include <fstream>
using namespace psemek::io;
test_case(io_file_null)
{
char buffer[256]{};
file_istream is;
expect_throw(is.read(buffer, std::size(buffer)), null_istream);
file_ostream os;
expect_throw(os.write(buffer, std::size(buffer)), null_ostream);
}
static std::filesystem::path temp_file()
{
return std::filesystem::temp_directory_path() / "psemek_test_io";
}
test_case(io_file_write)
{
char const test_str[] = "Hello, world!";
auto const path = temp_file();
auto const length = std::size(test_str);
{
file_ostream os(path);
expect_equal(os.write(test_str, length), length);
}
expect(std::filesystem::exists(path));
char buffer_in[256]{};
std::ifstream is(path);
expect(is.read(buffer_in, length));
expect_equal(std::string_view(test_str, length), std::string_view(buffer_in, length));
}
test_case(io_file_append)
{
char const test_str[] = "Hello, world!";
auto const path = temp_file();
auto const length = std::size(test_str);
auto const half_length = length / 2;
auto const remain_length = length - half_length;
{
file_ostream os(path);
expect_equal(os.write(test_str, half_length), half_length);
}
expect(std::filesystem::exists(path));
{
file_ostream os(path, file_ostream::append);
expect_equal(os.write(test_str + half_length, remain_length), remain_length);
}
expect(std::filesystem::exists(path));
char buffer_in[256]{};
std::ifstream is(path);
expect(is.read(buffer_in, length));
expect_equal(std::string_view(test_str, length), std::string_view(buffer_in, length));
}
test_case(io_file_read)
{
char const test_str[] = "Hello, world!";
auto const path = temp_file();
auto const length = std::size(test_str);
{
std::ofstream os(path);
expect(os.write(test_str, length));
}
char buffer_in[256]{};
file_istream is(path);
expect_equal(is.read(buffer_in, length), length);
expect_equal(std::string_view(test_str, length), std::string_view(buffer_in, length));
}