Skip to content

Commit

Permalink
libnixt/serialize: add unit tests for ExprInt and ExprFloat
Browse files Browse the repository at this point in the history
  • Loading branch information
inclyc committed Dec 28, 2023
1 parent 4630eb4 commit b51dbec
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
1 change: 1 addition & 0 deletions libnixt/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ nixt = declare_dependency(include_directories: libnixdInc,
)

libnixt_test_exe = executable('test-libnixt',
'test/Serialize.cpp',
'test/SerializeSupport.cpp',
dependencies: [ gtest_main, nixt ])

Expand Down
63 changes: 63 additions & 0 deletions libnixt/test/Serialize.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
#include <gtest/gtest.h>

#include "nixt/Serialize.h"

#include <nix/nixexpr.hh>

#include <bit>

using namespace nixt::serialize;

static_assert(std::endian::native == std::endian::little);

namespace {

class SerializeTest : public testing::Test {
protected:
nix::PosTable PT;
nix::SymbolTable ST;
std::ostringstream OS;
std::string write(const nix::Expr *E) {
nixt::serialize::write(OS, ST, PT, E);
return OS.str();
}
};

void checkASTHeader(const ASTHeader &H) {
EXPECT_EQ(std::memcmp(H.Magic, "\x7FNixAST\0", 8), 0);
EXPECT_EQ(H.Version, 1);
}

void checkASTHeader(const char *Raw) {
ASTHeader Header;
std::memcpy(&Header, Raw, sizeof(ASTHeader));
checkASTHeader(Header);
}

} // namespace

TEST_F(SerializeTest, ExprInt) {
nix::ExprInt E(0x2adeadbeef);
std::string Result = write(&E);
const char Expected[] = "\x6\0\0\0\xEF\xBE\xAD\xDE\x2A\0\0";
checkASTHeader(Result.c_str());
auto Content = std::string_view(Result).substr(sizeof(ASTHeader));
EXPECT_TRUE(std::memcmp(Expected, Content.begin(), sizeof(Expected)) == 0);
EXPECT_EQ(Content.size(), sizeof(Expected));
}

TEST_F(SerializeTest, ExprFloat) {
union {
double D;
std::uint64_t U;
} Data;
Data.U = 0x2adeadbeef;

nix::ExprFloat E(Data.D);
std::string Result = write(&E);
const char Expected[] = "\x4\0\0\0\xEF\xBE\xAD\xDE\x2A\0\0";
checkASTHeader(Result.c_str());
auto Content = std::string_view(Result).substr(sizeof(ASTHeader));
EXPECT_TRUE(std::memcmp(Expected, Content.begin(), sizeof(Expected)) == 0);
EXPECT_EQ(Content.size(), sizeof(Expected));
}

0 comments on commit b51dbec

Please sign in to comment.