diff --git a/samples/pom.xml b/samples/pom.xml index d0a71d9f8c..f059468a4d 100644 --- a/samples/pom.xml +++ b/samples/pom.xml @@ -34,6 +34,21 @@ + + + org.slf4j + jul-to-slf4j + 2.0.16 + + + ch.qos.logback + logback-classic + 1.4.11 + runtime + + + + diff --git a/samples/snapshot/src/test/resources/logback.xml b/samples/snapshot/src/test/resources/logback.xml new file mode 100644 index 0000000000..ccf099f935 --- /dev/null +++ b/samples/snapshot/src/test/resources/logback.xml @@ -0,0 +1,98 @@ + + + + + + true + + + + %date %-5.5level [%-32.32thread] %-17.17logger{17} - %message%n + + + + + %date %-5.5level [%-32.32thread] %-17.17logger{17} - %message%nopex%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/snippets/src/test/java/com/example/storage/ConfigureRetriesTest.java b/samples/snippets/src/test/java/com/example/storage/ConfigureRetriesTest.java deleted file mode 100644 index 76ae1e38c9..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/ConfigureRetriesTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2021 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.cloud.storage.Blob; -import com.google.cloud.storage.BlobInfo; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public final class ConfigureRetriesTest { - @Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule(); - - private String bucketName; - private Storage storage; - private String blobName; - - private Blob blob; - - @Before - public void setUp() { - blobName = "blob"; - bucketName = RemoteStorageHelper.generateBucketName(); - storage = StorageOptions.getDefaultInstance().getService(); - storage.create(BucketInfo.of(bucketName)); - blob = storage.create(BlobInfo.newBuilder(bucketName, blobName).build()); - } - - @After - public void tearDown() { - if (blob != null && blob.exists()) { - blob.delete(); - } - storage.delete(bucketName); - } - - @Test - public void testConfigureRetries() { - ConfigureRetries.deleteBlob(bucketName, blobName); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("Deletion"); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("successfully"); - assertThat(stdOut.getCapturedOutputAsUtf8String()).doesNotContain("unsuccessfully"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/ITBucketSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITBucketSnippets.java deleted file mode 100644 index dc68167a68..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/ITBucketSnippets.java +++ /dev/null @@ -1,705 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.example.storage.bucket.AddBucketIamConditionalBinding; -import com.example.storage.bucket.AddBucketIamMember; -import com.example.storage.bucket.AddBucketLabel; -import com.example.storage.bucket.ChangeDefaultStorageClass; -import com.example.storage.bucket.ConfigureBucketCors; -import com.example.storage.bucket.CreateBucket; -import com.example.storage.bucket.CreateBucketWithObjectRetention; -import com.example.storage.bucket.CreateBucketWithStorageClassAndLocation; -import com.example.storage.bucket.CreateBucketWithTurboReplication; -import com.example.storage.bucket.DeleteBucket; -import com.example.storage.bucket.DisableBucketVersioning; -import com.example.storage.bucket.DisableDefaultEventBasedHold; -import com.example.storage.bucket.DisableLifecycleManagement; -import com.example.storage.bucket.DisableRequesterPays; -import com.example.storage.bucket.DisableUniformBucketLevelAccess; -import com.example.storage.bucket.EnableBucketVersioning; -import com.example.storage.bucket.EnableDefaultEventBasedHold; -import com.example.storage.bucket.EnableLifecycleManagement; -import com.example.storage.bucket.EnableRequesterPays; -import com.example.storage.bucket.EnableUniformBucketLevelAccess; -import com.example.storage.bucket.GetBucketMetadata; -import com.example.storage.bucket.GetBucketRpo; -import com.example.storage.bucket.GetDefaultEventBasedHold; -import com.example.storage.bucket.GetPublicAccessPrevention; -import com.example.storage.bucket.GetRetentionPolicy; -import com.example.storage.bucket.GetUniformBucketLevelAccess; -import com.example.storage.bucket.ListBucketIamMembers; -import com.example.storage.bucket.ListBuckets; -import com.example.storage.bucket.LockRetentionPolicy; -import com.example.storage.bucket.MakeBucketPublic; -import com.example.storage.bucket.RemoveBucketCors; -import com.example.storage.bucket.RemoveBucketDefaultKmsKey; -import com.example.storage.bucket.RemoveBucketIamConditionalBinding; -import com.example.storage.bucket.RemoveBucketIamMember; -import com.example.storage.bucket.RemoveBucketLabel; -import com.example.storage.bucket.RemoveRetentionPolicy; -import com.example.storage.bucket.SetAsyncTurboRpo; -import com.example.storage.bucket.SetBucketDefaultKmsKey; -import com.example.storage.bucket.SetBucketWebsiteInfo; -import com.example.storage.bucket.SetClientEndpoint; -import com.example.storage.bucket.SetDefaultRpo; -import com.example.storage.bucket.SetPublicAccessPreventionEnforced; -import com.example.storage.bucket.SetPublicAccessPreventionInherited; -import com.example.storage.bucket.SetRetentionPolicy; -import com.example.storage.object.DownloadRequesterPaysObject; -import com.example.storage.object.ReleaseEventBasedHold; -import com.example.storage.object.ReleaseTemporaryHold; -import com.example.storage.object.SetEventBasedHold; -import com.example.storage.object.SetTemporaryHold; -import com.google.api.gax.retrying.RetrySettings; -import com.google.cloud.Identity; -import com.google.cloud.ServiceOptions; -import com.google.cloud.storage.Blob; -import com.google.cloud.storage.BlobInfo; -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.BucketInfo.PublicAccessPrevention; -import com.google.cloud.storage.Cors; -import com.google.cloud.storage.HttpMethod; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.Storage.BlobTargetOption; -import com.google.cloud.storage.StorageRoles; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.Timeout; -import org.threeten.bp.Duration; - -public class ITBucketSnippets { - - private static final Logger log = Logger.getLogger(ITBucketSnippets.class.getName()); - private static final String BUCKET = RemoteStorageHelper.generateBucketName(); - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String KMS_KEY_NAME = - "projects/cloud-java-ci-sample/locations/us/keyRings/" - + "gcs_test_kms_key_ring/cryptoKeys/gcs_kms_key_one"; - private static final RetrySettings RETRY_SETTINGS = - RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.ofSeconds(2)) - .setRetryDelayMultiplier(1.75) - .setTotalTimeout(Duration.ofSeconds(90)) - .setMaxRetryDelay(Duration.ofSeconds(10)) - .build(); - - private static Storage storage; - - @Rule public final StdOutCaptureRule stdOutCaptureRule = new StdOutCaptureRule(); - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Rule public Timeout globalTimeout = Timeout.seconds(300); - - @BeforeClass - public static void beforeClass() { - RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = - helper - .getOptions() - .toBuilder() - .setRetrySettings( - helper - .getOptions() - .getRetrySettings() - .toBuilder() - .setRetryDelayMultiplier(3.0) - .build()) - .build() - .getService(); - storage.create(BucketInfo.of(BUCKET)); - } - - @AfterClass - public static void afterClass() throws ExecutionException, InterruptedException { - if (storage != null) { - boolean wasDeleted = RemoteStorageHelper.forceDelete(storage, BUCKET, 5, TimeUnit.SECONDS); - if (!wasDeleted && log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, "Deletion of bucket {0} timed out, bucket is not empty", BUCKET); - } - } - } - - @After - public void after() throws Exception { - // This avoids 429 errors - Thread.sleep(3000); - } - - @Test - public void testAddBucketLabel() { - int oldSize = storage.get(BUCKET).getLabels().size(); - AddBucketLabel.addBucketLabel(PROJECT_ID, BUCKET, "key", "value"); - assertEquals(oldSize + 1, storage.get(BUCKET).getLabels().size()); - } - - @Test - public void testChangeDefaultStorageClass() throws Throwable { - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> assertEquals("STANDARD", storage.get(BUCKET).getStorageClass().name())); - ChangeDefaultStorageClass.changeDefaultStorageClass(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> assertEquals("COLDLINE", storage.get(BUCKET).getStorageClass().name())); - } - - @Test - public void testCreateBucket() { - String newBucket = RemoteStorageHelper.generateBucketName(); - CreateBucket.createBucket(PROJECT_ID, newBucket); - try { - Bucket remoteBucket = storage.get(newBucket); - assertNotNull(remoteBucket); - } finally { - storage.delete(newBucket); - } - } - - @Test - public void testCreateBucketWithStorageClassAndLocation() { - String newBucket = RemoteStorageHelper.generateBucketName(); - CreateBucketWithStorageClassAndLocation.createBucketWithStorageClassAndLocation( - PROJECT_ID, newBucket); - try { - Bucket remoteBucket = storage.get(newBucket); - assertNotNull(remoteBucket); - assertEquals("COLDLINE", remoteBucket.getStorageClass().name()); - assertEquals("ASIA", remoteBucket.getLocation()); - } finally { - storage.delete(newBucket); - } - } - - @Test - public void testDeleteBucket() { - String newBucket = RemoteStorageHelper.generateBucketName(); - storage.create(BucketInfo.newBuilder(newBucket).build()); - assertNotNull(storage.get(newBucket)); - try { - DeleteBucket.deleteBucket(PROJECT_ID, newBucket); - assertNull(storage.get(newBucket)); - } finally { - storage.delete(newBucket); - } - } - - @Test - public void testGetBucketMetadata() { - Bucket bucket = - storage.get(BUCKET, Storage.BucketGetOption.fields(Storage.BucketField.values())); - bucket = - bucket - .toBuilder() - .setLabels(ImmutableMap.of("k", "v")) - .setLifecycleRules( - ImmutableList.of( - new BucketInfo.LifecycleRule( - BucketInfo.LifecycleRule.LifecycleAction.newDeleteAction(), - BucketInfo.LifecycleRule.LifecycleCondition.newBuilder() - .setAge(5) - .build()))) - .build() - .update(); - - GetBucketMetadata.getBucketMetadata(PROJECT_ID, BUCKET); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains(("BucketName: " + bucket.getName()))); - assertTrue( - snippetOutput.contains(("DefaultEventBasedHold: " + bucket.getDefaultEventBasedHold()))); - assertTrue(snippetOutput.contains(("DefaultKmsKeyName: " + bucket.getDefaultKmsKeyName()))); - assertTrue(snippetOutput.contains(("Id: " + bucket.getGeneratedId()))); - assertTrue(snippetOutput.contains(("IndexPage: " + bucket.getIndexPage()))); - assertTrue(snippetOutput.contains(("Location: " + bucket.getLocation()))); - assertTrue(snippetOutput.contains(("LocationType: " + bucket.getLocationType()))); - assertTrue(snippetOutput.contains(("Metageneration: " + bucket.getMetageneration()))); - assertTrue(snippetOutput.contains(("NotFoundPage: " + bucket.getNotFoundPage()))); - assertTrue( - snippetOutput.contains(("RetentionEffectiveTime: " + bucket.getRetentionEffectiveTime()))); - assertTrue(snippetOutput.contains(("RetentionPeriod: " + bucket.getRetentionPeriod()))); - assertTrue( - snippetOutput.contains(("RetentionPolicyIsLocked: " + bucket.retentionPolicyIsLocked()))); - assertTrue(snippetOutput.contains(("RequesterPays: " + bucket.requesterPays()))); - assertTrue(snippetOutput.contains(("SelfLink: " + bucket.getSelfLink()))); - assertTrue(snippetOutput.contains(("StorageClass: " + bucket.getStorageClass().name()))); - assertTrue(snippetOutput.contains(("TimeCreated: " + bucket.getCreateTime()))); - assertTrue(snippetOutput.contains(("VersioningEnabled: " + bucket.versioningEnabled()))); - assertTrue(snippetOutput.contains("Labels:")); - assertTrue(snippetOutput.contains("k=v")); - assertTrue(snippetOutput.contains("Lifecycle Rules:")); - assertTrue(snippetOutput.contains("ObjectRetention: " + bucket.getObjectRetention())); - } - - @Test - public void testListBuckets() { - ListBuckets.listBuckets(PROJECT_ID); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains(BUCKET)); - } - - @Test - public void testRemoveBucketLabel() { - storage.get(BUCKET).toBuilder().setLabels(ImmutableMap.of("k", "v")).build().update(); - int oldSize = storage.get(BUCKET).getLabels().size(); - RemoveBucketLabel.removeBucketLabel(PROJECT_ID, BUCKET, "k"); - Map labels = storage.get(BUCKET).getLabels(); - if (labels != null) { - assertEquals(oldSize - 1, labels.size()); - } - } - - @Test - public void testEnableLifecycleManagement() throws Throwable { - EnableLifecycleManagement.enableLifecycleManagement(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertEquals(1, storage.get(BUCKET).getLifecycleRules().size())); - } - - @Test - public void testDisableLifecycleManagement() throws Throwable { - storage - .get(BUCKET) - .toBuilder() - .setLifecycleRules( - ImmutableList.of( - new BucketInfo.LifecycleRule( - BucketInfo.LifecycleRule.LifecycleAction.newDeleteAction(), - BucketInfo.LifecycleRule.LifecycleCondition.newBuilder().setAge(5).build()))) - .build() - .update(); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertEquals(1, storage.get(BUCKET).getLifecycleRules().size())); - DisableLifecycleManagement.disableLifecycleManagement(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertEquals(0, storage.get(BUCKET).getLifecycleRules().size())); - } - - @Test - public void testGetPublicAccessPrevention() throws Throwable { - try { - // By default a bucket PAP state is INHERITED and we are changing the state to validate - // non-default state. - storage - .get(BUCKET) - .toBuilder() - .setIamConfiguration( - BucketInfo.IamConfiguration.newBuilder() - .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED) - .build()) - .build() - .update(); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> - assertThat(storage.get(BUCKET).getIamConfiguration().getPublicAccessPrevention()) - .isEqualTo(PublicAccessPrevention.ENFORCED)); - GetPublicAccessPrevention.getPublicAccessPrevention(PROJECT_ID, BUCKET); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("enforced")); - } finally { - // No matter what happens make sure test set bucket back to INHERITED - storage - .get(BUCKET) - .toBuilder() - .setIamConfiguration( - BucketInfo.IamConfiguration.newBuilder() - .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.INHERITED) - .build()) - .build() - .update(); - } - } - - @Test - public void testSetPublicAccessPreventionEnforced() throws Throwable { - try { - SetPublicAccessPreventionEnforced.setPublicAccessPreventionEnforced(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> - assertEquals( - storage.get(BUCKET).getIamConfiguration().getPublicAccessPrevention(), - BucketInfo.PublicAccessPrevention.ENFORCED)); - } finally { - // No matter what happens make sure test set bucket back to INHERITED - storage - .get(BUCKET) - .toBuilder() - .setIamConfiguration( - BucketInfo.IamConfiguration.newBuilder() - .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.INHERITED) - .build()) - .build() - .update(); - } - } - - @Test - public void testSetPublicAccessPreventionInherited() throws Throwable { - try { - storage - .get(BUCKET) - .toBuilder() - .setIamConfiguration( - BucketInfo.IamConfiguration.newBuilder() - .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.ENFORCED) - .build()) - .build() - .update(); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> - assertThat(storage.get(BUCKET).getIamConfiguration().getPublicAccessPrevention()) - .isEqualTo(PublicAccessPrevention.ENFORCED)); - - SetPublicAccessPreventionInherited.setPublicAccessPreventionInherited(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> - assertEquals( - storage.get(BUCKET).getIamConfiguration().getPublicAccessPrevention(), - BucketInfo.PublicAccessPrevention.INHERITED)); - } finally { - // No matter what happens make sure test set bucket back to INHERITED - storage - .get(BUCKET) - .toBuilder() - .setIamConfiguration( - BucketInfo.IamConfiguration.newBuilder() - .setPublicAccessPrevention(BucketInfo.PublicAccessPrevention.INHERITED) - .build()) - .build() - .update(); - } - } - - @Test - public void testAddListRemoveBucketIamMembers() throws Throwable { - storage.update( - BucketInfo.newBuilder(BUCKET) - .setIamConfiguration( - BucketInfo.IamConfiguration.newBuilder() - .setIsUniformBucketLevelAccessEnabled(true) - .build()) - .build()); - // todo: - int originalSize = storage.getIamPolicy(BUCKET).getBindingsList().size(); - AddBucketIamMember.addBucketIamMember(PROJECT_ID, BUCKET); - assertEquals(originalSize + 1, storage.getIamPolicy(BUCKET).getBindingsList().size()); - ListBucketIamMembers.listBucketIamMembers(PROJECT_ID, BUCKET); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("example@google.com")); - RemoveBucketIamMember.removeBucketIamMember(PROJECT_ID, BUCKET); - assertEquals(originalSize, storage.getIamPolicy(BUCKET).getBindingsList().size()); - AddBucketIamConditionalBinding.addBucketIamConditionalBinding(PROJECT_ID, BUCKET); - assertEquals(originalSize + 1, storage.getIamPolicy(BUCKET).getBindingsList().size()); - RemoveBucketIamConditionalBinding.removeBucketIamConditionalBinding(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> assertEquals(originalSize, storage.getIamPolicy(BUCKET).getBindingsList().size())); - storage.update( - BucketInfo.newBuilder(BUCKET) - .setIamConfiguration( - BucketInfo.IamConfiguration.newBuilder() - .setIsUniformBucketLevelAccessEnabled(false) - .build()) - .build()); - } - - @Test - public void testMakeBucketPublic() throws Throwable { - MakeBucketPublic.makeBucketPublic(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> - assertTrue( - storage - .getIamPolicy(BUCKET) - .getBindings() - .get(StorageRoles.objectViewer()) - .contains(Identity.allUsers()))); - } - - @Test - public void deleteBucketDefaultKmsKey() throws Throwable { - storage - .get(BUCKET) - .toBuilder() - .setDefaultKmsKeyName( - "projects/cloud-java-ci-sample/locations/us/keyRings/" - + "gcs_test_kms_key_ring/cryptoKeys/gcs_kms_key_one") - .build() - .update(); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertNotNull(storage.get(BUCKET).getDefaultKmsKeyName())); - RemoveBucketDefaultKmsKey.removeBucketDefaultKmsKey(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertNull(storage.get(BUCKET).getDefaultKmsKeyName())); - } - - @Test - public void testEnableDisableVersioning() throws Throwable { - EnableBucketVersioning.enableBucketVersioning(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertTrue(storage.get(BUCKET).versioningEnabled())); - DisableBucketVersioning.disableBucketVersioning(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertFalse(storage.get(BUCKET).versioningEnabled())); - } - - @Test - public void testSetBucketWebsiteInfo() throws Throwable { - SetBucketWebsiteInfo.setBucketWesbiteInfo(PROJECT_ID, BUCKET, "index.html", "404.html"); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> { - Bucket bucket = storage.get(BUCKET); - assertEquals("index.html", bucket.getIndexPage()); - assertEquals("404.html", bucket.getNotFoundPage()); - }); - } - - @Test - public void testSetClientEndpoint() { - SetClientEndpoint.setClientEndpoint(PROJECT_ID, "https://storage.googleapis.com"); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("https://storage.googleapis.com")); - } - - @Test - public void testConfigureBucketCors() throws Throwable { - ConfigureBucketCors.configureBucketCors( - PROJECT_ID, BUCKET, "http://example.appspot.com", "Content-Type", 3600); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> { - Cors cors = storage.get(BUCKET).getCors().get(0); - assertTrue(cors.getOrigins().get(0).toString().contains("example.appspot.com")); - assertTrue(cors.getResponseHeaders().contains("Content-Type")); - assertEquals(3600, cors.getMaxAgeSeconds().intValue()); - assertTrue(cors.getMethods().get(0).toString().equalsIgnoreCase("GET")); - }); - } - - @Test - public void testRemoveBucketCors() throws Throwable { - storage - .get(BUCKET) - .toBuilder() - .setCors( - ImmutableList.of( - Cors.newBuilder() - .setOrigins(ImmutableList.of(Cors.Origin.of("http://example.appspot.com"))) - .setMethods(ImmutableList.of(HttpMethod.GET)) - .setResponseHeaders(ImmutableList.of("Content-Type")) - .setMaxAgeSeconds(3600) - .build())) - .build() - .update(); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> { - Cors cors = storage.get(BUCKET).getCors().get(0); - assertNotNull(cors); - assertTrue(cors.getOrigins().get(0).toString().contains("example.appspot.com")); - assertTrue(cors.getResponseHeaders().contains("Content-Type")); - assertEquals(3600, cors.getMaxAgeSeconds().intValue()); - assertTrue(cors.getMethods().get(0).toString().equalsIgnoreCase("GET")); - }); - RemoveBucketCors.removeBucketCors(PROJECT_ID, BUCKET); - TestUtils.retryAssert(RETRY_SETTINGS, () -> assertNull(storage.get(BUCKET).getCors())); - } - - @Test - public void testRequesterPays() throws Throwable { - EnableRequesterPays.enableRequesterPays(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> - assertTrue( - storage - .get(BUCKET, Storage.BucketGetOption.userProject(PROJECT_ID)) - .requesterPays())); - String projectId = ServiceOptions.getDefaultProjectId(); - String blobName = "test-create-empty-blob-requester-pays"; - byte[] content = {0xD, 0xE, 0xA, 0xD}; - Blob remoteBlob = - storage.create( - BlobInfo.newBuilder(BUCKET, blobName).build(), - content, - BlobTargetOption.userProject(projectId)); - assertNotNull(remoteBlob); - DownloadRequesterPaysObject.downloadRequesterPaysObject( - projectId, BUCKET, blobName, Paths.get(blobName)); - byte[] readBytes = Files.readAllBytes(Paths.get(blobName)); - assertArrayEquals(content, readBytes); - DisableRequesterPays.disableRequesterPays(PROJECT_ID, BUCKET); - TestUtils.retryAssert(RETRY_SETTINGS, () -> assertFalse(storage.get(BUCKET).requesterPays())); - } - - @Test - public void testRpo() throws Throwable { - String rpoBucket = RemoteStorageHelper.generateBucketName(); - try { - CreateBucketWithTurboReplication.createBucketWithTurboReplication( - PROJECT_ID, rpoBucket, "NAM4"); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> assertEquals("ASYNC_TURBO", storage.get(rpoBucket).getRpo().toString())); - - SetDefaultRpo.setDefaultRpo(PROJECT_ID, rpoBucket); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> assertEquals("DEFAULT", storage.get(rpoBucket).getRpo().toString())); - - SetAsyncTurboRpo.setAsyncTurboRpo(PROJECT_ID, rpoBucket); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> assertEquals("ASYNC_TURBO", storage.get(rpoBucket).getRpo().toString())); - - GetBucketRpo.getBucketRpo(PROJECT_ID, rpoBucket); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("ASYNC_TURBO")); - } finally { - storage.delete(rpoBucket); - } - } - - @Test - public void testDefaultKMSKey() throws Throwable { - SetBucketDefaultKmsKey.setBucketDefaultKmsKey(PROJECT_ID, BUCKET, KMS_KEY_NAME); - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> assertEquals(KMS_KEY_NAME, storage.get(BUCKET).getDefaultKmsKeyName())); - - RemoveBucketDefaultKmsKey.removeBucketDefaultKmsKey(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertNull(storage.get(BUCKET).getDefaultKmsKeyName())); - } - - @Test - public void testBucketRetention() throws Throwable { - Long retention = 5L; - SetRetentionPolicy.setRetentionPolicy(PROJECT_ID, BUCKET, retention); - Bucket bucket = storage.get(BUCKET); - assertEquals(retention, bucket.getRetentionPeriod()); - assertNotNull(bucket.getRetentionEffectiveTime()); - - GetRetentionPolicy.getRetentionPolicy(PROJECT_ID, BUCKET); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("5")); - - EnableDefaultEventBasedHold.enableDefaultEventBasedHold(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertTrue(storage.get(BUCKET).getDefaultEventBasedHold())); - - GetDefaultEventBasedHold.getDefaultEventBasedHold(PROJECT_ID, BUCKET); - snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("enabled")); - - byte[] content = {0xD, 0xE, 0xA, 0xD}; - String blobName = "test-create-empty-blob-retention-policy"; - bucket.create(blobName, content); - SetEventBasedHold.setEventBasedHold(PROJECT_ID, BUCKET, blobName); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertTrue(storage.get(BUCKET, blobName).getEventBasedHold())); - ReleaseEventBasedHold.releaseEventBasedHold(PROJECT_ID, BUCKET, blobName); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertFalse(storage.get(BUCKET, blobName).getEventBasedHold())); - RemoveRetentionPolicy.removeRetentionPolicy(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertNull(storage.get(BUCKET).getRetentionPeriod())); - DisableDefaultEventBasedHold.disableDefaultEventBasedHold(PROJECT_ID, BUCKET); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertFalse(storage.get(BUCKET).getDefaultEventBasedHold())); - SetTemporaryHold.setTemporaryHold(PROJECT_ID, BUCKET, blobName); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertTrue(storage.get(BUCKET, blobName).getTemporaryHold())); - ReleaseTemporaryHold.releaseTemporaryHold(PROJECT_ID, BUCKET, blobName); - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertFalse(storage.get(BUCKET, blobName).getTemporaryHold())); - } - - @Test - public void testLockRetentionPolicy() { - String tempBucket = RemoteStorageHelper.generateBucketName(); - Bucket bucket = storage.create(BucketInfo.of(tempBucket)); - assertNotNull(bucket); - try { - SetRetentionPolicy.setRetentionPolicy(PROJECT_ID, tempBucket, 5L); - assertEquals(5L, (long) storage.get(tempBucket).getRetentionPeriod()); - LockRetentionPolicy.lockRetentionPolicy(PROJECT_ID, tempBucket); - assertTrue(storage.get(tempBucket).retentionPolicyIsLocked()); - } finally { - storage.delete(tempBucket); - } - } - - @Test - public void testUniformBucketLevelAccess() { - EnableUniformBucketLevelAccess.enableUniformBucketLevelAccess(PROJECT_ID, BUCKET); - Bucket bucket = storage.get(BUCKET); - assertTrue(bucket.getIamConfiguration().isUniformBucketLevelAccessEnabled()); - assertNotNull(bucket.getIamConfiguration().getUniformBucketLevelAccessLockedTime()); - - GetUniformBucketLevelAccess.getUniformBucketLevelAccess(PROJECT_ID, BUCKET); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("enabled")); - - DisableUniformBucketLevelAccess.disableUniformBucketLevelAccess(PROJECT_ID, BUCKET); - assertFalse(storage.get(BUCKET).getIamConfiguration().isUniformBucketLevelAccessEnabled()); - } - - @Test - public void testCreateBucketWithObjectRetention() { - String tempBucket = RemoteStorageHelper.generateBucketName(); - - try { - CreateBucketWithObjectRetention.createBucketWithObjectRetention(PROJECT_ID, tempBucket); - assertNotNull(storage.get(tempBucket).getObjectRetention()); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("Enabled")); - } finally { - storage.delete(tempBucket); - } - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/ITHmacSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITHmacSnippets.java deleted file mode 100644 index 4e27749621..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/ITHmacSnippets.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2019 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import com.example.storage.hmac.ActivateHmacKey; -import com.example.storage.hmac.CreateHmacKey; -import com.example.storage.hmac.DeactivateHmacKey; -import com.example.storage.hmac.DeleteHmacKey; -import com.example.storage.hmac.GetHmacKey; -import com.example.storage.hmac.ListHmacKeys; -import com.google.api.gax.paging.Page; -import com.google.cloud.ServiceOptions; -import com.google.cloud.storage.HmacKey; -import com.google.cloud.storage.HmacKey.HmacKeyMetadata; -import com.google.cloud.storage.HmacKey.HmacKeyState; -import com.google.cloud.storage.ServiceAccount; -import com.google.cloud.storage.Storage; -import com.google.cloud.testing.junit4.MultipleAttemptsRule; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public class ITHmacSnippets extends TestBase { - private static final String PROJECT_ID = ServiceOptions.getDefaultProjectId(); - private static final String HMAC_KEY_TEST_SERVICE_ACCOUNT = - PROJECT_ID + "@" + PROJECT_ID + ".iam.gserviceaccount.com"; - - @Before - public void before() { - cleanUpHmacKeys(ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT)); - } - - @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(5, 2000L); - - private void cleanUpHmacKeys(ServiceAccount serviceAccount) { - Page metadatas = - storage.listHmacKeys(Storage.ListHmacKeysOption.serviceAccount(serviceAccount)); - for (HmacKey.HmacKeyMetadata hmacKeyMetadata : metadatas.iterateAll()) { - if (hmacKeyMetadata.getState() == HmacKeyState.ACTIVE) { - hmacKeyMetadata = storage.updateHmacKeyState(hmacKeyMetadata, HmacKeyState.INACTIVE); - } - if (hmacKeyMetadata.getState() == HmacKeyState.INACTIVE) { - storage.deleteHmacKey(hmacKeyMetadata); - } - } - } - - @Test - public void testCreateHmacKey() throws Exception { - CreateHmacKey.createHmacKey(HMAC_KEY_TEST_SERVICE_ACCOUNT, PROJECT_ID); - String snippetOutput = stdOut.getCapturedOutputAsUtf8String(); - String accessId = snippetOutput.split("Access ID: ")[1].split("\n")[0]; - Thread.sleep(5000); - assertNotNull(storage.getHmacKey(accessId)); - } - - @Test - public void testGetHmacKey() throws Exception { - HmacKey hmacKey = storage.createHmacKey(ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT)); - Thread.sleep(5000); - GetHmacKey.getHmacKey(hmacKey.getMetadata().getAccessId(), PROJECT_ID); - String snippetOutput = stdOut.getCapturedOutputAsUtf8String(); - Assert.assertTrue(snippetOutput.contains(HMAC_KEY_TEST_SERVICE_ACCOUNT)); - } - - @Test - public void testActivateHmacKey() throws Exception { - HmacKey hmacKey = storage.createHmacKey(ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT)); - HmacKeyMetadata metadata = - storage.updateHmacKeyState(hmacKey.getMetadata(), HmacKeyState.INACTIVE); - - ActivateHmacKey.activateHmacKey(metadata.getAccessId(), PROJECT_ID); - Thread.sleep(5000); - assertEquals(HmacKeyState.ACTIVE, storage.getHmacKey(metadata.getAccessId()).getState()); - } - - @Test - public void testDeactivateHmacKey() throws Exception { - HmacKey hmacKey = storage.createHmacKey(ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT)); - Thread.sleep(5000); - DeactivateHmacKey.deactivateHmacKey(hmacKey.getMetadata().getAccessId(), PROJECT_ID); - assertEquals( - HmacKeyState.INACTIVE, storage.getHmacKey(hmacKey.getMetadata().getAccessId()).getState()); - } - - @Test - public void testDeleteHmacKey() { - HmacKey hmacKey = storage.createHmacKey(ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT)); - HmacKeyMetadata metadata = - storage.updateHmacKeyState(hmacKey.getMetadata(), HmacKeyState.INACTIVE); - - DeleteHmacKey.deleteHmacKey(metadata.getAccessId(), PROJECT_ID); - assertEquals(HmacKeyState.DELETED, storage.getHmacKey(metadata.getAccessId()).getState()); - } - - @Test - public void testListHmacKeys() { - // Create 2 HMAC keys - final HmacKey one = - storage.createHmacKey( - ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT), - Storage.CreateHmacKeyOption.projectId(PROJECT_ID)); - final HmacKey two = - storage.createHmacKey( - ServiceAccount.of(HMAC_KEY_TEST_SERVICE_ACCOUNT), - Storage.CreateHmacKeyOption.projectId(PROJECT_ID)); - - ListHmacKeys.listHmacKeys(PROJECT_ID); - String snippetOutput = stdOut.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains(one.getMetadata().getAccessId())); - assertTrue(snippetOutput.contains(two.getMetadata().getAccessId())); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/ITObjectSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITObjectSnippets.java deleted file mode 100644 index 0ebaa55c6d..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/ITObjectSnippets.java +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.example.storage.object.BatchSetObjectMetadata; -import com.example.storage.object.ChangeObjectCsekToKms; -import com.example.storage.object.ChangeObjectStorageClass; -import com.example.storage.object.ComposeObject; -import com.example.storage.object.CopyObject; -import com.example.storage.object.CopyOldVersionOfObject; -import com.example.storage.object.DeleteObject; -import com.example.storage.object.DeleteOldVersionOfObject; -import com.example.storage.object.DownloadEncryptedObject; -import com.example.storage.object.DownloadObject; -import com.example.storage.object.DownloadObjectIntoMemory; -import com.example.storage.object.DownloadPublicObject; -import com.example.storage.object.GenerateEncryptionKey; -import com.example.storage.object.GenerateV4GetObjectSignedUrl; -import com.example.storage.object.GenerateV4PutObjectSignedUrl; -import com.example.storage.object.GetObjectMetadata; -import com.example.storage.object.ListObjects; -import com.example.storage.object.ListObjectsWithOldVersions; -import com.example.storage.object.ListObjectsWithPrefix; -import com.example.storage.object.MakeObjectPublic; -import com.example.storage.object.MoveObject; -import com.example.storage.object.RotateObjectEncryptionKey; -import com.example.storage.object.SetObjectMetadata; -import com.example.storage.object.SetObjectRetentionPolicy; -import com.example.storage.object.StreamObjectDownload; -import com.example.storage.object.StreamObjectUpload; -import com.example.storage.object.UploadEncryptedObject; -import com.example.storage.object.UploadKmsEncryptedObject; -import com.example.storage.object.UploadObject; -import com.example.storage.object.UploadObjectFromMemory; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Blob; -import com.google.cloud.storage.BlobId; -import com.google.cloud.storage.BlobInfo; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.Storage.BlobListOption; -import com.google.cloud.storage.StorageClass; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.MultipleAttemptsRule; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.common.collect.ImmutableMap; -import com.google.common.io.BaseEncoding; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.nio.file.Files; -import java.util.Date; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.net.ssl.HttpsURLConnection; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -public class ITObjectSnippets { - - private static final Logger log = Logger.getLogger(ITObjectSnippets.class.getName()); - private static final String BUCKET = RemoteStorageHelper.generateBucketName(); - private static final String BLOB = "blob"; - private static final String STRING_CONTENT = "Hello, World!"; - private static final byte[] CONTENT = STRING_CONTENT.getBytes(UTF_8); - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String KMS_KEY_NAME = - "projects/cloud-java-ci-sample/locations/us/keyRings/" - + "gcs_test_kms_key_ring/cryptoKeys/gcs_kms_key_one"; - - private static Storage storage; - - @Rule public final StdOutCaptureRule stdOutCaptureRule = new StdOutCaptureRule(); - - @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(5); - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @BeforeClass - public static void beforeClass() { - RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.getOptions().getService(); - storage.create(BucketInfo.of(BUCKET)); - storage.create(BlobInfo.newBuilder(BUCKET, BLOB).build(), CONTENT); - } - - @AfterClass - public static void afterClass() throws ExecutionException, InterruptedException { - if (storage != null) { - for (BlobInfo info : storage.list(BUCKET, BlobListOption.versions(true)).getValues()) { - storage.delete(info.getBlobId()); - } - boolean wasDeleted = RemoteStorageHelper.forceDelete(storage, BUCKET, 5, TimeUnit.SECONDS); - if (!wasDeleted && log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, "Deletion of bucket {0} timed out, bucket is not empty", BUCKET); - } - } - } - - @Test - public void testChangeObjectStorageClass() { - Blob blob = storage.get(BUCKET, BLOB); - Assert.assertNotEquals(StorageClass.COLDLINE, blob.getStorageClass()); - ChangeObjectStorageClass.changeObjectStorageClass(PROJECT_ID, BUCKET, BLOB); - assertEquals(StorageClass.COLDLINE, storage.get(BUCKET, BLOB).getStorageClass()); - assertArrayEquals(CONTENT, storage.get(BUCKET, BLOB).getContent()); - } - - @Test - public void testCopyObject() { - String newBucket = RemoteStorageHelper.generateBucketName(); - storage.create(BucketInfo.newBuilder(newBucket).build()); - try { - CopyObject.copyObject(PROJECT_ID, BUCKET, BLOB, newBucket); - assertNotNull(storage.get(newBucket, BLOB)); - } finally { - storage.delete(newBucket, BLOB); - storage.delete(newBucket); - } - } - - @Test - public void testDeleteObject() { - String blob = "deletethisblob"; - storage.create(BlobInfo.newBuilder(BlobId.of(BUCKET, blob)).build()); - assertNotNull(storage.get(BUCKET, blob)); - DeleteObject.deleteObject(PROJECT_ID, BUCKET, blob); - assertNull(storage.get(BUCKET, blob)); - } - - @Test - public void testDownloadObject() throws IOException { - File tempFile = File.createTempFile("file", ".txt"); - try { - DownloadObject.downloadObject(PROJECT_ID, BUCKET, BLOB, tempFile.getPath()); - assertEquals("Hello, World!", new String(Files.readAllBytes(tempFile.toPath()))); - } finally { - tempFile.delete(); - } - } - - @Test - public void testDownloadObjectIntoMemory() throws IOException { - DownloadObjectIntoMemory.downloadObjectIntoMemory(PROJECT_ID, BUCKET, BLOB); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - } - - @Test - public void testDownloadPublicObject() throws IOException { - String publicBlob = "publicblob" + System.currentTimeMillis(); - BlobId publicBlobId = BlobId.of(BUCKET, publicBlob); - storage.create(BlobInfo.newBuilder(publicBlobId).build(), CONTENT); - storage.createAcl(publicBlobId, Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER)); - File tempFile = File.createTempFile("file", ".txt"); - try { - DownloadPublicObject.downloadPublicObject(BUCKET, publicBlob, tempFile.toPath()); - assertEquals("Hello, World!", new String(Files.readAllBytes(tempFile.toPath()))); - } finally { - tempFile.delete(); - } - } - - @Test - public void testGetObjectMetadata() { - String blobName = "test-create-empty-blob"; - BlobId blobId = BlobId.of(BUCKET, blobName); - BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setMetadata(ImmutableMap.of("k", "v")).build(); - Blob remoteBlob = storage.create(blobInfo, CONTENT); - assertNotNull(remoteBlob); - GetObjectMetadata.getObjectMetadata(PROJECT_ID, BUCKET, blobName); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("Bucket: " + remoteBlob.getBucket())); - assertTrue(snippetOutput.contains("Bucket: " + remoteBlob.getBucket())); - assertTrue(snippetOutput.contains("CacheControl: " + remoteBlob.getCacheControl())); - assertTrue(snippetOutput.contains("ComponentCount: " + remoteBlob.getComponentCount())); - assertTrue(snippetOutput.contains("ContentDisposition: " + remoteBlob.getContentDisposition())); - assertTrue(snippetOutput.contains("ContentEncoding: " + remoteBlob.getContentEncoding())); - assertTrue(snippetOutput.contains("ContentLanguage: " + remoteBlob.getContentLanguage())); - assertTrue(snippetOutput.contains("ContentType: " + remoteBlob.getContentType())); - assertTrue(snippetOutput.contains("CustomTime: " + remoteBlob.getCustomTime())); - assertTrue(snippetOutput.contains("Crc32c: " + remoteBlob.getCrc32c())); - assertTrue(snippetOutput.contains("Crc32cHexString: " + remoteBlob.getCrc32cToHexString())); - assertTrue(snippetOutput.contains("ETag: " + remoteBlob.getEtag())); - assertTrue(snippetOutput.contains("Generation: " + remoteBlob.getGeneration())); - assertTrue(snippetOutput.contains("Id: " + remoteBlob.getBlobId())); - assertTrue(snippetOutput.contains("KmsKeyName: " + remoteBlob.getKmsKeyName())); - assertTrue(snippetOutput.contains("Md5Hash: " + remoteBlob.getMd5())); - assertTrue(snippetOutput.contains("Md5HexString: " + remoteBlob.getMd5ToHexString())); - assertTrue(snippetOutput.contains("MediaLink: " + remoteBlob.getMediaLink())); - assertTrue(snippetOutput.contains("Metageneration: " + remoteBlob.getMetageneration())); - assertTrue(snippetOutput.contains("Name: " + remoteBlob.getName())); - assertTrue(snippetOutput.contains("Size: " + remoteBlob.getSize())); - assertTrue(snippetOutput.contains("StorageClass: " + remoteBlob.getStorageClass())); - assertTrue(snippetOutput.contains("TimeCreated: " + new Date(remoteBlob.getCreateTime()))); - assertTrue( - snippetOutput.contains("Last Metadata Update: " + new Date(remoteBlob.getUpdateTime()))); - assertTrue(snippetOutput.contains("temporaryHold: disabled")); - assertTrue(snippetOutput.contains("eventBasedHold: disabled")); - assertTrue(snippetOutput.contains("User metadata:")); - assertTrue(snippetOutput.contains("k=v")); - assertTrue(snippetOutput.contains("Object Retention Policy: " + remoteBlob.getRetention())); - } - - @Test - public void testListObjects() { - ListObjects.listObjects(PROJECT_ID, BUCKET); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains(BLOB)); - } - - @Test - public void testListObjectsWithPrefix() { - storage.create(BlobInfo.newBuilder(BlobId.of(BUCKET, "a/1.txt")).build()); - storage.create(BlobInfo.newBuilder(BlobId.of(BUCKET, "a/b/2.txt")).build()); - storage.create(BlobInfo.newBuilder(BlobId.of(BUCKET, "a/b/3.txt")).build()); - ListObjectsWithPrefix.listObjectsWithPrefix(PROJECT_ID, BUCKET, "a/"); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue(snippetOutput.contains("a/1.txt")); - assertTrue(snippetOutput.contains("a/b/")); - assertFalse(snippetOutput.contains("a/b/2.txt")); - } - - @Test - public void testMoveObject() { - String blob = "movethisblob"; - String newBlob = "movedthisblob"; - - storage.create(BlobInfo.newBuilder(BlobId.of(BUCKET, blob)).build()); - assertNotNull(storage.get(BUCKET, blob)); - String newBucket = RemoteStorageHelper.generateBucketName(); - storage.create(BucketInfo.newBuilder(newBucket).build()); - try { - MoveObject.moveObject(PROJECT_ID, BUCKET, blob, newBucket, newBlob); - assertNotNull(storage.get(newBucket, newBlob)); - assertNull(storage.get(BUCKET, blob)); - } finally { - storage.delete(newBucket, newBlob); - storage.delete(newBucket); - } - } - - @Test - public void testSetObjectMetadata() { - SetObjectMetadata.setObjectMetadata(PROJECT_ID, BUCKET, BLOB); - Map metadata = storage.get(BUCKET, BLOB).getMetadata(); - assertEquals("value", metadata.get("keyToAddOrUpdate")); - } - - @Test - public void testUploadObject() throws IOException { - File tempFile = File.createTempFile("file", ".txt"); - try { - Files.write(tempFile.toPath(), CONTENT); - UploadObject.uploadObject(PROJECT_ID, BUCKET, "uploadobjecttest", tempFile.getPath()); - assertArrayEquals(CONTENT, storage.get(BUCKET, "uploadobjecttest").getContent()); - } finally { - tempFile.delete(); - } - } - - @Test - public void testUploadObjectFromMemory() throws IOException { - UploadObjectFromMemory.uploadObjectFromMemory( - PROJECT_ID, BUCKET, "uploadobjectfrommemorytest", STRING_CONTENT); - final byte[] output = storage.get(BUCKET, "uploadobjectfrommemorytest").getContent(); - assertEquals(STRING_CONTENT, new String(output, UTF_8)); - } - - @Test - public void testObjectCSEKOperations() throws IOException { - GenerateEncryptionKey.generateEncryptionKey(); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - String encryptionKey = snippetOutput.split(": ")[1].trim(); - - File tempFile = File.createTempFile("file", ".txt"); - File downloadFile = File.createTempFile("dlfile", ".txt"); - String encryptedBlob = "uploadencryptedobjecttest"; - Files.write(tempFile.toPath(), CONTENT); - - UploadEncryptedObject.uploadEncryptedObject( - PROJECT_ID, BUCKET, encryptedBlob, tempFile.getPath(), encryptionKey); - DownloadEncryptedObject.downloadEncryptedObject( - PROJECT_ID, BUCKET, encryptedBlob, downloadFile.toPath(), encryptionKey); - assertArrayEquals(CONTENT, Files.readAllBytes(downloadFile.toPath())); - - byte[] key = new byte[32]; - new Random().nextBytes(key); - String newEncryptionKey = BaseEncoding.base64().encode(key); - RotateObjectEncryptionKey.rotateObjectEncryptionKey( - PROJECT_ID, BUCKET, encryptedBlob, encryptionKey, newEncryptionKey); - File newDownloadFile = File.createTempFile("newdownloadfile", ".txt"); - DownloadEncryptedObject.downloadEncryptedObject( - PROJECT_ID, BUCKET, encryptedBlob, newDownloadFile.toPath(), newEncryptionKey); - assertArrayEquals(CONTENT, Files.readAllBytes(newDownloadFile.toPath())); - - assertNull(storage.get(BUCKET, encryptedBlob).getKmsKeyName()); - ChangeObjectCsekToKms.changeObjectFromCsekToKms( - PROJECT_ID, BUCKET, encryptedBlob, newEncryptionKey, KMS_KEY_NAME); - assertTrue(storage.get(BUCKET, encryptedBlob).getKmsKeyName().contains(KMS_KEY_NAME)); - } - - @Test - public void testObjectVersioningOperations() { - storage.get(BUCKET).toBuilder().setVersioningEnabled(true).build().update(); - String versionedBlob = "versionedblob"; - final Blob originalBlob = - storage.create(BlobInfo.newBuilder(BUCKET, versionedBlob).build(), CONTENT); - byte[] content2 = "Hello, World 2".getBytes(UTF_8); - storage.create(BlobInfo.newBuilder(BUCKET, versionedBlob).build(), content2); - - ListObjectsWithOldVersions.listObjectsWithOldVersions(PROJECT_ID, BUCKET); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - - snippetOutput = snippetOutput.replaceFirst(versionedBlob, ""); - assertTrue(snippetOutput.contains(versionedBlob)); - - CopyOldVersionOfObject.copyOldVersionOfObject( - PROJECT_ID, BUCKET, versionedBlob, originalBlob.getGeneration(), "copiedblob"); - assertArrayEquals(CONTENT, storage.get(BUCKET, "copiedblob").getContent()); - - DeleteOldVersionOfObject.deleteOldVersionOfObject( - PROJECT_ID, BUCKET, versionedBlob, originalBlob.getGeneration()); - assertNull(storage.get(BlobId.of(BUCKET, versionedBlob, originalBlob.getGeneration()))); - assertNotNull(storage.get(BUCKET, versionedBlob)); - } - - @Test - public void testV4SignedURLs() throws IOException { - String tempObject = "test-upload-signed-url-object"; - GenerateV4PutObjectSignedUrl.generateV4PutObjectSignedUrl(PROJECT_ID, BUCKET, tempObject); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - String url = snippetOutput.split("\n")[1]; - URL uploadUrl = new URL(url); - HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection(); - connection.setRequestMethod("PUT"); - connection.setDoOutput(true); - connection.setRequestProperty("Content-Type", "application/octet-stream"); - try (OutputStream out = connection.getOutputStream()) { - out.write(CONTENT); - assertEquals(connection.getResponseCode(), 200); - } - GenerateV4GetObjectSignedUrl.generateV4GetObjectSignedUrl(PROJECT_ID, BUCKET, tempObject); - snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - url = snippetOutput.split("\n")[5]; - URL downloadUrl = new URL(url); - connection = (HttpsURLConnection) downloadUrl.openConnection(); - byte[] readBytes = new byte[CONTENT.length]; - try (InputStream responseStream = connection.getInputStream()) { - assertEquals(CONTENT.length, responseStream.read(readBytes)); - assertArrayEquals(CONTENT, readBytes); - } - } - - @Test - public void testMakeObjectPublic() { - String aclBlob = "acl-test-blob"; - assertNull( - storage.create(BlobInfo.newBuilder(BUCKET, aclBlob).build()).getAcl(Acl.User.ofAllUsers())); - MakeObjectPublic.makeObjectPublic(PROJECT_ID, BUCKET, aclBlob); - assertNotNull(storage.get(BUCKET, aclBlob).getAcl(Acl.User.ofAllUsers())); - } - - @Test - public void testComposeObject() { - String firstObject = "firstObject"; - String secondObject = "secondObject"; - String targetObject = "targetObject"; - storage.create(BlobInfo.newBuilder(BUCKET, firstObject).build(), firstObject.getBytes(UTF_8)); - storage.create(BlobInfo.newBuilder(BUCKET, secondObject).build(), secondObject.getBytes(UTF_8)); - - ComposeObject.composeObject(BUCKET, firstObject, secondObject, targetObject, PROJECT_ID); - - assertArrayEquals( - "firstObjectsecondObject".getBytes(UTF_8), storage.get(BUCKET, targetObject).getContent()); - } - - @Test - public void testStreamUploadDownload() throws Exception { - StreamObjectUpload.streamObjectUpload(PROJECT_ID, BUCKET, "streamBlob", "hello world"); - File file = File.createTempFile("stream", "test"); - StreamObjectDownload.streamObjectDownload( - PROJECT_ID, BUCKET, "streamBlob", file.getAbsolutePath()); - assertArrayEquals(Files.readAllBytes(file.toPath()), "hello world".getBytes()); - file.delete(); - } - - @Test - public void testUploadKMSEncryptedObject() { - String blobName = "kms-encrypted-blob"; - UploadKmsEncryptedObject.uploadKmsEncryptedObject(PROJECT_ID, BUCKET, blobName, KMS_KEY_NAME); - assertNotNull(storage.get(BUCKET, blobName)); - } - - @Test - public void testBatchSetObjectMetadata() { - storage.create(BlobInfo.newBuilder(BUCKET, "b/1.txt").build()); - storage.create(BlobInfo.newBuilder(BUCKET, "b/2.txt").build()); - - BatchSetObjectMetadata.batchSetObjectMetadata(PROJECT_ID, BUCKET, "b/"); - - Map firstBlobMetadata = storage.get(BUCKET, "b/1.txt").getMetadata(); - Map secondBlobMetadata = storage.get(BUCKET, "b/2.txt").getMetadata(); - - assertEquals("value", firstBlobMetadata.get("keyToAddOrUpdate")); - assertEquals("value", secondBlobMetadata.get("keyToAddOrUpdate")); - } - - @Test - public void testSetObjectRetentionPolicy() { - String tempBucket = RemoteStorageHelper.generateBucketName(); - storage.create( - BucketInfo.of(tempBucket), Storage.BucketTargetOption.enableObjectRetention(true)); - String retentionBlob = "retentionblob"; - storage.create(BlobInfo.newBuilder(tempBucket, retentionBlob).build()); - assertNull(storage.get(tempBucket, retentionBlob).getRetention()); - try { - SetObjectRetentionPolicy.setObjectRetentionPolicy(PROJECT_ID, tempBucket, retentionBlob); - assertNotNull(storage.get(tempBucket, retentionBlob).getRetention()); - } finally { - - storage - .get(tempBucket, retentionBlob) - .toBuilder() - .setRetention(null) - .build() - .update(Storage.BlobTargetOption.overrideUnlockedRetention(true)); - storage.delete(tempBucket, retentionBlob); - storage.delete(tempBucket); - } - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/ITStorageSnippets.java b/samples/snippets/src/test/java/com/example/storage/ITStorageSnippets.java deleted file mode 100644 index 9a33bbcdb8..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/ITStorageSnippets.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright 2016 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import java.io.File; -import java.io.FileInputStream; -import java.nio.file.Files; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.mime.MultipartEntityBuilder; -import org.apache.http.impl.client.HttpClientBuilder; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.rules.Timeout; - -public class ITStorageSnippets { - - private static final Logger log = Logger.getLogger(ITStorageSnippets.class.getName()); - private static final String BUCKET = RemoteStorageHelper.generateBucketName(); - private static Storage storage; - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - - @Rule public final StdOutCaptureRule stdOutCaptureRule = new StdOutCaptureRule(); - - @Rule public ExpectedException thrown = ExpectedException.none(); - - @Rule public Timeout globalTimeout = Timeout.seconds(300); - - @BeforeClass - public static void beforeClass() { - RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.getOptions().getService(); - storage.create(BucketInfo.of(BUCKET)); - } - - @AfterClass - public static void afterClass() throws ExecutionException, InterruptedException { - if (storage != null) { - boolean wasDeleted = RemoteStorageHelper.forceDelete(storage, BUCKET, 1, TimeUnit.MINUTES); - if (!wasDeleted && log.isLoggable(Level.WARNING)) { - log.log(Level.WARNING, "Deletion of bucket {0} timed out, bucket is not empty", BUCKET); - } - } - } - - @Test - public void testGetServiceAccount() { - GetServiceAccount.getServiceAccount(PROJECT_ID); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - - assertTrue(snippetOutput.contains("service")); - assertTrue(snippetOutput.contains("@gs-project-accounts.iam.gserviceaccount.com")); - } - - @Test - public void testGenerateSignedPostPolicyV4() throws Exception { - GenerateSignedPostPolicyV4.generateSignedPostPolicyV4(PROJECT_ID, BUCKET, "my-object"); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertTrue( - snippetOutput.contains("
")); - - String[] output = snippetOutput.split("'"); - final HttpClient client = HttpClientBuilder.create().build(); - final HttpPost request = new HttpPost(output[1]); - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - - Map policy = new HashMap<>(); - /** - * When splitting by "'", any element in the form has its value two array elements ahead of it, - * for example ["x-goog-algorithm", "value=", "GOOG4-RSA-SHA256"] We take advantage of this to - * make a map which has any policy element easily accessible. The map also has a lot of noise, - * but we just use the parts we need - */ - for (int i = 3; i < output.length - 3; i += 2) { - policy.put(output[i], output[i + 2]); - } - - builder.addTextBody("x-goog-date", policy.get("x-goog-date")); - builder.addTextBody("x-goog-meta-test", "data"); - builder.addTextBody("x-goog-algorithm", "GOOG4-RSA-SHA256"); - builder.addTextBody("x-goog-credential", policy.get("x-goog-credential")); - builder.addTextBody("key", "my-object"); - builder.addTextBody("x-goog-signature", policy.get("x-goog-signature")); - builder.addTextBody("policy", policy.get("policy")); - - File file = File.createTempFile("temp", "file"); - Files.write(file.toPath(), "hello world".getBytes()); - builder.addBinaryBody( - "file", new FileInputStream(file), ContentType.APPLICATION_OCTET_STREAM, file.getName()); - request.setEntity(builder.build()); - - client.execute(request); - - assertEquals("hello world", new String(storage.get(BUCKET, "my-object").getContent())); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/ITVerboseBucketCleanupTest.java b/samples/snippets/src/test/java/com/example/storage/ITVerboseBucketCleanupTest.java index 5f185ff1e8..deff724f1a 100644 --- a/samples/snippets/src/test/java/com/example/storage/ITVerboseBucketCleanupTest.java +++ b/samples/snippets/src/test/java/com/example/storage/ITVerboseBucketCleanupTest.java @@ -24,6 +24,10 @@ import org.junit.Test; public final class ITVerboseBucketCleanupTest { + static { + org.slf4j.bridge.SLF4JBridgeHandler.removeHandlersForRootLogger(); + org.slf4j.bridge.SLF4JBridgeHandler.install(); + } private static final Logger LOGGER = Logger.getLogger(ITVerboseBucketCleanupTest.class.getName()); @Test diff --git a/samples/snippets/src/test/java/com/example/storage/QuickstartSampleIT.java b/samples/snippets/src/test/java/com/example/storage/QuickstartSampleIT.java deleted file mode 100644 index 60d918e842..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/QuickstartSampleIT.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2015 Google Inc. - * - * Licensed 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. - */ - -package com.example.storage; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.storage.control.v2.StorageLayoutName; -import java.util.UUID; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** Tests for quickstart sample. */ -@RunWith(JUnit4.class) -@SuppressWarnings("checkstyle:abbreviationaswordinname") -public class QuickstartSampleIT { - - @Rule public final StdOutCaptureRule stdOutCaptureRule = new StdOutCaptureRule(); - - private String bucketName; - - private static void deleteBucket(String bucketName) { - Storage storage = StorageOptions.getDefaultInstance().getService(); - storage.delete(bucketName); - } - - @Before - public void setUp() { - bucketName = "java-storage-grpc-" + UUID.randomUUID(); - } - - @After - public void tearDown() { - deleteBucket(bucketName); - } - - @Test - public void testQuickstart() throws Exception { - QuickstartSample.main(bucketName); - String got = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(got).contains(String.format("Bucket %s created.", bucketName)); - } - - @Test - public void testQuickstartGrpc() throws Exception { - QuickstartGrpcSample.main(bucketName); - String got = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(got).contains(String.format("Bucket %s created.", bucketName)); - } - - @Test - public void testQuickstartGrpcDp() throws Exception { - QuickstartGrpcDpSample.main(bucketName); - String got = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(got).contains(String.format("Bucket %s created.", bucketName)); - } - - @Test - public void testQuickstartStorageControl() throws Exception { - Storage storageClient = StorageOptions.getDefaultInstance().getService(); - storageClient.create(BucketInfo.of(bucketName)); - QuickstartStorageControlSample.main(bucketName); - String got = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(got) - .contains( - String.format( - "Performed getStorageLayout request for %s", - StorageLayoutName.format("_", bucketName))); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/TestBase.java b/samples/snippets/src/test/java/com/example/storage/TestBase.java deleted file mode 100644 index a13edb4ba1..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/TestBase.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import com.google.cloud.storage.Blob; -import com.google.cloud.storage.BlobInfo; -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; - -public abstract class TestBase { - - @Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule(); - - protected String bucketName; - protected Storage storage; - protected String blobName; - protected Bucket bucket; - protected Blob blob; - - @Before - public void setUp() { - blobName = "blob"; - bucketName = RemoteStorageHelper.generateBucketName(); - storage = StorageOptions.getDefaultInstance().getService(); - bucket = storage.create(BucketInfo.of(bucketName)); - blob = storage.create(BlobInfo.newBuilder(bucketName, blobName).build()); - } - - @After - public void tearDown() { - RemoteStorageHelper.forceDelete(storage, bucketName); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/TestUtils.java b/samples/snippets/src/test/java/com/example/storage/TestUtils.java deleted file mode 100644 index 6530c1519c..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/TestUtils.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2023 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import com.google.api.core.CurrentMillisClock; -import com.google.api.gax.retrying.BasicResultRetryAlgorithm; -import com.google.api.gax.retrying.RetrySettings; -import com.google.cloud.RetryHelper; -import com.google.cloud.RetryHelper.RetryHelperException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Logger; - -public final class TestUtils { - - private static final Logger log = Logger.getLogger(TestUtils.class.getName()); - private static final Object SENTINEL = new Object(); - - private TestUtils() {} - - public static void retryAssert(RetrySettings rs, RetryRunnable f) throws Throwable { - AtomicInteger counter = new AtomicInteger(1); - try { - RetryHelper.runWithRetries( - () -> { - try { - int c = counter.getAndIncrement(); - if (c > 1) { - log.warning(String.format("Retrying assertion for the %d time", c)); - } - f.run(); - return SENTINEL; - } catch (Throwable e) { - throw new TunnelThrowable(e); - } - }, - rs, - new BasicResultRetryAlgorithm() { - @Override - public boolean shouldRetry(Throwable previousThrowable, Object previousResponse) { - return previousResponse != SENTINEL && previousThrowable != null; - } - }, - CurrentMillisClock.getDefaultClock()); - } catch (RetryHelperException e) { - if (e.getCause() instanceof TunnelThrowable) { - TunnelThrowable cause = (TunnelThrowable) e.getCause(); - throw cause.getCause(); - } - throw e.getCause(); - } - } - - @FunctionalInterface - public interface RetryRunnable { - - void run() throws Throwable; - } - - private static final class TunnelThrowable extends Exception { - private TunnelThrowable(Throwable cause) { - super(cause); - } - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/TestUtilsTest.java b/samples/snippets/src/test/java/com/example/storage/TestUtilsTest.java deleted file mode 100644 index d4a76072b8..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/TestUtilsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2023 Google LLC - * - * Licensed 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. - */ - -package com.example.storage; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; - -import com.google.api.gax.retrying.RetrySettings; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; - -public class TestUtilsTest { - - private static final RetrySettings RETRY_SETTINGS = - RetrySettings.newBuilder().setMaxAttempts(3).build(); - - @Test - public void noException() throws Throwable { - TestUtils.retryAssert(RETRY_SETTINGS, () -> assertThat(true).isTrue()); - } - - @Test - public void assertionFailureOnce() throws Throwable { - System.out.println("TestUtilsTest.assertionFailureOnce"); - AtomicInteger c = new AtomicInteger(1); - TestUtils.retryAssert(RETRY_SETTINGS, () -> assertThat(c.getAndIncrement()).isGreaterThan(1)); - } - - @Test - public void assertionError_exhausted() throws Throwable { - AtomicInteger c = new AtomicInteger(1); - try { - TestUtils.retryAssert( - RETRY_SETTINGS, () -> assertThat(c.getAndIncrement()).isGreaterThan(10)); - throw new Throwable("expected AssertionError"); - } catch (AssertionError ignore) { - // expected - } - } - - @Test - public void runtimeException_exhausted() { - assertThrows( - RuntimeException.class, - () -> - TestUtils.retryAssert( - RETRY_SETTINGS, - () -> { - throw new RuntimeException("kaboom"); - })); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/AddBucketDefaultOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/AddBucketDefaultOwnerTest.java deleted file mode 100644 index 8dbb1786a2..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/AddBucketDefaultOwnerTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class AddBucketDefaultOwnerTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testAddBucketDefaultOwner() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - AddBucketDefaultOwner.addBucketDefaultOwner(bucketName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(bucket.getDefaultAcl(new User(IT_SERVICE_ACCOUNT_EMAIL))).isNotNull(); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/AddBucketOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/AddBucketOwnerTest.java deleted file mode 100644 index 77c722421a..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/AddBucketOwnerTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class AddBucketOwnerTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testAddBucketOwner() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - AddBucketOwner.addBucketOwner( - System.getenv("GOOGLE_CLOUD_PROJECT"), bucketName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(bucket.getAcl(new User(IT_SERVICE_ACCOUNT_EMAIL))).isNotNull(); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/AutoclassTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/AutoclassTest.java deleted file mode 100644 index 82297c69e0..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/AutoclassTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; - -import com.example.storage.TestBase; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.BucketInfo.Autoclass; -import com.google.cloud.storage.StorageClass; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import org.junit.Test; - -public class AutoclassTest extends TestBase { - - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - - @Test - public void testSetGetBucketAutoclass() throws Exception { - String autoclassBucket = RemoteStorageHelper.generateBucketName(); - storage.create( - BucketInfo.newBuilder(autoclassBucket) - .setAutoclass(Autoclass.newBuilder().setEnabled(true).build()) - .build()); - try { - SetBucketAutoclass.setBucketAutoclass(PROJECT_ID, autoclassBucket, StorageClass.NEARLINE); - Autoclass autoclass = storage.get(autoclassBucket).getAutoclass(); - assertThat(autoclass.getEnabled()).isTrue(); - - GetBucketAutoclass.getBucketAutoclass(PROJECT_ID, autoclassBucket); - assertThat(stdOut.getCapturedOutputAsUtf8String()) - .contains(autoclass.getToggleTime().toString()); - } finally { - RemoteStorageHelper.forceDelete(storage, autoclassBucket); - } - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketDualRegionTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketDualRegionTest.java deleted file mode 100644 index d4910c67c8..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketDualRegionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import org.junit.Test; - -public class CreateBucketDualRegionTest extends TestBase { - - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - - @Test - public void testCreateBucketDualRegion() { - assertNotNull("Unable to determine Project ID", PROJECT_ID); - String newBucket = RemoteStorageHelper.generateBucketName(); - CreateBucketDualRegion.createBucketDualRegion( - PROJECT_ID, newBucket, "US", "US-EAST1", "US-WEST1"); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("US-WEST1"); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("US-EAST1"); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("Created bucket"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketPubSubNotificationTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketPubSubNotificationTest.java deleted file mode 100644 index 7bfd95242e..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/CreateBucketPubSubNotificationTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.pubsub.v1.TopicAdminClient; -import com.google.cloud.storage.Notification; -import com.google.cloud.storage.NotificationInfo.EventType; -import com.google.common.collect.ImmutableMap; -import com.google.iam.v1.Binding; -import com.google.iam.v1.GetIamPolicyRequest; -import com.google.iam.v1.SetIamPolicyRequest; -import java.io.IOException; -import java.util.Map; -import java.util.UUID; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -public class CreateBucketPubSubNotificationTest extends TestBase { - - private static final Notification.PayloadFormat PAYLOAD_FORMAT = - Notification.PayloadFormat.JSON_API_V1.JSON_API_V1; - private static final Map CUSTOM_ATTRIBUTES = ImmutableMap.of("label1", "value1"); - private static final String PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String PROJECT_NUMBER = System.getenv("GOOGLE_CLOUD_PROJECT_NUMBER"); - - private static final String ID = UUID.randomUUID().toString().substring(0, 8); - private static final String TOPIC = - String.format("projects/%s/topics/new-topic-create-%s", PROJECT, ID); - private static final String OBJECT_NAME_PREFIX = "index.html"; - private static final EventType[] EVENT_TYPES = { - EventType.OBJECT_FINALIZE, EventType.OBJECT_METADATA_UPDATE - }; - private static TopicAdminClient topicAdminClient; - - @BeforeClass - public static void configureTopicAdminClient() throws IOException { - if (PROJECT != null) { - topicAdminClient = TopicAdminClient.create(); - topicAdminClient.createTopic(TOPIC); - GetIamPolicyRequest getIamPolicyRequest = - GetIamPolicyRequest.newBuilder().setResource(TOPIC).build(); - com.google.iam.v1.Policy policy = topicAdminClient.getIamPolicy(getIamPolicyRequest); - // For available bindings identities, see - // https://cloud.google.com/iam/docs/overview#concepts_related_identity - String member = - PROJECT_NUMBER != null - ? "serviceAccount:service-" - + PROJECT_NUMBER - + "@gs-project-accounts.iam.gserviceaccount.com" - : "allAuthenticatedUsers"; - Binding binding = Binding.newBuilder().setRole("roles/owner").addMembers(member).build(); - SetIamPolicyRequest setIamPolicyRequest = - SetIamPolicyRequest.newBuilder() - .setResource(TOPIC) - .setPolicy(policy.toBuilder().addBindings(binding).build()) - .build(); - topicAdminClient.setIamPolicy(setIamPolicyRequest); - } - } - - @AfterClass - public static void deleteTopicAndClient() { - /* Delete the Pub/Sub topic */ - if (topicAdminClient != null) { - topicAdminClient.deleteTopic(TOPIC); - topicAdminClient.close(); - } - } - - @Test - public void testCreateBucketPubSubNotification() { - // Check that we can access project value and that topic admin client came up successfully - assertNotNull("Unable to determine project", PROJECT); - assertNotNull("Topic Admin Client did not start up", topicAdminClient); - - com.example.storage.bucket.CreateBucketPubSubNotification.createBucketPubSubNotification( - bucketName, TOPIC, CUSTOM_ATTRIBUTES, EVENT_TYPES, OBJECT_NAME_PREFIX, PAYLOAD_FORMAT); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(TOPIC); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/DeleteBucketPubSubNotificationTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/DeleteBucketPubSubNotificationTest.java deleted file mode 100644 index aab1073b38..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/DeleteBucketPubSubNotificationTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.pubsub.v1.TopicAdminClient; -import com.google.cloud.storage.Notification; -import com.google.cloud.storage.NotificationInfo; -import com.google.cloud.testing.junit4.MultipleAttemptsRule; -import com.google.common.collect.ImmutableMap; -import com.google.iam.v1.Binding; -import com.google.iam.v1.GetIamPolicyRequest; -import com.google.iam.v1.SetIamPolicyRequest; -import java.io.IOException; -import java.util.Map; -import java.util.UUID; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; - -public class DeleteBucketPubSubNotificationTest extends TestBase { - - @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(5); - - private static final Notification.PayloadFormat PAYLOAD_FORMAT = - Notification.PayloadFormat.JSON_API_V1.JSON_API_V1; - private static final Map CUSTOM_ATTRIBUTES = ImmutableMap.of("label1", "value1"); - private static final String PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String PROJECT_NUMBER = System.getenv("GOOGLE_CLOUD_PROJECT_NUMBER"); - - private static final String ID = UUID.randomUUID().toString().substring(0, 8); - private static final String TOPIC = - String.format("projects/%s/topics/new-topic-delete-%s", PROJECT, ID); - private static TopicAdminClient topicAdminClient; - private static final NotificationInfo notificationInfo = - NotificationInfo.newBuilder(TOPIC) - .setCustomAttributes(CUSTOM_ATTRIBUTES) - .setPayloadFormat(PAYLOAD_FORMAT) - .build(); - - @BeforeClass - public static void configureTopicAdminClient() throws IOException { - if (PROJECT != null) { - topicAdminClient = TopicAdminClient.create(); - topicAdminClient.createTopic(TOPIC); - GetIamPolicyRequest getIamPolicyRequest = - GetIamPolicyRequest.newBuilder().setResource(TOPIC).build(); - com.google.iam.v1.Policy policy = topicAdminClient.getIamPolicy(getIamPolicyRequest); - // For available bindings identities, see - // https://cloud.google.com/iam/docs/overview#concepts_related_identity - String member = - PROJECT_NUMBER != null - ? "serviceAccount:service-" - + PROJECT_NUMBER - + "@gs-project-accounts.iam.gserviceaccount.com" - : "allAuthenticatedUsers"; - Binding binding = Binding.newBuilder().setRole("roles/owner").addMembers(member).build(); - SetIamPolicyRequest setIamPolicyRequest = - SetIamPolicyRequest.newBuilder() - .setResource(TOPIC) - .setPolicy(policy.toBuilder().addBindings(binding).build()) - .build(); - topicAdminClient.setIamPolicy(setIamPolicyRequest); - } - } - - @AfterClass - public static void deleteTopicAndClient() { - /* Delete the Pub/Sub topic */ - if (topicAdminClient != null) { - topicAdminClient.deleteTopic(TOPIC); - topicAdminClient.close(); - } - } - - @Test - public void testDeleteBucketPubSubNotification() { - // Check that we can access project value and that topic admin client came up successfully - assertNotNull("Unable to determine project", PROJECT); - assertNotNull("Topic Admin Client did not start up", topicAdminClient); - - Notification notification = storage.createNotification(bucketName, notificationInfo); - com.example.storage.bucket.DeleteBucketPubSubNotification.deleteBucketPubSubNotification( - bucketName, notification.getNotificationId()); - assertThat(stdOut.getCapturedOutputAsUtf8String()) - .contains("Successfully deleted notification"); - } - - @Test - public void testNotificationNotFound() { - // Check that we can access project value and that topic admin client came up successfully - assertNotNull("Unable to determine project", PROJECT); - assertNotNull("Topic Admin Client did not start up", topicAdminClient); - Notification notification = storage.createNotification(bucketName, notificationInfo); - // Do a delete first. - storage.deleteNotification(bucketName, notification.getNotificationId()); - // Now try to delete again. - com.example.storage.bucket.DeleteBucketPubSubNotification.deleteBucketPubSubNotification( - bucketName, notification.getNotificationId()); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("Failed to find notification"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/ListPubSubNotificationsTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/ListPubSubNotificationsTest.java deleted file mode 100644 index 88a4613e7a..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/ListPubSubNotificationsTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.pubsub.v1.TopicAdminClient; -import com.google.cloud.storage.Notification; -import com.google.cloud.storage.NotificationInfo; -import com.google.cloud.testing.junit4.MultipleAttemptsRule; -import com.google.common.collect.ImmutableMap; -import com.google.iam.v1.Binding; -import com.google.iam.v1.GetIamPolicyRequest; -import com.google.iam.v1.SetIamPolicyRequest; -import java.io.IOException; -import java.util.Map; -import java.util.UUID; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; - -public class ListPubSubNotificationsTest extends TestBase { - - @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(5); - - private static final Notification.PayloadFormat PAYLOAD_FORMAT = - Notification.PayloadFormat.JSON_API_V1.JSON_API_V1; - private static final Map CUSTOM_ATTRIBUTES = ImmutableMap.of("label1", "value1"); - private static final String PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String PROJECT_NUMBER = System.getenv("GOOGLE_CLOUD_PROJECT_NUMBER"); - - private static final String ID = UUID.randomUUID().toString().substring(0, 8); - private static final String TOPIC = - String.format("projects/%s/topics/new-topic-list-%s", PROJECT, ID); - private static TopicAdminClient topicAdminClient; - - @BeforeClass - public static void configureTopicAdminClient() throws IOException { - if (PROJECT != null) { - topicAdminClient = TopicAdminClient.create(); - topicAdminClient.createTopic(TOPIC); - GetIamPolicyRequest getIamPolicyRequest = - GetIamPolicyRequest.newBuilder().setResource(TOPIC).build(); - com.google.iam.v1.Policy policy = topicAdminClient.getIamPolicy(getIamPolicyRequest); - // For available bindings identities, see - // https://cloud.google.com/iam/docs/overview#concepts_related_identity - String member = - PROJECT_NUMBER != null - ? "serviceAccount:service-" - + PROJECT_NUMBER - + "@gs-project-accounts.iam.gserviceaccount.com" - : "allAuthenticatedUsers"; - Binding binding = Binding.newBuilder().setRole("roles/owner").addMembers(member).build(); - SetIamPolicyRequest setIamPolicyRequest = - SetIamPolicyRequest.newBuilder() - .setResource(TOPIC) - .setPolicy(policy.toBuilder().addBindings(binding).build()) - .build(); - topicAdminClient.setIamPolicy(setIamPolicyRequest); - } - } - - @AfterClass - public static void deleteTopicAndClient() { - /* Delete the Pub/Sub topic */ - if (topicAdminClient != null) { - topicAdminClient.deleteTopic(TOPIC); - topicAdminClient.close(); - } - } - - @Test - public void testListBucketPubSubNotification() { - // Check that we can access project value and that topic admin client came up successfully - assertNotNull("Unable to determine project", PROJECT); - assertNotNull("Topic Admin Client did not start up", topicAdminClient); - - NotificationInfo notificationInfo = - NotificationInfo.newBuilder(TOPIC) - .setCustomAttributes(CUSTOM_ATTRIBUTES) - .setPayloadFormat(PAYLOAD_FORMAT) - .build(); - storage.createNotification(bucketName, notificationInfo); - ListPubSubNotifications.listPubSubNotifications(bucketName); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(TOPIC); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/PrintBucketAclFilterByUserTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/PrintBucketAclFilterByUserTest.java deleted file mode 100644 index 95443a237c..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/PrintBucketAclFilterByUserTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Acl.Entity; -import com.google.cloud.storage.Acl.Role; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class PrintBucketAclFilterByUserTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testPrintBucketAclByUser() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - Entity testUser = new User(IT_SERVICE_ACCOUNT_EMAIL); - storage.createAcl(bucketName, Acl.of(testUser, Role.READER)); - PrintBucketAclFilterByUser.printBucketAclFilterByUser(bucketName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(Role.READER.name()); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/PrintBucketAclTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/PrintBucketAclTest.java deleted file mode 100644 index 399cbe65bf..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/PrintBucketAclTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Acl.Entity; -import com.google.cloud.storage.Acl.Role; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class PrintBucketAclTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testPrintBucketAcls() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - Entity testUser = new User(IT_SERVICE_ACCOUNT_EMAIL); - storage.createAcl(bucketName, Acl.of(testUser, Role.READER)); - PrintBucketAcl.printBucketAcl(System.getenv("GOOGLE_CLOUD_PROJECT"), bucketName); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("READER: USER"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/PrintPubSubNotificationTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/PrintPubSubNotificationTest.java deleted file mode 100644 index d342795a85..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/PrintPubSubNotificationTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.pubsub.v1.TopicAdminClient; -import com.google.cloud.storage.Notification; -import com.google.cloud.storage.NotificationInfo; -import com.google.common.collect.ImmutableMap; -import com.google.iam.v1.Binding; -import com.google.iam.v1.GetIamPolicyRequest; -import com.google.iam.v1.SetIamPolicyRequest; -import java.io.IOException; -import java.util.Map; -import java.util.UUID; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -public class PrintPubSubNotificationTest extends TestBase { - - private static final Notification.PayloadFormat PAYLOAD_FORMAT = - Notification.PayloadFormat.JSON_API_V1.JSON_API_V1; - private static final Map CUSTOM_ATTRIBUTES = ImmutableMap.of("label1", "value1"); - private static final String PROJECT = System.getenv("GOOGLE_CLOUD_PROJECT"); - private static final String PROJECT_NUMBER = System.getenv("GOOGLE_CLOUD_PROJECT_NUMBER"); - - private static final String ID = UUID.randomUUID().toString().substring(0, 8); - private static final String TOPIC = - String.format("projects/%s/topics/new-topic-print-%s", PROJECT, ID); - private static TopicAdminClient topicAdminClient; - - @BeforeClass - public static void configureTopicAdminClient() throws IOException { - if (PROJECT != null) { - topicAdminClient = TopicAdminClient.create(); - topicAdminClient.createTopic(TOPIC); - GetIamPolicyRequest getIamPolicyRequest = - GetIamPolicyRequest.newBuilder().setResource(TOPIC).build(); - com.google.iam.v1.Policy policy = topicAdminClient.getIamPolicy(getIamPolicyRequest); - // For available bindings identities, see - // https://cloud.google.com/iam/docs/overview#concepts_related_identity - String member = - PROJECT_NUMBER != null - ? "serviceAccount:service-" - + PROJECT_NUMBER - + "@gs-project-accounts.iam.gserviceaccount.com" - : "allAuthenticatedUsers"; - Binding binding = Binding.newBuilder().setRole("roles/owner").addMembers(member).build(); - SetIamPolicyRequest setIamPolicyRequest = - SetIamPolicyRequest.newBuilder() - .setResource(TOPIC) - .setPolicy(policy.toBuilder().addBindings(binding).build()) - .build(); - topicAdminClient.setIamPolicy(setIamPolicyRequest); - } - } - - @AfterClass - public static void deleteTopicAndClient() { - /* Delete the Pub/Sub topic */ - if (topicAdminClient != null) { - topicAdminClient.deleteTopic(TOPIC); - topicAdminClient.close(); - } - } - - @Test - public void testPrintBucketPubSubNotification() { - // Check that we can access project value and that topic admin client came up successfully - assertNotNull("Unable to determine project", PROJECT); - assertNotNull("Topic Admin Client did not start up", topicAdminClient); - - NotificationInfo notificationInfo = - NotificationInfo.newBuilder(TOPIC) - .setCustomAttributes(CUSTOM_ATTRIBUTES) - .setPayloadFormat(PAYLOAD_FORMAT) - .build(); - Notification notification = storage.createNotification(bucketName, notificationInfo); - PrintPubSubNotification.printPubSubNotification(bucketName, notification.getNotificationId()); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(TOPIC); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/RemoveBucketDefaultOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/RemoveBucketDefaultOwnerTest.java deleted file mode 100644 index 8af2f1ef9c..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/RemoveBucketDefaultOwnerTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Acl.Role; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class RemoveBucketDefaultOwnerTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testRemoveBucketDefaultOwner() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - // Add User as Default Owner - Acl newDefaultOwner = Acl.of(new User(IT_SERVICE_ACCOUNT_EMAIL), Role.OWNER); - bucket.createDefaultAcl(newDefaultOwner); - - // Remove User as Default owner - RemoveBucketDefaultOwner.removeBucketDefaultOwner(bucketName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("Removed user"); - assertThat(bucket.getDefaultAcl(new User(IT_SERVICE_ACCOUNT_EMAIL))).isNull(); - } - - @Test - public void testUserNotFound() { - // Remove User without Default Owner Permissions - RemoveBucketDefaultOwner.removeBucketDefaultOwner(bucketName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("was not found"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/bucket/RemoveBucketOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/bucket/RemoveBucketOwnerTest.java deleted file mode 100644 index add09380fb..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/bucket/RemoveBucketOwnerTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.bucket; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Acl.Role; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class RemoveBucketOwnerTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testRemoveBucketOwner() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - // Add User as Owner - Acl newOwner = Acl.of(new User(IT_SERVICE_ACCOUNT_EMAIL), Role.OWNER); - bucket.createAcl(newOwner); - - // Remove User as owner - RemoveBucketOwner.removeBucketOwner( - System.getenv("GOOGLE_CLOUD_PROJECT"), bucketName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("Removed user"); - assertThat(bucket.getAcl(new User(IT_SERVICE_ACCOUNT_EMAIL))).isNull(); - } - - @Test - public void testUserNotFound() { - // Remove User without Owner Permissions - RemoveBucketOwner.removeBucketOwner( - System.getenv("GOOGLE_CLOUD_PROJECT"), bucketName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("was not found"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/control/v2/FoldersTest.java b/samples/snippets/src/test/java/com/example/storage/control/v2/FoldersTest.java deleted file mode 100644 index 7b4f8f214a..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/control/v2/FoldersTest.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.control.v2; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertThrows; - -import com.google.api.gax.rpc.NotFoundException; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.BucketInfo.HierarchicalNamespace; -import com.google.cloud.storage.BucketInfo.IamConfiguration; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.storage.control.v2.BucketName; -import com.google.storage.control.v2.Folder; -import com.google.storage.control.v2.FolderName; -import com.google.storage.control.v2.StorageControlClient; -import java.io.IOException; -import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeoutException; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public final class FoldersTest { - - @Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule(); - - private Storage storage; - private BucketInfo bucket; - private StorageControlClient storageControl; - - @Before - public void setUp() throws Exception { - storage = StorageOptions.http().build().getService(); - String bucketName = RemoteStorageHelper.generateBucketName(); - BucketInfo bucketInfo = - BucketInfo.newBuilder(bucketName) - .setIamConfiguration( - // Hierarchical namespace buckets must use uniform bucket-level access. - IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build()) - .setHierarchicalNamespace(HierarchicalNamespace.newBuilder().setEnabled(true).build()) - .build(); - - bucket = storage.create(bucketInfo).asBucketInfo(); - storageControl = StorageControlClient.create(); - } - - @After - public void tearDown() throws Exception { - // Use try-with-resource to handle the dance closing multiple things - //noinspection EmptyTryBlock - try (AutoCloseable ignore1 = storage; - AutoCloseable ignore2 = storageControl) { - // ignore - } - } - - @Test - public void createFolder() throws IOException { - String folderName = UUID.randomUUID().toString(); - CreateFolder.createFolder(bucket.getName(), folderName); - try { - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(folderName); - } finally { - storageControl.deleteFolder(FolderName.of("_", bucket.getName(), folderName)); - } - } - - @Test - public void getFolder() throws IOException { - FolderName folderName = FolderName.of("_", bucket.getName(), UUID.randomUUID().toString()); - Folder gen1 = - storageControl.createFolder( - BucketName.of("_", bucket.getName()), - Folder.getDefaultInstance(), - folderName.getFolder()); - - GetFolder.getFolder(bucket.getName(), folderName.getFolder()); - try { - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(folderName.toString()); - } finally { - storageControl.deleteFolder(folderName); - } - } - - @Test - public void renameFolder() - throws IOException, ExecutionException, InterruptedException, TimeoutException { - FolderName srcFolderName = FolderName.of("_", bucket.getName(), UUID.randomUUID().toString()); - Folder gen1 = - storageControl.createFolder( - BucketName.of("_", bucket.getName()), - Folder.getDefaultInstance(), - srcFolderName.getFolder()); - - FolderName dstFolderName = FolderName.of("_", bucket.getName(), UUID.randomUUID().toString()); - - RenameFolder.renameFolder( - bucket.getName(), srcFolderName.getFolder(), dstFolderName.getFolder()); - try { - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(srcFolderName.toString()); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(dstFolderName.toString()); - assertThrows(NotFoundException.class, () -> storageControl.getFolder(srcFolderName)); - } finally { - storageControl.deleteFolder(dstFolderName); - } - } - - @Test - public void deleteFolder() throws IOException { - FolderName folderName = FolderName.of("_", bucket.getName(), UUID.randomUUID().toString()); - Folder gen1 = - storageControl.createFolder( - BucketName.of("_", bucket.getName()), - Folder.getDefaultInstance(), - folderName.getFolder()); - - DeleteFolder.deleteFolder(bucket.getName(), folderName.getFolder()); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(folderName.toString()); - assertThrows(NotFoundException.class, () -> storageControl.getFolder(folderName)); - } - - @Test - public void listFolder() throws IOException { - FolderName folderName = FolderName.of("_", bucket.getName(), UUID.randomUUID().toString()); - Folder gen1 = - storageControl.createFolder( - BucketName.of("_", bucket.getName()), - Folder.getDefaultInstance(), - folderName.getFolder()); - - ListFolders.listFolders(bucket.getName()); - try { - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(folderName.toString()); - } finally { - storageControl.deleteFolder(folderName); - } - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/control/v2/HNSTest.java b/samples/snippets/src/test/java/com/example/storage/control/v2/HNSTest.java deleted file mode 100644 index 5d2ec83c1a..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/control/v2/HNSTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.control.v2; - -import static com.google.common.truth.Truth.assertThat; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import org.junit.Test; - -public final class HNSTest extends TestBase { - - @Test - public void createHierarchicalNamespaceBucket() throws Exception { - String newBucketName = RemoteStorageHelper.generateBucketName(); - String projectId = storage.getOptions().getProjectId(); - CreateHierarchicalNamespaceBucket.createHierarchicalNamespaceBucket(projectId, newBucketName); - try { - Bucket remoteBucket = storage.get(newBucketName); - assertThat(remoteBucket).isNotNull(); - assertThat(remoteBucket.getHierarchicalNamespace().getEnabled()).isTrue(); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(newBucketName); - } finally { - storage.delete(newBucketName); - } - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/managedfolders/CreateManagedFolderTest.java b/samples/snippets/src/test/java/com/example/storage/managedfolders/CreateManagedFolderTest.java deleted file mode 100644 index 7bb8b74df1..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/managedfolders/CreateManagedFolderTest.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.managedfolders; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.BucketInfo.IamConfiguration; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.storage.control.v2.DeleteManagedFolderRequest; -import com.google.storage.control.v2.ManagedFolderName; -import com.google.storage.control.v2.StorageControlClient; -import java.io.IOException; -import java.util.UUID; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public class CreateManagedFolderTest { - - @Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule(); - - protected String bucketName; - protected Storage storage; - protected Bucket bucket; - protected String managedFolderId; - protected StorageControlClient storageControl; - - @Before - public void setUp() throws IOException { - bucketName = RemoteStorageHelper.generateBucketName(); - storageControl = StorageControlClient.create(); - storage = StorageOptions.getDefaultInstance().getService(); - managedFolderId = "new-managed-folder-" + UUID.randomUUID(); - BucketInfo bucketInfo = - BucketInfo.newBuilder(bucketName) - .setIamConfiguration( - IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build()) - .build(); - bucket = storage.create(bucketInfo); - } - - @After - public void tearDown() { - storageControl.deleteManagedFolder( - DeleteManagedFolderRequest.newBuilder() - .setName(ManagedFolderName.format("_", bucketName, managedFolderId)) - .build()); - storage.delete(bucketName); - storageControl.shutdown(); - } - - @Test - public void testCreateManagedFolder() throws Exception { - CreateManagedFolder.managedFolderCreate(bucketName, managedFolderId); - String got = stdOut.getCapturedOutputAsUtf8String(); - assertThat(got).contains(String.format(managedFolderId)); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/managedfolders/DeleteManagedFolderTest.java b/samples/snippets/src/test/java/com/example/storage/managedfolders/DeleteManagedFolderTest.java deleted file mode 100644 index 7225d95fa9..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/managedfolders/DeleteManagedFolderTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.managedfolders; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.BucketInfo.IamConfiguration; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.storage.control.v2.BucketName; -import com.google.storage.control.v2.CreateManagedFolderRequest; -import com.google.storage.control.v2.ManagedFolder; -import com.google.storage.control.v2.StorageControlClient; -import java.io.IOException; -import java.util.UUID; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public class DeleteManagedFolderTest { - - @Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule(); - - protected String bucketName; - protected Storage storage; - protected Bucket bucket; - protected String managedFolderId; - protected StorageControlClient storageControl; - - @Before - public void setUp() throws IOException { - bucketName = RemoteStorageHelper.generateBucketName(); - storageControl = StorageControlClient.create(); - storage = StorageOptions.getDefaultInstance().getService(); - managedFolderId = "new-managed-folder-" + UUID.randomUUID(); - BucketInfo bucketInfo = - BucketInfo.newBuilder(bucketName) - .setIamConfiguration( - IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build()) - .build(); - bucket = storage.create(bucketInfo); - storageControl.createManagedFolder( - CreateManagedFolderRequest.newBuilder() - // Set project to "_" to signify global bucket - .setParent(BucketName.format("_", bucketName)) - .setManagedFolder(ManagedFolder.newBuilder().build()) - .setManagedFolderId(managedFolderId) - .build()); - } - - @After - public void tearDown() { - storage.delete(bucketName); - storageControl.shutdown(); - } - - @Test - public void testDeleteManagedFolder() throws Exception { - DeleteManagedFolder.managedFolderDelete(bucketName, managedFolderId); - String got = stdOut.getCapturedOutputAsUtf8String(); - assertThat(got).contains(String.format(managedFolderId)); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/managedfolders/GetManagedFolderTest.java b/samples/snippets/src/test/java/com/example/storage/managedfolders/GetManagedFolderTest.java deleted file mode 100644 index 3b5128cf5d..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/managedfolders/GetManagedFolderTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.managedfolders; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.BucketInfo.IamConfiguration; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.storage.control.v2.BucketName; -import com.google.storage.control.v2.CreateManagedFolderRequest; -import com.google.storage.control.v2.DeleteManagedFolderRequest; -import com.google.storage.control.v2.ManagedFolder; -import com.google.storage.control.v2.ManagedFolderName; -import com.google.storage.control.v2.StorageControlClient; -import java.io.IOException; -import java.util.UUID; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public class GetManagedFolderTest { - - @Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule(); - - protected String bucketName; - protected Storage storage; - protected Bucket bucket; - protected String managedFolderId; - protected StorageControlClient storageControl; - - @Before - public void setUp() throws IOException { - bucketName = RemoteStorageHelper.generateBucketName(); - storageControl = StorageControlClient.create(); - storage = StorageOptions.getDefaultInstance().getService(); - managedFolderId = "new-managed-folder-" + UUID.randomUUID(); - BucketInfo bucketInfo = - BucketInfo.newBuilder(bucketName) - .setIamConfiguration( - IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build()) - .build(); - bucket = storage.create(bucketInfo); - storageControl.createManagedFolder( - CreateManagedFolderRequest.newBuilder() - // Set project to "_" to signify global bucket - .setParent(BucketName.format("_", bucketName)) - .setManagedFolder(ManagedFolder.newBuilder().build()) - .setManagedFolderId(managedFolderId) - .build()); - } - - @After - public void tearDown() { - storageControl.deleteManagedFolder( - DeleteManagedFolderRequest.newBuilder() - .setName(ManagedFolderName.format("_", bucketName, managedFolderId)) - .build()); - storage.delete(bucketName); - storageControl.shutdown(); - } - - @Test - public void testGetManagedFolder() throws Exception { - GetManagedFolder.managedFolderGet(bucketName, managedFolderId); - String got = stdOut.getCapturedOutputAsUtf8String(); - assertThat(got).contains(String.format(managedFolderId)); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/managedfolders/ListManagedFolderTest.java b/samples/snippets/src/test/java/com/example/storage/managedfolders/ListManagedFolderTest.java deleted file mode 100644 index 55bf404b86..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/managedfolders/ListManagedFolderTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.managedfolders; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.cloud.storage.Bucket; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.BucketInfo.IamConfiguration; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.StorageOptions; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.storage.control.v2.BucketName; -import com.google.storage.control.v2.CreateManagedFolderRequest; -import com.google.storage.control.v2.DeleteManagedFolderRequest; -import com.google.storage.control.v2.ManagedFolder; -import com.google.storage.control.v2.ManagedFolderName; -import com.google.storage.control.v2.StorageControlClient; -import java.io.IOException; -import java.util.UUID; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; - -public class ListManagedFolderTest { - - @Rule public StdOutCaptureRule stdOut = new StdOutCaptureRule(); - - protected String bucketName; - protected Storage storage; - protected Bucket bucket; - protected String managedFolderId; - protected StorageControlClient storageControl; - - @Before - public void setUp() throws IOException { - bucketName = RemoteStorageHelper.generateBucketName(); - storageControl = StorageControlClient.create(); - storage = StorageOptions.getDefaultInstance().getService(); - managedFolderId = "new-managed-folder-" + UUID.randomUUID(); - BucketInfo bucketInfo = - BucketInfo.newBuilder(bucketName) - .setIamConfiguration( - IamConfiguration.newBuilder().setIsUniformBucketLevelAccessEnabled(true).build()) - .build(); - bucket = storage.create(bucketInfo); - storageControl.createManagedFolder( - CreateManagedFolderRequest.newBuilder() - // Set project to "_" to signify global bucket - .setParent(BucketName.format("_", bucketName)) - .setManagedFolder(ManagedFolder.newBuilder().build()) - .setManagedFolderId(managedFolderId) - .build()); - } - - @After - public void tearDown() { - storageControl.deleteManagedFolder( - DeleteManagedFolderRequest.newBuilder() - .setName(ManagedFolderName.format("_", bucketName, managedFolderId)) - .build()); - storage.delete(bucketName); - storageControl.shutdown(); - } - - @Test - public void testListManagedFolder() throws Exception { - ListManagedFolders.managedFolderList(bucketName); - String got = stdOut.getCapturedOutputAsUtf8String(); - assertThat(got).contains(String.format(managedFolderId)); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/object/AddFileOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/object/AddFileOwnerTest.java deleted file mode 100644 index 7d56878a76..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/object/AddFileOwnerTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.object; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class AddFileOwnerTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testAddFileOwner() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - // Add Ownership to the file. - AddFileOwner.addFileOwner( - System.getenv("GOOGLE_CLOUD_PROJECT"), bucketName, IT_SERVICE_ACCOUNT_EMAIL, blobName); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(blob.getAcl(new User(IT_SERVICE_ACCOUNT_EMAIL))).isNotNull(); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/object/DownloadBytesRangeTest.java b/samples/snippets/src/test/java/com/example/storage/object/DownloadBytesRangeTest.java deleted file mode 100644 index c20be6793d..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/object/DownloadBytesRangeTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.object; - -import static com.google.common.truth.Truth.assertThat; - -import com.example.storage.TestBase; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.Arrays; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -public class DownloadBytesRangeTest extends TestBase { - - @Rule public final TemporaryFolder tmp = new TemporaryFolder(); - - @Test - public void testDownloadByteRange() throws IOException { - byte[] bytes = { // 18 elements per row - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', - 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', - 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', - 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' - }; - - blob = storage.create(blob, bytes); - - File file = tmp.newFile(); - - int startByte = 14; - int endBytes = 37; - byte[] expectedBytes = Arrays.copyOfRange(bytes, startByte, endBytes); - - try { - String destFileName = file.getAbsolutePath(); - DownloadByteRange.downloadByteRange( - System.getenv("GOOGLE_CLOUD_PROJECT"), - bucketName, - blobName, - startByte, - endBytes, - destFileName); - - byte[] readBytes = Files.readAllBytes(Paths.get(destFileName)); - - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("downloaded to"); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("from byte 14 to byte 37"); - assertThat(readBytes).isEqualTo(expectedBytes); - } finally { - file.delete(); - } - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/object/PrintFileAclForUserTest.java b/samples/snippets/src/test/java/com/example/storage/object/PrintFileAclForUserTest.java deleted file mode 100644 index 20c728ed3c..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/object/PrintFileAclForUserTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.object; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Acl.Entity; -import com.google.cloud.storage.Acl.Role; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class PrintFileAclForUserTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testPrintBucketAclByUser() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - Entity testUser = new User(IT_SERVICE_ACCOUNT_EMAIL); - blob.createAcl(Acl.of(testUser, Role.READER)); - PrintFileAclForUser.printFileAclForUser(bucketName, blobName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(Role.READER.name()); - } - - @Test - public void testUserNotFound() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - // Delete Acl just in case to make sure the User ACL is not present - blob.deleteAcl(new User(IT_SERVICE_ACCOUNT_EMAIL)); - PrintFileAclForUser.printFileAclForUser(bucketName, blobName, IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("not found"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/object/PrintFileAclTest.java b/samples/snippets/src/test/java/com/example/storage/object/PrintFileAclTest.java deleted file mode 100644 index 23bf7e7cae..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/object/PrintFileAclTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.object; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Acl.Entity; -import com.google.cloud.storage.Acl.Role; -import com.google.cloud.storage.Acl.User; -import org.junit.Test; - -public class PrintFileAclTest extends TestBase { - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testPrintFileAcls() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - Entity testUser = new User(IT_SERVICE_ACCOUNT_EMAIL); - blob.createAcl(Acl.of(testUser, Role.READER)); - PrintFileAcl.printFileAcl(bucketName, blobName); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("READER: USER"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/object/RemoveFileOwnerTest.java b/samples/snippets/src/test/java/com/example/storage/object/RemoveFileOwnerTest.java deleted file mode 100644 index 9d8936c789..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/object/RemoveFileOwnerTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2022 Google LLC - * - * Licensed 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. - */ - -package com.example.storage.object; - -import static com.google.common.truth.Truth.assertThat; -import static org.junit.Assert.assertNotNull; - -import com.example.storage.TestBase; -import com.google.cloud.storage.Acl; -import com.google.cloud.storage.Acl.Role; -import com.google.cloud.storage.Acl.User; -import com.google.cloud.testing.junit4.MultipleAttemptsRule; -import org.junit.Rule; -import org.junit.Test; - -public class RemoveFileOwnerTest extends TestBase { - - @Rule public MultipleAttemptsRule multipleAttemptsRule = new MultipleAttemptsRule(5); - - public static final String IT_SERVICE_ACCOUNT_EMAIL = System.getenv("IT_SERVICE_ACCOUNT_EMAIL"); - - @Test - public void testRemoveFileOwner() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - // Add User as Owner - Acl newFileOwner = Acl.of(new User(IT_SERVICE_ACCOUNT_EMAIL), Role.OWNER); - blob.createAcl(newFileOwner); - - // Remove User as owner - RemoveFileOwner.removeFileOwner( - System.getenv("GOOGLE_CLOUD_PROJECT"), bucketName, IT_SERVICE_ACCOUNT_EMAIL, blobName); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("Removed user"); - assertThat(blob.getAcl(new User(IT_SERVICE_ACCOUNT_EMAIL))).isNull(); - } - - @Test - public void testUserNotFound() { - // Check for user email before the actual test. - assertNotNull("Unable to determine user email", IT_SERVICE_ACCOUNT_EMAIL); - - // Remove User without Owner Permissions - RemoveFileOwner.removeFileOwner( - System.getenv("GOOGLE_CLOUD_PROJECT"), bucketName, IT_SERVICE_ACCOUNT_EMAIL, blobName); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains(IT_SERVICE_ACCOUNT_EMAIL); - assertThat(stdOut.getCapturedOutputAsUtf8String()).contains("was not found"); - } -} diff --git a/samples/snippets/src/test/java/com/example/storage/transfermanager/ITTransferManagerSamples.java b/samples/snippets/src/test/java/com/example/storage/transfermanager/ITTransferManagerSamples.java deleted file mode 100644 index d75b0a162a..0000000000 --- a/samples/snippets/src/test/java/com/example/storage/transfermanager/ITTransferManagerSamples.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2024 Google LLC - * - * Licensed 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. - * - */ - -package com.example.storage.transfermanager; - -import static com.google.common.truth.Truth.assertThat; - -import com.google.cloud.storage.BlobInfo; -import com.google.cloud.storage.BucketInfo; -import com.google.cloud.storage.Storage; -import com.google.cloud.storage.testing.RemoteStorageHelper; -import com.google.cloud.testing.junit4.StdOutCaptureRule; -import com.google.common.collect.ImmutableList; -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -public class ITTransferManagerSamples { - private static final String BUCKET = RemoteStorageHelper.generateBucketName(); - private static Storage storage; - private static List blobs; - private static List bigBlob; - private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); - @Rule public final StdOutCaptureRule stdOutCaptureRule = new StdOutCaptureRule(); - @Rule public final TemporaryFolder tmp = new TemporaryFolder(); - @Rule public final TemporaryFolder tmpDirectory = new TemporaryFolder(); - - @BeforeClass - public static void beforeClass() { - RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.getOptions().getService(); - storage.create(BucketInfo.of(BUCKET)); - blobs = - Arrays.asList( - BlobInfo.newBuilder(BUCKET, "blob1").build(), - BlobInfo.newBuilder(BUCKET, "blob2").build(), - BlobInfo.newBuilder(BUCKET, "blob3").build()); - for (BlobInfo blob : blobs) { - storage.create(blob); - } - } - - @Test - public void uploadFiles() throws Exception { - File tmpFile = File.createTempFile("file", ".txt"); - File tmpFile2 = File.createTempFile("file2", ".txt"); - File tmpFile3 = File.createTempFile("file3", ".txt"); - List files = ImmutableList.of(tmpFile.toPath(), tmpFile2.toPath(), tmpFile3.toPath()); - UploadMany.uploadManyFiles(BUCKET, files); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(snippetOutput.contains("file")).isTrue(); - assertThat(snippetOutput.contains("file2")).isTrue(); - assertThat(snippetOutput.contains("file3")).isTrue(); - } - - @Test - public void uploadDirectory() throws IOException { - File tmpFile = tmpDirectory.newFile("fileDirUpload.txt"); - File tmpFile2 = tmpDirectory.newFile("fileDirUpload2.txt"); - File tmpFile3 = tmpDirectory.newFile("fileDirUpload3.txt"); - UploadDirectory.uploadDirectoryContents(BUCKET, tmpDirectory.getRoot().toPath()); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(snippetOutput.contains("fileDirUpload.txt")).isTrue(); - assertThat(snippetOutput.contains("fileDirUpload2.txt")).isTrue(); - assertThat(snippetOutput.contains("fileDirUpload3.txt")).isTrue(); - } - - @Test - public void downloadBucket() { - String downloadFullBucketName = RemoteStorageHelper.generateBucketName(); - storage.create(BucketInfo.of(downloadFullBucketName)); - List bucketBlobs = - Arrays.asList( - BlobInfo.newBuilder(downloadFullBucketName, "bucketb1").build(), - BlobInfo.newBuilder(downloadFullBucketName, "bucketb2").build(), - BlobInfo.newBuilder(downloadFullBucketName, "bucketb3").build()); - for (BlobInfo blob : bucketBlobs) { - storage.create(blob); - } - DownloadBucket.downloadBucketContents( - PROJECT_ID, downloadFullBucketName, tmp.getRoot().toPath()); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(snippetOutput.contains("bucketb1")).isTrue(); - assertThat(snippetOutput.contains("bucketb2")).isTrue(); - assertThat(snippetOutput.contains("bucketb3")).isTrue(); - } - - @Test - public void downloadFiles() { - DownloadMany.downloadManyBlobs(BUCKET, blobs, tmp.getRoot().toPath()); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(snippetOutput.contains("blob1")).isTrue(); - assertThat(snippetOutput.contains("blob2")).isTrue(); - assertThat(snippetOutput.contains("blob3")).isTrue(); - } - - @Test - public void uploadAllowPCU() throws IOException { - File tmpFile = tmpDirectory.newFile("fileDirUpload.txt"); - AllowParallelCompositeUpload.parallelCompositeUploadAllowed( - BUCKET, Collections.singletonList(tmpFile.toPath())); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(snippetOutput.contains("fileDirUpload.txt")).isTrue(); - } - - @Test - public void downloadAllowDivideAndConquer() { - AllowDivideAndConquerDownload.divideAndConquerDownloadAllowed( - blobs, BUCKET, tmp.getRoot().toPath()); - String snippetOutput = stdOutCaptureRule.getCapturedOutputAsUtf8String(); - assertThat(snippetOutput.contains("blob1")).isTrue(); - assertThat(snippetOutput.contains("blob2")).isTrue(); - assertThat(snippetOutput.contains("blob3")).isTrue(); - } -}