Skip to content

Add tests to Cloud Tasks Samples #1459

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Jun 14, 2019
Merged
56 changes: 13 additions & 43 deletions tasks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,68 +19,38 @@ pushes it to your queue.

## Creating a queue

To create a queue using the Cloud SDK, use the following gcloud command:
To create a queue using the Cloud SDK, use the following `gcloud` command:

```
gcloud tasks queues create <QUEUE_NAME>
```

## Run the Sample Using the Command Line
The location of your queue is the same as your Google Cloud Project. It can be discovered by using the following `gcloud` command:

Set environment variables:

First, your project ID:

```
export GOOGLE_CLOUD_PROJECT=<YOUR_GOOGLE_CLOUD_PROJECT>
```

Then the queue ID, as specified at queue creation time. Queue IDs already
created can be listed with `gcloud tasks queues list`.

gcloud tasks queues describe <QUEUE_NAME>
```
export QUEUE_ID=<QUEUE_NAME>
```

And finally the location ID, which can be discovered with
`gcloud tasks queues describe $QUEUE_ID`, with the location embedded in
the "name" value (for instance, if the name is
the location embedded in the "name" value (for instance, if the name is
"projects/my-project/locations/us-central1/queues/my-queue", then the
location is "us-central1").

```
export LOCATION_ID=<YOUR_ZONE>
```

### Creating Tasks with HTTP Targets
## Creating Tasks with HTTP Targets

Set an environment variable for the endpoint to your task handler. This is an
example url:
```
export URL=https://example.com/taskshandler
```
Set an endpoint to your task handler by replacing the variable `url` with your
HTTP target in `CreateHttpTask.java`.

Running the sample will create a task and add it to your queue. As the queue
processes each task, it will send the task to the specific URL endpoint:
The sample will create a task and add it to your queue. As the queue processes
each task, it will send the task to the specific URL endpoint.

```
mvn exec:java@HttpTask"
```
## Using HTTP Targets with Authentication Tokens

### Using HTTP Targets with Authentication Tokens
Set an endpoint to your task handler by replacing the variable `url` with your
HTTP target in `CreateHttpTaskWithToken.java`.

Your Cloud Tasks [service account][sa],
(service-<project-number>@gcp-sa-cloudtasks.iam.gserviceaccount.com), must
have the role of: `Service Account Token Creator` to generate a tokens.

Create or use an existing [service account][sa] to replace `<SERVICE_ACCOUNT_EMAIL>`
in `CreateHttpTaskWithToken.java`. This service account will be used to
authenticate the OIDC token.

Running the sample with command:
```
mvn exec:java@WithToken"
```

Create or use an existing [service account][sa] to authenticate the OIDC token.

[sa]: https://cloud.google.com/iam/docs/service-accounts
49 changes: 26 additions & 23 deletions tasks/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ Copyright 2018 Google LLC
<groupId>com.google.cloud.samples</groupId>
<artifactId>shared-configuration</artifactId>
<version>1.0.11</version>
<relativePath></relativePath>
</parent>

<properties>
Expand All @@ -45,35 +44,39 @@ Copyright 2018 Google LLC
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-tasks</artifactId>
<version>1.4.0</version>
<version>1.3.0</version>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13-beta-2</version>
</dependency>
<dependency>
<groupId>com.google.truth</groupId>
<artifactId>truth</artifactId>
<version>0.44</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.4.0</version>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>HttpTask</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.example.task.CreateHttpTask</mainClass>
<cleanupDaemonThreads>false</cleanupDaemonThreads>
</configuration>
</execution>
<execution>
<id>WithToken</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.example.task.CreateHttpTaskWithToken</mainClass>
<cleanupDaemonThreads>false</cleanupDaemonThreads>
</configuration>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
Expand Down
26 changes: 13 additions & 13 deletions tasks/src/main/java/com/example/task/CreateHttpTask.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,24 +26,24 @@
import java.nio.charset.Charset;

public class CreateHttpTask {

public static void main(String[] args) throws Exception {
String projectId = System.getenv("PROJECT_ID");
String queueName = System.getenv("QUEUE_ID");
String location = System.getenv("LOCATION_ID");
String url = System.getenv("URL");
/**
* Create a task with a HTTP target using the Cloud Tasks client.
*
* @param projectId the Id of the project.
* @param queueId the name of your Queue.
* @param locationId the GCP region of your queue.
* @throws Exception on Cloud Tasks Client errors.
*/
public static void createTask(String projectId, String locationId, String queueId)
throws Exception {

// Instantiates a client.
try (CloudTasksClient client = CloudTasksClient.create()) {
// Variables provided by the system variables.
// projectId = "my-project-id";
// queueName = "my-queue";
// location = "us-central1";
// url = "https://example.com/taskhandler";
String payload = "hello";
String url = "https://example.com/taskhandler";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you call this out in the README? (CHANGEME)

String payload = "Hello, World!";

// Construct the fully qualified queue name.
String queuePath = QueueName.of(projectId, location, queueName).toString();
String queuePath = QueueName.of(projectId, locationId, queueId).toString();

// Construct the task body.
Task.Builder taskBuilder =
Expand Down
31 changes: 17 additions & 14 deletions tasks/src/main/java/com/example/task/CreateHttpTaskWithToken.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,29 +27,32 @@
import java.nio.charset.Charset;

public class CreateHttpTaskWithToken {

public static void main(String[] args) throws Exception {
String projectId = System.getenv("PROJECT_ID");
String queueName = System.getenv("QUEUE_ID");
String location = System.getenv("LOCATION_ID");
String url = System.getenv("URL");
/**
* Create a task with a HTTP target and authorization token using the Cloud Tasks client.
*
* @param projectId the Id of the project.
* @param queueId the name of your Queue.
* @param locationId the GCP region of your queue.
* @param serviceAccountEmail your Cloud IAM service account
* @throws Exception on Cloud Tasks Client errors.
*/
public static void createTask(
String projectId, String locationId, String queueId, String serviceAccountEmail)
throws Exception {

// Instantiates a client.
try (CloudTasksClient client = CloudTasksClient.create()) {
// Variables provided by the system variables.
// projectId = "my-project-id";
// queueName = "my-queue";
// location = "us-central1";
// url = "https://example.com/taskhandler";
String payload = "hello";
String url =
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we suggest changing this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since this is a snippet. I have updated with the sample without a main and highlighted the parameters.

"https://example.com/taskhandler"; // The full url path that the request will be sent to
String payload = "Hello, World!"; // The task HTTP request body

// Construct the fully qualified queue name.
String queuePath = QueueName.of(projectId, location, queueName).toString();
String queuePath = QueueName.of(projectId, locationId, queueId).toString();

// Add your service account email to construct the OIDC token.
// in order to add an authentication header to the request.
OidcToken.Builder oidcTokenBuilder =
OidcToken.newBuilder().setServiceAccountEmail("<SERVICE_ACCOUNT_EMAIL>");
OidcToken.newBuilder().setServiceAccountEmail(serviceAccountEmail);

// Construct the task body.
Task.Builder taskBuilder =
Expand Down
67 changes: 67 additions & 0 deletions tasks/src/test/java/com/example/task/CreateHttpTaskIT.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* 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.task;

import static com.google.common.truth.Truth.assertThat;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for creating Tasks with HTTP targets. */
@RunWith(JUnit4.class)
public class CreateHttpTaskIT {
private static final String PROJECT_ID = "java-docs-samples-testing";
private static final String LOCATION_ID = "us-east1";
private static final String QUEUE_ID = "default";
private static final String EMAIL =
"java-docs-samples-testing@java-docs-samples-testing.iam.gserviceaccount.com";
private ByteArrayOutputStream bout;
private PrintStream out;

@Before
public void setUp() {
bout = new ByteArrayOutputStream();
out = new PrintStream(bout);
System.setOut(out);
}

@After
public void tearDown() {
System.setOut(null);
}

@Test
public void testCreateHttpTask() throws Exception {
CreateHttpTask.createTask(PROJECT_ID, LOCATION_ID, QUEUE_ID);
String got = bout.toString();
assertThat(got).contains("Task created:");
}

@Test
public void testCreateHttpTaskWithToken() throws Exception {
CreateHttpTaskWithToken.createTask(PROJECT_ID, LOCATION_ID, QUEUE_ID, EMAIL);
String got = bout.toString();
assertThat(got).contains("Task created:");
}
}