Skip to content
Merged
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 AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ Concrete review expectations for this repository:
- **Cover the branches.** Every new branch, error path, and boundary (empty, zero, negative, invalid, concurrent) needs a case. For combinations of boolean conditions, cover the combinations, not just one. Test both the enabled and disabled paths of any flag or capability that guards behavior.
- **Do not generate test bloat; reuse setup.** Do not add heavy tests for trivial data-holder classes with no logic. Do not repeat identical setup in every method: hoist shared setup into `@BeforeEach` and extend the shared base test classes (`BaseServerTest`, `BaseCRUDTest`) rather than re-creating their scaffolding, and reserve `@BeforeAll` for a genuinely immutable, expensive fixture. Collapse several near-identical cases that do not mutate state into one parameterized test, or one method that walks a list of input/expected pairs, instead of copy-pasting a method per input. Object, client, and server setup is expensive, and slow or bloated suites get flagged in review.
- **Stack:** JUnit 5 (`@BeforeEach`/`@AfterEach`/`@TempDir`), servers bound to a random port per test, schema reset between tests. Integration tests spanning server plus a client or connector go in `integration-tests/`.
- **S3-compatible storage:** `s3://` paths in tests use emulated storage by default. `build/sbt testMinIO` (also `testSeaweedFS`, `testRustFS`, `testCeph`, `testGarage`, `testCephStaticKey` and `testGarageStaticKey`, or `UC_TEST_STORAGE=<storage>`, one of `SupportedStorage`) runs every project's tests on that storage in Docker; tests that need real storage skip without it, and `S3CompatibleCredentialScopeTest` also skips on storage without STS, whose keys carry no session policy.

## Contribution workflow

Expand Down
13 changes: 13 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -960,3 +960,16 @@ addCommandAlias(
s"""; set every Test / envVars := Map("UC_TEST_DATABASE" -> "$database", "UC_TEST_MIGRATION_CHECKS" -> "true", "UC_UPDATE_SCHEMA_EFFECTS" -> "true")""" +
" ; server/testOnly io.unitycatalog.server.migrate.MigrationStepRulesTest"
}.mkString)

// Runs every project's tests with s3:// paths on one S3-compatible storage. One alias per
// SupportedStorage constant except EMULATED (the default). Forked tests also inherit the shell's
// environment, so UC_TEST_DATABASE set there selects the database as well.
def testOnStorage(storage: String): String =
s"""; set every Test / envVars := Map("UC_TEST_STORAGE" -> "$storage") ; test"""
addCommandAlias("testMinIO", testOnStorage("MINIO"))
addCommandAlias("testCeph", testOnStorage("CEPH"))
addCommandAlias("testCephStaticKey", testOnStorage("CEPH_STATIC_KEY"))
addCommandAlias("testRustFS", testOnStorage("RUSTFS"))
addCommandAlias("testSeaweedFS", testOnStorage("SEAWEEDFS"))
addCommandAlias("testGarage", testOnStorage("GARAGE"))
addCommandAlias("testGarageStaticKey", testOnStorage("GARAGE_STATIC_KEY"))
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,17 @@
import static io.unitycatalog.spark.DeltaVersionUtils.MIN_DELTA_VERSION_FOR_UC_DELTA_API;
import static org.assertj.core.api.Assertions.assertThat;

import io.unitycatalog.client.ApiClient;
import io.unitycatalog.client.ApiException;
import io.unitycatalog.client.api.CredentialsApi;
import io.unitycatalog.client.api.ExternalLocationsApi;
import io.unitycatalog.client.model.CreateCatalog;
import io.unitycatalog.client.model.CreateCredentialRequest;
import io.unitycatalog.client.model.CreateExternalLocation;
import io.unitycatalog.client.model.CreateSchema;
import io.unitycatalog.client.model.CredentialPurpose;
import io.unitycatalog.client.model.S3AssumeRole;
import io.unitycatalog.client.model.S3CompatibleRequest;
import io.unitycatalog.server.base.BaseCRUDTest;
import io.unitycatalog.server.base.ServerConfig;
import io.unitycatalog.server.base.catalog.CatalogOperations;
Expand All @@ -17,6 +25,8 @@
import io.unitycatalog.server.sdk.catalog.SdkCatalogOperations;
import io.unitycatalog.server.sdk.schema.SdkSchemaOperations;
import io.unitycatalog.server.service.credential.gcp.TestingCredentialGenerator;
import io.unitycatalog.server.teststorage.TestStorage;
import io.unitycatalog.server.teststorage.TestStorages;
import io.unitycatalog.server.utils.LocalMappingFileOperations;
import io.unitycatalog.server.utils.NormalizedURL;
import io.unitycatalog.server.utils.ServerProperties;
Expand All @@ -29,6 +39,7 @@
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeEach;

