gcloud

package module
v0.33.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2024 License: MIT Imports: 6 Imported by: 3

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type GCloudContainer

type GCloudContainer struct {
	testcontainers.Container
	Settings options
	URI      string
}

func RunBigQuery added in v0.32.0

func RunBigQuery(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

RunBigQuery creates an instance of the GCloud container type for BigQuery. The URI will always use http:// as the protocol.

func RunBigQueryContainer deprecated

func RunBigQueryContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

Deprecated: use RunBigQuery instead RunBigQueryContainer creates an instance of the GCloud container type for BigQuery.

Example
package main

import (
	"context"
	"errors"
	"fmt"
	"log"

	"cloud.google.com/go/bigquery"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
	"google.golang.org/api/option/internaloption"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"github.com/testcontainers/testcontainers-go/modules/gcloud"
)

func main() {
	// runBigQueryContainer {
	ctx := context.Background()

	bigQueryContainer, err := gcloud.RunBigQuery(
		ctx,
		"ghcr.io/goccy/bigquery-emulator:0.4.3",
		gcloud.WithProjectID("bigquery-project"),
	)
	if err != nil {
		log.Fatalf("failed to run container: %v", err)
	}

	// Clean up the container
	defer func() {
		if err := bigQueryContainer.Terminate(ctx); err != nil {
			log.Fatalf("failed to terminate container: %v", err)
		}
	}()
	// }

	// bigQueryClient {
	projectID := bigQueryContainer.Settings.ProjectID

	opts := []option.ClientOption{
		option.WithEndpoint(bigQueryContainer.URI),
		option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
		option.WithoutAuthentication(),
		internaloption.SkipDialSettingsValidation(),
	}

	client, err := bigquery.NewClient(ctx, projectID, opts...)
	if err != nil {
		log.Fatalf("failed to create bigquery client: %v", err) // nolint:gocritic
	}
	defer client.Close()
	// }

	createFnQuery := client.Query("CREATE FUNCTION testr(arr ARRAY<STRUCT<name STRING, val INT64>>) AS ((SELECT SUM(IF(elem.name = \"foo\",elem.val,null)) FROM UNNEST(arr) AS elem))")
	_, err = createFnQuery.Read(ctx)
	if err != nil {
		log.Fatalf("failed to create function: %v", err)
	}

	selectQuery := client.Query("SELECT testr([STRUCT<name STRING, val INT64>(\"foo\", 10), STRUCT<name STRING, val INT64>(\"bar\", 40), STRUCT<name STRING, val INT64>(\"foo\", 20)])")
	it, err := selectQuery.Read(ctx)
	if err != nil {
		log.Fatalf("failed to read query: %v", err)
	}

	var val []bigquery.Value
	for {
		err := it.Next(&val)
		if errors.Is(err, iterator.Done) {
			break
		}
		if err != nil {
			log.Fatalf("failed to iterate: %v", err)
		}
	}

	fmt.Println(val)

}
Output:

[30]

func RunBigTable added in v0.32.0

func RunBigTable(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

RunBigTable creates an instance of the GCloud container type for BigTable.

func RunBigTableContainer deprecated

func RunBigTableContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

Deprecated: use RunBigTable instead RunBigTableContainer creates an instance of the GCloud container type for BigTable.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/bigtable"
	"google.golang.org/api/option"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"github.com/testcontainers/testcontainers-go/modules/gcloud"
)

func main() {
	// runBigTableContainer {
	ctx := context.Background()

	bigTableContainer, err := gcloud.RunBigTable(
		ctx,
		"gcr.io/google.com/cloudsdktool/cloud-sdk:367.0.0-emulators",
		gcloud.WithProjectID("bigtable-project"),
	)
	if err != nil {
		log.Fatalf("failed to run container: %v", err)
	}

	// Clean up the container
	defer func() {
		if err := bigTableContainer.Terminate(ctx); err != nil {
			log.Fatalf("failed to terminate container: %v", err)
		}
	}()
	// }

	// bigTableAdminClient {
	projectId := bigTableContainer.Settings.ProjectID

	const (
		instanceId = "test-instance"
		tableName  = "test-table"
	)

	options := []option.ClientOption{
		option.WithEndpoint(bigTableContainer.URI),
		option.WithoutAuthentication(),
		option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
	}
	adminClient, err := bigtable.NewAdminClient(ctx, projectId, instanceId, options...)
	if err != nil {
		log.Fatalf("failed to create admin client: %v", err) // nolint:gocritic
	}
	defer adminClient.Close()
	// }

	err = adminClient.CreateTable(ctx, tableName)
	if err != nil {
		log.Fatalf("failed to create table: %v", err)
	}
	err = adminClient.CreateColumnFamily(ctx, tableName, "name")
	if err != nil {
		log.Fatalf("failed to create column family: %v", err)
	}

	// bigTableClient {
	client, err := bigtable.NewClient(ctx, projectId, instanceId, options...)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	defer client.Close()
	// }

	tbl := client.Open(tableName)

	mut := bigtable.NewMutation()
	mut.Set("name", "firstName", bigtable.Now(), []byte("Gopher"))
	err = tbl.Apply(ctx, "1", mut)
	if err != nil {
		log.Fatalf("failed to apply mutation: %v", err)
	}

	row, err := tbl.ReadRow(ctx, "1", bigtable.RowFilter(bigtable.FamilyFilter("name")))
	if err != nil {
		log.Fatalf("failed to read row: %v", err)
	}

	fmt.Println(string(row["name"][0].Value))

}
Output:

Gopher

func RunDatastore added in v0.32.0

func RunDatastore(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

RunDatastore creates an instance of the GCloud container type for Datastore.

func RunDatastoreContainer deprecated

func RunDatastoreContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

Deprecated: use RunDatastore instead RunDatastoreContainer creates an instance of the GCloud container type for Datastore.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/datastore"
	"google.golang.org/api/option"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"github.com/testcontainers/testcontainers-go/modules/gcloud"
)

func main() {
	// runDatastoreContainer {
	ctx := context.Background()

	datastoreContainer, err := gcloud.RunDatastore(
		ctx,
		"gcr.io/google.com/cloudsdktool/cloud-sdk:367.0.0-emulators",
		gcloud.WithProjectID("datastore-project"),
	)
	if err != nil {
		log.Fatalf("failed to run container: %v", err)
	}

	// Clean up the container
	defer func() {
		if err := datastoreContainer.Terminate(ctx); err != nil {
			log.Fatalf("failed to terminate container: %v", err)
		}
	}()
	// }

	// datastoreClient {
	projectID := datastoreContainer.Settings.ProjectID

	options := []option.ClientOption{
		option.WithEndpoint(datastoreContainer.URI),
		option.WithoutAuthentication(),
		option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
	}

	dsClient, err := datastore.NewClient(ctx, projectID, options...)
	if err != nil {
		log.Fatalf("failed to create client: %v", err) // nolint:gocritic
	}
	defer dsClient.Close()
	// }

	type Task struct {
		Description string
	}

	k := datastore.NameKey("Task", "sample", nil)
	data := Task{
		Description: "my description",
	}
	_, err = dsClient.Put(ctx, k, &data)
	if err != nil {
		log.Fatalf("failed to put data: %v", err)
	}

	saved := Task{}
	err = dsClient.Get(ctx, k, &saved)
	if err != nil {
		log.Fatalf("failed to get data: %v", err)
	}

	fmt.Println(saved.Description)

}
Output:

my description

func RunFirestore added in v0.32.0

func RunFirestore(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

RunFirestore creates an instance of the GCloud container type for Firestore.

func RunFirestoreContainer deprecated

func RunFirestoreContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

Deprecated: use RunFirestore instead RunFirestoreContainer creates an instance of the GCloud container type for Firestore.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/firestore"
	"google.golang.org/api/option"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"github.com/testcontainers/testcontainers-go/modules/gcloud"
)

type emulatorCreds struct{}

func (ec emulatorCreds) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{"authorization": "Bearer owner"}, nil
}

