2525#include < gtest/gtest.h>
2626#include < nlohmann/json.hpp>
2727
28+ #include " iceberg/partition_spec.h"
2829#include " iceberg/schema.h"
2930#include " iceberg/sort_field.h"
3031#include " iceberg/sort_order.h"
@@ -48,6 +49,12 @@ expected<std::unique_ptr<SortOrder>, Error> FromJsonHelper(const nlohmann::json&
4849 return SortOrderFromJson (json);
4950}
5051
52+ template <>
53+ expected<std::unique_ptr<PartitionField>, Error> FromJsonHelper (
54+ const nlohmann::json& json) {
55+ return PartitionFieldFromJson (json);
56+ }
57+
5158// Helper function to reduce duplication in testing
5259template <typename T>
5360void TestJsonConversion (const T& obj, const nlohmann::json& expected_json) {
@@ -94,4 +101,51 @@ TEST(JsonInternalTest, SortOrder) {
94101 TestJsonConversion (sort_order, expected_sort_order);
95102}
96103
104+ TEST (JsonInternalTest, PartitionField) {
105+ auto identity_transform = std::make_shared<IdentityTransformFunction>();
106+ PartitionField field (3 , 101 , " region" , identity_transform);
107+ nlohmann::json expected_json =
108+ R"( {"source-id":3,"field-id":101,"transform":"identity","name":"region"})" _json;
109+ TestJsonConversion (field, expected_json);
110+ }
111+
112+ TEST (JsonPartitionTest, PartitionFieldFromJsonMissingField) {
113+ nlohmann::json invalid_json =
114+ R"( {"field-id":101,"transform":"identity","name":"region"})" _json;
115+ // missing source-id
116+
117+ auto result = PartitionFieldFromJson (invalid_json);
118+ EXPECT_FALSE (result.has_value ());
119+ EXPECT_EQ (result.error ().kind , ErrorKind::kJsonParseError );
120+ }
121+
122+ TEST (JsonPartitionTest, PartitionSpec) {
123+ auto schema = std::make_shared<Schema>(
124+ 100 , std::vector<SchemaField>{
125+ SchemaField (3 , " region" , std::make_shared<StringType>(), false ),
126+ SchemaField (5 , " ts" , std::make_shared<LongType>(), false )});
127+
128+ auto identity_transform = std::make_shared<IdentityTransformFunction>();
129+ PartitionSpec spec (schema, 1 ,
130+ {PartitionField (3 , 101 , " region" , identity_transform),
131+ PartitionField (5 , 102 , " ts" , identity_transform)});
132+ auto json = ToJson (spec);
133+ nlohmann::json expected_json = R"( {"spec-id": 1,
134+ "fields": [
135+ {"source-id": 3,
136+ "field-id": 101,
137+ "transform": "identity",
138+ "name": "region"},
139+ {"source-id": 5,
140+ "field-id": 102,
141+ "transform": "identity",
142+ "name": "ts"}]})" _json;
143+
144+ EXPECT_EQ (json, expected_json);
145+
146+ auto parsed_spec_result = PartitionSpecFromJson (schema, json);
147+ ASSERT_TRUE (parsed_spec_result.has_value ()) << parsed_spec_result.error ().message ;
148+ EXPECT_EQ (spec, *parsed_spec_result.value ());
149+ }
150+
97151} // namespace iceberg
0 commit comments