public abstract class BaseSparkIntegrationTest extends BaseCRUDTest {
Expand All @@ -42,6 +53,21 @@ public abstract class BaseSparkIntegrationTest extends BaseCRUDTest {
/** S3 bucket with no credentials configured on server - for testing SSP fallback. */
public static final String NO_CREDS_BUCKET = "test-bucket-2-no-creds";

/** The S3 buckets the tests read and write; Unity Catalog has credentials for each. */
protected static final List<String> S3_BUCKETS = List.of("test-bucket0", "test-bucket1");

/**
* The S3-compatible storage {@code s3://} paths live on, selected by {@code UC_TEST_STORAGE};
* empty when they are emulated by fake file systems and clients over local files. Resolved on use
* rather than in a static initializer, so a failed start reports its cause in each suite.
*/
protected static Optional<TestStorage> s3Storage() {
return TestStorages.selected();
}

/** The storage credential that reaches {@link #s3Storage()}. */
private static final String S3_CREDENTIAL = "s3_test_storage";

private SchemaOperations schemaOperations;
// Each test would create this session. It will be closed automatically.
protected SparkSession session;
Expand Down Expand Up @@ -128,11 +154,69 @@ protected SparkSession createSparkSessionWithCatalogs(
builder.config(
catalogConfKey(SPARK_CATALOG), "org.apache.spark.sql.delta.catalog.DeltaCatalog");
}
// Use fake file system for cloud storage so that we can test credentials.
builder.config("spark.hadoop.fs.s3.impl", S3CredentialTestFileSystem.class.getName());
return configureCloudFileSystems(builder).getOrCreate();
}

/** True when {@code s3://} paths are on real S3-compatible storage rather than emulated. */
protected static boolean onRealS3Storage() {
return s3Storage().isPresent();
}

/**
* True when the S3 storage is real but Unity Catalog vends it no keys ({@code
* server.s3-compatible-storage.static-key-vending=endpoint-only}), so the engine is configured
* with the storage's own keys.
*/
protected static boolean usesAmbientS3Keys() {
return s3Storage().isPresent() && !s3Storage().get().vendsKeys();
}

/**
* Skips a test whose subject is the emulated storage itself (its fixed credentials, fake file
* systems, or mock clients), which real storage cannot reproduce.
*
* @param reason what the test checks of the emulation
*/
protected static void assumeEmulatedS3Storage(String reason) {
Assumptions.assumeFalse(onRealS3Storage(), "Checks the emulated S3 storage: " + reason);
}

/**
* Sets the file systems for cloud paths: S3A for {@code s3://} on real storage, otherwise fake
* file systems over local files that check the credentials Unity Catalog vends. {@code gs://} and
* {@code abfs://} are always emulated.
*
* @param builder the session builder
* @return the same builder
*/
protected static SparkSession.Builder configureCloudFileSystems(SparkSession.Builder builder) {
if (onRealS3Storage()) {
builder.config("spark.hadoop.fs.s3.impl", "org.apache.hadoop.fs.s3a.S3AFileSystem");
// Only keys Unity Catalog vends: without them a request fails at once, instead of reaching
// for keys from the environment or the host's instance metadata.
builder.config(
"spark.hadoop.fs.s3a.aws.credentials.provider",
"org.apache.hadoop.fs.s3a.TemporaryAWSCredentialsProvider,"
+ "org.apache.hadoop.fs.s3a.SimpleAWSCredentialsProvider");
if (usesAmbientS3Keys()) {
// Unity Catalog vends only the endpoint, so the engine brings the storage's keys, the way
// an engine set up for that storage would. The routing comes from the vend alone, so the
// tests see whether it reaches S3A; only the bucket that gets no vend is routed here.
TestStorage storage = s3Storage().get();
String noCredsBucket = "spark.hadoop.fs.s3a.bucket." + NO_CREDS_BUCKET + ".";
builder
.config("spark.hadoop.fs.s3a.access.key", storage.accessKeyId())
.config("spark.hadoop.fs.s3a.secret.key", storage.secretAccessKey())
.config(noCredsBucket + "endpoint", storage.s3Endpoint())
.config(noCredsBucket + "endpoint.region", "us-east-1")
.config(noCredsBucket + "path.style.access", "true");
}
} else {
builder.config("spark.hadoop.fs.s3.impl", S3CredentialTestFileSystem.class.getName());
}
builder.config("spark.hadoop.fs.gs.impl", GCSCredentialTestFileSystem.class.getName());
builder.config("spark.hadoop.fs.abfs.impl", AzureCredentialTestFileSystem.class.getName());
return builder.getOrCreate();
return builder;
}

/** The Spark SQL config key prefix for a catalog, e.g. {@code spark.sql.catalog.<name>}. */
Expand All @@ -158,9 +242,9 @@ private SparkSession.Builder ucSingleCatalogConfig(

/**
* Wires one catalog as Iceberg's REST {@code SparkCatalog} against the server's Iceberg REST
* catalog, with the client FileIO following the storage scheme: on emulated S3 the table consumes
* the credentials UC vends through a mock S3 client ({@code MockS3ClientFactory}); otherwise data
* files read and write locally through {@code HadoopFileIO}.
* catalog, with the client FileIO following the storage scheme: on S3 the table consumes the
* credentials and S3 endpoint UC vends, through a mock S3 client ({@code MockS3ClientFactory})
* when S3 is emulated; otherwise data files read and write locally through {@code HadoopFileIO}.
*/
private SparkSession.Builder icebergCatalogConfig(SparkSession.Builder builder, String catalog) {
String catalogConf = catalogConfKey(catalog);
Expand All @@ -172,9 +256,17 @@ private SparkSession.Builder icebergCatalogConfig(SparkSession.Builder builder,
.config(catalogConf + ".warehouse", catalog)
.config(catalogConf + ".token", serverConfig.getAuthToken());
if ("s3".equals(managedStorageCloudScheme())) {
return builder
.config(catalogConf + ".io-impl", "org.apache.iceberg.aws.s3.S3FileIO")
.config(catalogConf + ".s3.client-factory-impl", FakeS3.MOCK_S3_CLIENT_FACTORY);
builder = builder.config(catalogConf + ".io-impl", "org.apache.iceberg.aws.s3.S3FileIO");
if (usesAmbientS3Keys()) {
// The table config Unity Catalog returns carries the endpoint but no keys.
builder =
builder
.config(catalogConf + ".s3.access-key-id", s3Storage().get().accessKeyId())
.config(catalogConf + ".s3.secret-access-key", s3Storage().get().secretAccessKey());
}
return onRealS3Storage()
? builder
: builder.config(catalogConf + ".s3.client-factory-impl", FakeS3.MOCK_S3_CLIENT_FACTORY);
}
return builder.config(catalogConf + ".io-impl", "org.apache.iceberg.hadoop.HadoopFileIO");
}
Expand All @@ -195,19 +287,62 @@ protected static boolean isSparkAtLeast(int major, int minor) {
* True when managed tables sit on emulated S3 storage, the only cloud scheme the server can read
* here (server-side cloud-to-local mapping; for Iceberg also client {@code S3FileIO} + mock
* factory). The server reads that storage for Iceberg metadata and for Delta backfill
* verification.
* verification. On real S3-compatible storage the server reads it directly.
*/
private boolean managedStorageOnEmulatedS3() {
String scheme = managedStorageCloudScheme();
if ("s3".equals(scheme)) {
return true;
return !onRealS3Storage();
}
// s3 is the only emulated cloud wired for the server; the only other scheme the suites use is
// local file. Fail loudly if an unwired scheme (e.g. gs/abfs) ever reaches here.
assertThat(scheme).as("Managed storage scheme").isEqualTo("file");
return false;
}

/**
* Registers the real S3-compatible storage the way a deployment does: its buckets, an {@code
* s3_compatible} credential, and an external location per bucket. The credential assumes the
* storage's role when it has one, and otherwise follows {@code
* server.s3-compatible-storage.static-key-vending}. The bucket for the no-credentials case gets
* no external location.
*/
private void registerS3Storage(TestStorage storage) throws ApiException {
for (String bucket : S3_BUCKETS) {
storage.createBucket(bucket);
}
storage.createBucket(NO_CREDS_BUCKET);
ApiClient apiClient = createApiClient(serverConfig);
new CredentialsApi(apiClient)
.createCredential(
new CreateCredentialRequest()
.name(S3_CREDENTIAL)
.purpose(CredentialPurpose.STORAGE)
.s3Compatible(
new S3CompatibleRequest()
.accessKeyId(storage.accessKeyId())
.secretAccessKey(storage.secretAccessKey())
.s3Endpoint(storage.s3Endpoint())
// Each vend is an STS session of the storage's role, narrowed by the
// session policy Unity Catalog sends; without STS the server's
// server.s3-compatible-storage.static-key-vending decides whether clients
// get the key
// pair.
.assumeRole(
storage
.roleArn()
.map(arn -> new S3AssumeRole().roleArn(arn))
.orElse(null))));
ExternalLocationsApi externalLocationsApi = new ExternalLocationsApi(apiClient);
for (String bucket : S3_BUCKETS) {
externalLocationsApi.createExternalLocation(
new CreateExternalLocation()
.name(bucket.replace('-', '_'))
.url("s3://" + bucket)
.credentialName(S3_CREDENTIAL));
}
}

@BeforeEach
@Override
public void setUp() {
Expand All @@ -224,6 +359,9 @@ public void setUp() {
System.setProperty("spark.testing", "true");
schemaOperations = new SdkSchemaOperations(createApiClient(serverConfig));
try {
if (s3Storage().isPresent()) {
registerS3Storage(s3Storage().get());
}
createCommonResources();
} catch (ApiException e) {
throw new RuntimeException(e);
Expand Down Expand Up @@ -257,14 +395,25 @@ protected void setUpProperties() {
serverProperties.put(
ServerProperties.Property.MANAGED_TABLE_USE_DELTA_API_ONLY.getKey(), "true");
}
serverProperties.put("s3.bucketPath.0", "s3://test-bucket0");
serverProperties.put("s3.accessKey.0", "accessKey0");
serverProperties.put("s3.secretKey.0", "secretKey0");
serverProperties.put("s3.sessionToken.0", "sessionToken0");
serverProperties.put("s3.bucketPath.1", "s3://test-bucket1");
serverProperties.put("s3.accessKey.1", "accessKey1");
serverProperties.put("s3.secretKey.1", "secretKey1");
serverProperties.put("s3.sessionToken.1", "sessionToken1");
s3Storage()
.ifPresent(
storage -> {
enableS3CompatibleStorage();
serverProperties.put(
ServerProperties.Property.S3_COMPATIBLE_STATIC_KEY_VENDING.getKey(),
storage.staticKeyVending().value());
});
// Real S3-compatible storage is reached through external locations instead (registerS3Storage).
if (!onRealS3Storage()) {
serverProperties.put("s3.bucketPath.0", "s3://test-bucket0");
serverProperties.put("s3.accessKey.0", "accessKey0");
serverProperties.put("s3.secretKey.0", "secretKey0");
serverProperties.put("s3.sessionToken.0", "sessionToken0");
serverProperties.put("s3.bucketPath.1", "s3://test-bucket1");
serverProperties.put("s3.accessKey.1", "accessKey1");
serverProperties.put("s3.secretKey.1", "secretKey1");
serverProperties.put("s3.sessionToken.1", "sessionToken1");
}

serverProperties.put("gcs.bucketPath.0", "gs://test-bucket0");
serverProperties.put("gcs.jsonKeyFilePath.0", "testing://0");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ public void cleanUp() {

@Test
public void bothCredentialsAreRequiredToReadBothLocations() {
assumeEmulatedS3Storage(
"the per-path fake file system and a mocked credential fetcher stand in for the server");
CredentialTestFileSystem.credentialCheckEnabled = false;
try {
sql("INSERT OVERWRITE DIRECTORY '%s' USING parquet SELECT 1 AS i, 'a' AS s", locationA);
Expand Down
Loading
Loading