func (ec emulatorCreds) RequireTransportSecurity() bool {
	return false
}

func main() {
	// runFirestoreContainer {
	ctx := context.Background()

	firestoreContainer, err := gcloud.RunFirestore(
		ctx,
		"gcr.io/google.com/cloudsdktool/cloud-sdk:367.0.0-emulators",
		gcloud.WithProjectID("firestore-project"),
	)
	if err != nil {
		log.Fatalf("failed to run container: %v", err)
	}

	// Clean up the container
	defer func() {
		if err := firestoreContainer.Terminate(ctx); err != nil {
			log.Fatalf("failed to terminate container: %v", err)
		}
	}()
	// }

	// firestoreClient {
	projectID := firestoreContainer.Settings.ProjectID

	conn, err := grpc.NewClient(firestoreContainer.URI, grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithPerRPCCredentials(emulatorCreds{}))
	if err != nil {
		log.Fatalf("failed to dial: %v", err) // nolint:gocritic
	}

	options := []option.ClientOption{option.WithGRPCConn(conn)}
	client, err := firestore.NewClient(ctx, projectID, options...)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	defer client.Close()
	// }

	users := client.Collection("users")
	docRef := users.Doc("alovelace")

	type Person struct {
		Firstname string `json:"firstname"`
		Lastname  string `json:"lastname"`
	}

	data := Person{
		Firstname: "Ada",
		Lastname:  "Lovelace",
	}
	_, err = docRef.Create(ctx, data)
	if err != nil {
		log.Fatalf("failed to create document: %v", err)
	}

	docsnap, err := docRef.Get(ctx)
	if err != nil {
		log.Fatalf("failed to get document: %v", err)
	}

	var saved Person
	if err := docsnap.DataTo(&saved); err != nil {
		log.Fatalf("failed to convert data: %v", err)
	}

	fmt.Println(saved.Firstname, saved.Lastname)

}
Output:

