Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/iceberg/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,7 @@ add_iceberg_test(json_serde_test
if(ICEBERG_BUILD_VERIFICATION_TESTS)
add_iceberg_test(verification_test
SOURCES
verification/partition_transforms_verification_test.cc
verification/schema_verification_test.cc
verification/types_verification_test.cc
verification/verification_util.cc)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* http://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.
*/

// Runs the `table-spec/partition-transforms` surface: binding `input.transform` to
// `input.source_type` yields one of `decoded.result_types`, and applying it to each
// of `input.values` yields the value at the same index of `decoded.values`.

#include <algorithm>
#include <array>
#include <cstdint>
#include <exception>
#include <format>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <vector>

#include <gtest/gtest.h>
#include <nlohmann/json.hpp>

#include "iceberg/expression/json_serde_internal.h"
#include "iceberg/expression/literal.h"
#include "iceberg/json_serde_internal.h"
#include "iceberg/result.h"
#include "iceberg/test/verification/verification_util.h"
#include "iceberg/transform.h"
#include "iceberg/type.h"
#include "iceberg/util/string_util.h"

namespace iceberg::verification {

namespace {

constexpr std::array<std::string_view, 8> kSubdirs = {
"identity", "bucket", "truncate", "year", "month", "day", "hour", "void"};

constexpr std::string_view kTransform = "transform";
constexpr std::string_view kSourceType = "source_type";
constexpr std::string_view kValues = "values";
constexpr std::string_view kResultTypes = "result_types";

/// \brief Decode a language-neutral value of this surface into a literal of `type`.
Result<Literal> DecodeValue(const nlohmann::json& json,
const std::shared_ptr<PrimitiveType>& type) {
if (json.is_null()) {
return Literal::Null(type);
}
switch (type->type_id()) {
case TypeId::kLong: {
// partition-transforms/README.md: "`long` values are decimal strings so JSON
// number handling cannot lose 64-bit precision."
if (!json.is_string()) {
return JsonParseError("long value {} is not a decimal string", json.dump());
}
ICEBERG_ASSIGN_OR_RAISE(auto value,
StringUtils::ParseNumber<int64_t>(json.get<std::string>()));
return Literal::Long(value);
}
default:
Comment thread
WZhuo marked this conversation as resolved.
Resolved
return LiteralFromJson(json, type.get());
}
}

std::string Describe(const Literal& literal) {
if (literal.IsNull()) {
return "null";
}
auto json = ToJson(literal);
return json.has_value() ? json->dump() : literal.ToString();
}

/// \brief Give a `day` result its declared `date` type.
Literal NormalizeResult(const Literal& literal,
const std::shared_ptr<PrimitiveType>& result_type) {
if (result_type->type_id() != TypeId::kDate ||
literal.type()->type_id() != TypeId::kInt) {
return literal;
}
if (literal.IsNull()) {
return Literal::Null(result_type);
}
return Literal::Date(std::get<int32_t>(literal.value()));
}

Result<std::shared_ptr<PrimitiveType>> ParsePrimitiveType(const nlohmann::json& json) {
ICEBERG_ASSIGN_OR_RAISE(std::shared_ptr<Type> type, TypeFromJson(json));
if (!type->is_primitive()) {
return InvalidArgument("{} is not a primitive type", json.dump());
}
return std::static_pointer_cast<PrimitiveType>(type);
}

/// \brief Apply `transform` to `input` and compare the result with `expected`.
std::optional<std::string> CheckValue(TransformFunction& transform,
const std::shared_ptr<PrimitiveType>& source_type,
const std::shared_ptr<PrimitiveType>& result_type,
const nlohmann::json& input,
const nlohmann::json& expected_json) {
auto value = DecodeValue(input, source_type);
if (!value.has_value()) {
return std::format("cannot decode input {}: {}", input.dump(), value.error().message);
}
Result<Literal> transformed = [&]() -> Result<Literal> {
try {
return transform.Transform(*value);
} catch (const std::exception& e) {
return Invalid("transform threw: {}", e.what());
}
}();
if (!transformed.has_value()) {
return std::format("transform failed: {}", transformed.error().message);
}
Literal actual = NormalizeResult(*transformed, result_type);
if (expected_json.is_null()) {
if (!actual.IsNull()) {
return std::format("expected null, got {}", Describe(actual));
}
return std::nullopt;
}
auto expected = DecodeValue(expected_json, result_type);
if (!expected.has_value()) {
return std::format("cannot decode expected {} as {}: {}", expected_json.dump(),
result_type->ToString(), expected.error().message);
}
if (actual.IsNull() || *actual.type() != *expected->type() || actual != *expected) {
return std::format("expected {} of type {}, got {} of type {}", expected_json.dump(),
expected->type()->ToString(), Describe(actual),
actual.type()->ToString());
}
return std::nullopt;
}

std::vector<std::string> CheckCase(const nlohmann::json& c) {
const auto& input = c.at(kInput);
const auto& decoded = c.at(kDecoded);

auto source_type = ParsePrimitiveType(input.at(kSourceType));
if (!source_type.has_value()) {
return {std::format("source type: {}", source_type.error().message)};
}
auto transform = TransformFromString(input.at(kTransform).get<std::string>());
if (!transform.has_value()) {
return {std::format("transform: {}", transform.error().message)};
}
auto bound = (*transform)->Bind(*source_type);
if (!bound.has_value()) {
return {std::format("bind failed: {}", bound.error().message)};
}

std::vector<std::string> diffs;
auto result_type = (*bound)->ResultType();
const auto& allowed = decoded.at(kResultTypes);
bool result_type_allowed = std::ranges::any_of(allowed, [&](const auto& json) {
auto type = TypeFromJson(json);
return type.has_value() && **type == *result_type;
});
if (!result_type_allowed) {
diffs.push_back(std::format("result_type: expected one of {}, got {}", allowed.dump(),
result_type->ToString()));
}
if (!result_type->is_primitive()) {
diffs.push_back(
std::format("result_type: {} is not primitive", result_type->ToString()));
return diffs;
}
auto result_primitive = std::static_pointer_cast<PrimitiveType>(result_type);

const auto& inputs = input.at(kValues);
const auto& expected_values = decoded.at(kValues);
if (inputs.size() != expected_values.size()) {
diffs.push_back(std::format("values: {} inputs but {} expected values", inputs.size(),
expected_values.size()));
return diffs;
}
for (size_t i = 0; i < inputs.size(); ++i) {
Comment thread
WZhuo marked this conversation as resolved.
Resolved
auto diff = CheckValue(**bound, *source_type, result_primitive, inputs[i],
expected_values[i]);
if (diff.has_value()) {
diffs.push_back(std::format("values[{}]: {}", i, *diff));
}
}
return diffs;
}

class PartitionTransformsVerificationTest
: public ::testing::TestWithParam<VerificationCase> {};

TEST_P(PartitionTransformsVerificationTest, Apply) { RunCase(GetParam(), CheckCase); }

INSTANTIATE_TEST_SUITE_P(PartitionTransforms, PartitionTransformsVerificationTest,
::testing::ValuesIn(LoadCases("partition-transforms", kSubdirs)),
CaseName);
GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(PartitionTransformsVerificationTest);

} // namespace

} // namespace iceberg::verification
8 changes: 1 addition & 7 deletions src/iceberg/test/verification/schema_verification_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,7 @@ std::vector<std::string> CheckCase(const nlohmann::json& c) {

class SchemaVerificationTest : public ::testing::TestWithParam<VerificationCase> {};

TEST_P(SchemaVerificationTest, Parse) {
const auto& c = GetParam();
if (!c.load_error.empty()) {
FAIL() << c.load_error;
}
ReportOutcome(c, CheckCase(c.json));
}
TEST_P(SchemaVerificationTest, Parse) { RunCase(GetParam(), CheckCase); }

INSTANTIATE_TEST_SUITE_P(Schema, SchemaVerificationTest,
::testing::ValuesIn(LoadCases("schema", kSubdirs)), CaseName);
Expand Down
8 changes: 1 addition & 7 deletions src/iceberg/test/verification/types_verification_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -148,13 +148,7 @@ std::vector<std::string> CheckCase(const nlohmann::json& c) {

class TypesVerificationTest : public ::testing::TestWithParam<VerificationCase> {};

TEST_P(TypesVerificationTest, Parse) {
const auto& c = GetParam();
if (!c.load_error.empty()) {
FAIL() << c.load_error;
}
ReportOutcome(c, CheckCase(c.json));
}
TEST_P(TypesVerificationTest, Parse) { RunCase(GetParam(), CheckCase); }

INSTANTIATE_TEST_SUITE_P(Types, TypesVerificationTest,
::testing::ValuesIn(LoadCases("types", kSubdirs)), CaseName);
Expand Down
6 changes: 5 additions & 1 deletion src/iceberg/test/verification/verification_util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,12 @@ void DiffJson(const nlohmann::json& expected, const nlohmann::json& actual,
}
}

void ReportOutcome(const VerificationCase& c, const std::vector<std::string>& diffs) {
void RunCase(const VerificationCase& c, const CaseChecker& check) {
const auto label = c.Label();
if (!c.load_error.empty()) {
FAIL() << c.load_error;
}
const auto diffs = check(c.json);
if (diffs.empty()) {
return;
}
Expand Down
14 changes: 9 additions & 5 deletions src/iceberg/test/verification/verification_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
/// reports differences labeled `<subdir>/<case-id> <path>`, as the surface READMEs
/// require.

#include <functional>
#include <ostream>
#include <span>
#include <string>
Expand Down Expand Up @@ -95,11 +96,14 @@ std::string CaseName(const ::testing::TestParamInfo<VerificationCase>& info);
void DiffJson(const nlohmann::json& expected, const nlohmann::json& actual,
const std::string& path, std::vector<std::string>* diffs);

/// \brief Turn the differences found for a case into a test outcome.
/// \brief Checks a case object and returns the differences found.
using CaseChecker = std::function<std::vector<std::string>(const nlohmann::json&)>;

/// \brief Run `check` on a case and turn the differences into a test outcome.
///
/// No differences pass. Differences fail the test, unless the case is advisory
/// (`normative_level: should`), in which case the test is skipped with the
/// differences in the message.
void ReportOutcome(const VerificationCase& c, const std::vector<std::string>& diffs);
/// A case carrying a load error fails with it. No differences pass. Differences fail
/// the test, unless the case is advisory (`normative_level: should`), in which case
/// the test is skipped with the differences in the message.
void RunCase(const VerificationCase& c, const CaseChecker& check);

} // namespace iceberg::verification
Loading