Ada Lovelace

func RunPubsub added in v0.32.0

func RunPubsub(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

RunPubsub creates an instance of the GCloud container type for Pubsub.

func RunPubsubContainer deprecated

func RunPubsubContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

Deprecated: use RunPubsub instead RunPubsubContainer creates an instance of the GCloud container type for Pubsub.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/pubsub"
	"google.golang.org/api/option"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"github.com/testcontainers/testcontainers-go/modules/gcloud"
)

func main() {
	// runPubsubContainer {
	ctx := context.Background()

	pubsubContainer, err := gcloud.RunPubsub(
		ctx,
		"gcr.io/google.com/cloudsdktool/cloud-sdk:367.0.0-emulators",
		gcloud.WithProjectID("pubsub-project"),
	)
	if err != nil {
		log.Fatalf("failed to run container: %v", err)
	}

	// Clean up the container
	defer func() {
		if err := pubsubContainer.Terminate(ctx); err != nil {
			log.Fatalf("failed to terminate container: %v", err)
		}
	}()
	// }

	// pubsubClient {
	projectID := pubsubContainer.Settings.ProjectID

	conn, err := grpc.NewClient(pubsubContainer.URI, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("failed to dial: %v", err) // nolint:gocritic
	}

	options := []option.ClientOption{option.WithGRPCConn(conn)}
	client, err := pubsub.NewClient(ctx, projectID, options...)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	defer client.Close()
	// }

	topic, err := client.CreateTopic(ctx, "greetings")
	if err != nil {
		log.Fatalf("failed to create topic: %v", err)
	}
	subscription, err := client.CreateSubscription(ctx, "subscription",
		pubsub.SubscriptionConfig{Topic: topic})
	if err != nil {
		log.Fatalf("failed to create subscription: %v", err)
	}
	result := topic.Publish(ctx, &pubsub.Message{Data: []byte("Hello World")})
	_, err = result.Get(ctx)
	if err != nil {
		log.Fatalf("failed to publish message: %v", err)
	}

	var data []byte
	cctx, cancel := context.WithCancel(ctx)
	err = subscription.Receive(cctx, func(ctx context.Context, m *pubsub.Message) {
		data = m.Data
		m.Ack()
		defer cancel()
	})
	if err != nil {
		log.Fatalf("failed to receive message: %v", err)
	}

	fmt.Println(string(data))

}
Output:

Hello World

func RunSpanner added in v0.32.0

func RunSpanner(ctx context.Context, img string, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

RunSpanner creates an instance of the GCloud container type for Spanner.

func RunSpannerContainer deprecated

func RunSpannerContainer(ctx context.Context, opts ...testcontainers.ContainerCustomizer) (*GCloudContainer, error)

Deprecated: use RunSpanner instead RunSpannerContainer creates an instance of the GCloud container type for Spanner.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/spanner"
	database "cloud.google.com/go/spanner/admin/database/apiv1"

	databasepb "cloud.google.com/go/spanner/admin/database/apiv1/databasepb"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"

	instancepb "cloud.google.com/go/spanner/admin/instance/apiv1/instancepb"
	"google.golang.org/api/option"
	"google.golang.org/api/option/internaloption"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"

	"github.com/testcontainers/testcontainers-go/modules/gcloud"
)

func main() {
	// runSpannerContainer {
	ctx := context.Background()

	spannerContainer, err := gcloud.RunSpanner(
		ctx,
		"gcr.io/cloud-spanner-emulator/emulator:1.4.0",
		gcloud.WithProjectID("spanner-project"),
	)
	if err != nil {
		log.Fatalf("failed to run container: %v", err)
	}

	// Clean up the container
	defer func() {
		if err := spannerContainer.Terminate(ctx); err != nil {
			log.Fatalf("failed to terminate container: %v", err)
		}
	}()
	// }

	// spannerAdminClient {
	projectId := spannerContainer.Settings.ProjectID

	const (
		instanceId   = "test-instance"
		databaseName = "test-db"
	)

	options := []option.ClientOption{
		option.WithEndpoint(spannerContainer.URI),
		option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
		option.WithoutAuthentication(),
		internaloption.SkipDialSettingsValidation(),
	}

	instanceAdmin, err := instance.NewInstanceAdminClient(ctx, options...)
	if err != nil {
		log.Fatalf("failed to create instance admin client: %v", err) // nolint:gocritic
	}
	defer instanceAdmin.Close()
	// }

	instanceOp, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{
		Parent:     fmt.Sprintf("projects/%s", projectId),
		InstanceId: instanceId,
		Instance: &instancepb.Instance{
			DisplayName: instanceId,
		},
	})
	if err != nil {
		log.Fatalf("failed to create instance: %v", err)
	}

	_, err = instanceOp.Wait(ctx)
	if err != nil {
		log.Fatalf("failed to wait for instance creation: %v", err)
	}

	// spannerDBAdminClient {
	c, err := database.NewDatabaseAdminClient(ctx, options...)
	if err != nil {
		log.Fatalf("failed to create admin client: %v", err)
	}
	defer c.Close()
	// }

	databaseOp, err := c.CreateDatabase(ctx, &databasepb.CreateDatabaseRequest{
		Parent:          fmt.Sprintf("projects/%s/instances/%s", projectId, instanceId),
		CreateStatement: fmt.Sprintf("CREATE DATABASE `%s`", databaseName),
		ExtraStatements: []string{
			"CREATE TABLE Languages (Language STRING(MAX), Mascot STRING(MAX)) PRIMARY KEY (Language)",
		},
	})
	if err != nil {
		log.Fatalf("failed to create database: %v", err)
	}
	_, err = databaseOp.Wait(ctx)
	if err != nil {
		log.Fatalf("failed to wait for database creation: %v", err)
	}

	db := fmt.Sprintf("projects/%s/instances/%s/databases/%s", projectId, instanceId, databaseName)
	client, err := spanner.NewClient(ctx, db, options...)
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	defer client.Close()

	_, err = client.Apply(ctx, []*spanner.Mutation{
		spanner.Insert("Languages",
			[]string{"language", "mascot"},
			[]interface{}{"Go", "Gopher"}),
	})
	if err != nil {
		log.Fatalf("failed to apply mutation: %v", err)
	}
	row, err := client.Single().ReadRow(ctx, "Languages",
		spanner.Key{"Go"}, []string{"mascot"})
	if err != nil {
		log.Fatalf("failed to read row: %v", err)
	}

	var mascot string
	err = row.ColumnByName("Mascot", &mascot)
	if err != nil {
		log.Fatalf("failed to read column: %v", err)
	}

	fmt.Println(mascot)

}
Output:

Gopher

type Option

type Option func(*options)

Option is an option for the GCloud container.

func WithProjectID

func WithProjectID(projectID string) Option

WithProjectID sets the project ID for the GCloud container.

func (Option) Customize

func (o Option) Customize(*testcontainers.GenericContainerRequest) error

Customize is a NOOP. It's defined to satisfy the testcontainers.ContainerCustomizer interface.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL