How to use CreateTestHandler method of v1 Package

Best Testkube code snippet using v1.CreateTestHandler

api_test.go

Source:api_test.go Github

copy

Full Screen

1package rest2import (3 "context"4 "encoding/json"5 "fmt"6 "io"7 "io/ioutil"8 "net/http"9 "net/http/httptest"10 "strings"11 "testing"12 kitlog "github.com/go-kit/kit/log"13 errors "github.com/go-openapi/errors"14 "github.com/go-openapi/swag"15 "github.com/stretchr/testify/assert"16 "github.com/stretchr/testify/require"17 yaml "gopkg.in/yaml.v2"18 corev1 "k8s.io/api/core/v1"19 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"20 "k8s.io/apimachinery/pkg/runtime"21 "k8s.io/client-go/kubernetes/fake"22 "k8s.io/client-go/tools/cache"23 apipkg "github.com/sapcc/kubernikus/pkg/api"24 "github.com/sapcc/kubernikus/pkg/api/auth"25 "github.com/sapcc/kubernikus/pkg/api/models"26 "github.com/sapcc/kubernikus/pkg/api/rest/operations"27 "github.com/sapcc/kubernikus/pkg/api/spec"28 "github.com/sapcc/kubernikus/pkg/apis/kubernikus"29 kubernikusv1 "github.com/sapcc/kubernikus/pkg/apis/kubernikus/v1"30 "github.com/sapcc/kubernikus/pkg/client/kubernetes"31 kubernikusfake "github.com/sapcc/kubernikus/pkg/generated/clientset/fake"32 "github.com/sapcc/kubernikus/pkg/util"33)34const (35 NAMESPACE = "test"36 TOKEN = "abc123"37 ACCOUNT = "testaccount"38)39func init() {40 auth.DefaultPolicyFile = "../../../etc/policy.json"41}42func mockAuth(token string) (*models.Principal, error) {43 if token != TOKEN {44 return nil, errors.New(401, "auth failed")45 }46 return &models.Principal{47 ID: "test",48 Name: "Test Mc Dougle",49 Domain: "TestDomain",50 Account: ACCOUNT,51 Roles: []string{"member", "kubernetes_admin"},52 }, nil53}54func createTestHandler(t *testing.T, klusters ...runtime.Object) (http.Handler, *apipkg.Runtime, func()) {55 swaggerSpec, err := spec.Spec()56 if err != nil {57 t.Fatal(err)58 }59 api := operations.NewKubernikusAPI(swaggerSpec)60 rt := apipkg.NewRuntime(61 NAMESPACE,62 kubernikusfake.NewSimpleClientset(klusters...),63 fake.NewSimpleClientset(),64 kitlog.NewNopLogger(),65 )66 rt.KlusterClientFactory = &kubernetes.MockSharedClientFactory{67 Clientset: fake.NewSimpleClientset(),68 }69 if err := Configure(api, rt); err != nil {70 t.Fatal(err)71 }72 api.KeystoneAuth = mockAuth73 return configureAPI(api), rt, runInformer(rt)74}75func runInformer(rt *apipkg.Runtime) func() {76 closeCh := make(chan struct{})77 go rt.Informer.Run(closeCh)78 cache.WaitForCacheSync(nil, rt.Informer.HasSynced)79 return func() {80 close(closeCh)81 }82}83func createRequest(method, path, body string) *http.Request {84 var buf io.Reader85 if body != "" {86 buf = strings.NewReader(body)87 }88 req := httptest.NewRequest(method, path, buf)89 req.Header.Set("Content-Type", "application/json")90 req.Header.Set("X-Auth-Token", TOKEN)91 return req92}93func result(handler http.Handler, req *http.Request) (int, http.Header, []byte) {94 rec := httptest.NewRecorder()95 handler.ServeHTTP(rec, req)96 response := rec.Result()97 body, _ := ioutil.ReadAll(response.Body)98 return response.StatusCode, response.Header, body99}100func TestCreateCluster(t *testing.T) {101 handler, rt, cancel := createTestHandler(t)102 defer cancel()103 req := createRequest("POST", "/api/v1/clusters", `{"name": "nase", "spec": { "openstack": { "routerID":"routerA"}}}`)104 code, _, body := result(handler, req)105 if !assert.Equal(t, 201, code) {106 return107 }108 //Test create109 crd, err := rt.Kubernikus.KubernikusV1().Klusters(rt.Namespace).Get(context.Background(), fmt.Sprintf("%s-%s", "nase", ACCOUNT), metav1.GetOptions{})110 assert.NoError(t, err, "resource not persisted")111 assert.Equal(t, crd.Labels["account"], ACCOUNT)112 var kluster models.Kluster113 assert.NoError(t, kluster.UnmarshalBinary(body), "Failed to parse response")114 assert.Equal(t, "nase", kluster.Name)115 assert.Equal(t, "nase", kluster.Spec.Name)116 assert.Equal(t, models.KlusterPhasePending, kluster.Status.Phase)117 assert.Equal(t, kubernikus.DEFAULT_CLUSTER_CIDR, *kluster.Spec.ClusterCIDR)118 //Ensure authentication is required119 req = createRequest("POST", "/api/v1/clusters", `{"name": "nase2"}`)120 req.Header.Del("X-Auth-Token")121 code, _, _ = result(handler, req)122 assert.Equal(t, 401, code)123 //Ensure cluster CIDR does not overlap with other clusters specifying no router124 req = createRequest("POST", "/api/v1/clusters", `{"name": "ohr" }`)125 code, _, body = result(handler, req)126 if assert.Equal(t, 409, code, "response body: %s", string(body)) {127 assert.Contains(t, string(body), "nase", "when specifying no router it should always conflict with exiting clusters")128 }129 //Ensure cluster CIDR does not overlap with other clusters using the same router130 req = createRequest("POST", "/api/v1/clusters", `{"name": "ohr", "spec": { "openstack": { "routerID":"routerA"}}}`)131 code, _, body = result(handler, req)132 if assert.Equal(t, 409, code, "response body: %s", string(body)) {133 assert.Contains(t, string(body), "nase")134 }135 //Ensure specifying a different router doesn't obverlap136 req = createRequest("POST", "/api/v1/clusters", `{"name": "ohr", "spec": { "openstack": { "routerID":"routerB"}}}`)137 code, _, body = result(handler, req)138 assert.Equal(t, 201, code, "specifying a different router should not conflict. response: %s", string(body))139 //Ensure we refuse service CIDRs that overlap with the control plane140 rt.Kubernikus = kubernikusfake.NewSimpleClientset()141 rt.Kubernetes = fake.NewSimpleClientset(&corev1.Service{142 ObjectMeta: metav1.ObjectMeta{143 Name: "kubernetes",144 Namespace: "default",145 },146 Spec: corev1.ServiceSpec{147 ClusterIP: "198.18.128.1",148 },149 })150 req = createRequest("POST", "/api/v1/clusters", `{"name": "nase"}`)151 code, _, body = result(handler, req)152 if assert.Equal(t, 409, code) {153 assert.Contains(t, string(body), "CIDR")154 }155 //Ensure specifying a different router doesn't obverlap156 req = createRequest("POST", "/api/v1/clusters", `{"name": "nocidr", "spec": { "clusterCIDR": "", "noCloud": true, "serviceCIDR":"5.5.5.5/24"}}`)157 code, _, body = result(handler, req)158 assert.Equal(t, 201, code, "Creating a cluster with empty clusterCIDR should not fail. response: %s", string(body))159 k, err := rt.Kubernikus.KubernikusV1().Klusters(NAMESPACE).Get(context.Background(), "nocidr-"+ACCOUNT, metav1.GetOptions{})160 assert.NoError(t, err)161 assert.Empty(t, k.Spec.ClusterCIDR)162}163func TestClusterShow(t *testing.T) {164 kluster := kubernikusv1.Kluster{165 ObjectMeta: metav1.ObjectMeta{166 Name: fmt.Sprintf("%s-%s", "nase", ACCOUNT),167 Namespace: NAMESPACE,168 Labels: map[string]string{"account": ACCOUNT},169 },170 Spec: models.KlusterSpec{Name: "nase"},171 }172 handler, _, cancel := createTestHandler(t, &kluster)173 defer cancel()174 //Test Success175 req := createRequest("GET", "/api/v1/clusters/nase", "")176 code, _, body := result(handler, req)177 if !assert.Equal(t, 200, code) {178 return179 }180 var apiKluster models.Kluster181 assert.NoError(t, apiKluster.UnmarshalBinary(body), "Failed to parse response")182 assert.Equal(t, "nase", apiKluster.Name)183 //Test 404184 req = createRequest("GET", "/api/v1/clusters/doesnotexit", "")185 code, _, _ = result(handler, req)186 assert.Equal(t, 404, code)187}188func TestClusterList(t *testing.T) {189 kluster1 := &kubernikusv1.Kluster{190 ObjectMeta: metav1.ObjectMeta{191 Name: fmt.Sprintf("%s-%s", "nase", ACCOUNT),192 Namespace: NAMESPACE,193 Labels: map[string]string{"account": ACCOUNT},194 },195 Spec: models.KlusterSpec{Name: "nase"},196 }197 kluster2 := &kubernikusv1.Kluster{198 ObjectMeta: metav1.ObjectMeta{199 Name: fmt.Sprintf("%s-%s", "mund", ACCOUNT),200 Namespace: NAMESPACE,201 Labels: map[string]string{"account": ACCOUNT},202 },203 Spec: models.KlusterSpec{Name: "mund"},204 }205 otherKluster := &kubernikusv1.Kluster{206 ObjectMeta: metav1.ObjectMeta{207 Name: fmt.Sprintf("%s-%s", "ohr", "other"),208 Namespace: NAMESPACE,209 Labels: map[string]string{"account": "other"},210 },211 Spec: models.KlusterSpec{Name: "ohr"},212 }213 handler, _, cancel := createTestHandler(t, kluster1, kluster2, otherKluster)214 defer cancel()215 //Test Success216 req := createRequest("GET", "/api/v1/clusters", "")217 code, _, body := result(handler, req)218 if !assert.Equal(t, 200, code) {219 return220 }221 var apiKlusters []models.Kluster222 assert.NoError(t, json.Unmarshal(body, &apiKlusters), "Failed to parse response")223 assert.ElementsMatch(t, []models.Kluster{224 {225 Name: "nase",226 Spec: models.KlusterSpec{Name: "nase"},227 },228 {229 Name: "mund",230 Spec: models.KlusterSpec{Name: "mund"},231 },232 }, apiKlusters)233}234func TestClusterUpdate(t *testing.T) {235 on := true236 off := false237 kluster := kubernikusv1.Kluster{238 ObjectMeta: metav1.ObjectMeta{239 Name: fmt.Sprintf("%s-%s", "nase", ACCOUNT),240 Namespace: NAMESPACE,241 Labels: map[string]string{"account": ACCOUNT},242 },243 Spec: models.KlusterSpec{244 AdvertiseAddress: "0.0.0.0",245 ClusterCIDR: swag.String("1.1.1.1/24"),246 DNSAddress: "2.2.2.254",247 DNSDomain: "cluster.local",248 Name: "nase",249 ServiceCIDR: "2.2.2.2/24",250 Openstack: models.OpenstackSpec{251 LBSubnetID: "lbid",252 NetworkID: "networkid",253 RouterID: "routerid",254 },255 NodePools: []models.NodePool{256 {257 AvailabilityZone: "us-west-1a",258 Flavor: "flavour",259 Image: "image",260 Name: "poolname",261 Size: 2,262 Config: &models.NodePoolConfig{263 AllowReboot: &off,264 AllowReplace: &off,265 },266 },267 },268 },269 Status: models.KlusterStatus{270 Phase: models.KlusterPhaseRunning,271 Version: "someversion",272 },273 }274 handler, _, cancel := createTestHandler(t, &kluster)275 defer cancel()276 updateObject := models.Kluster{277 Name: "mund",278 Spec: models.KlusterSpec{279 AdvertiseAddress: "7.7.7.7",280 ClusterCIDR: swag.String("8.8.8.8/24"),281 DNSAddress: "9.9.9.9",282 DNSDomain: "changed",283 Name: "mund",284 ServiceCIDR: "9.9.9.9/24",285 Openstack: models.OpenstackSpec{286 LBSubnetID: "changed",287 NetworkID: "changed",288 RouterID: "changed",289 },290 NodePools: []models.NodePool{291 {292 AvailabilityZone: "us-west-1a",293 Flavor: "flavour",294 Image: "image",295 Name: "poolname",296 Size: 5,297 Config: &models.NodePoolConfig{298 AllowReboot: &on,299 AllowReplace: &on,300 },301 },302 {303 AvailabilityZone: "us-east-1a",304 Flavor: "newflavour",305 Image: "newimage",306 Name: "newpoolname",307 Size: 3,308 Config: &models.NodePoolConfig{309 AllowReboot: &on,310 AllowReplace: &on,311 },312 },313 },314 },315 Status: models.KlusterStatus{316 Phase: models.KlusterPhaseTerminating,317 Version: "changed",318 },319 }320 jsonPayload, err := updateObject.MarshalBinary()321 assert.NoError(t, err, "marshaling update payload failed")322 req := createRequest("PUT", "/api/v1/clusters/nase", string(jsonPayload))323 code, _, body := result(handler, req)324 if !assert.Equal(t, 200, code) {325 return326 }327 var apiResponse models.Kluster328 assert.NoError(t, apiResponse.UnmarshalBinary(body), "Failed to parse response")329 //assert fields are immutable330 assert.Equal(t, "nase", apiResponse.Name)331 assert.Equal(t, "0.0.0.0", apiResponse.Spec.AdvertiseAddress)332 assert.Equal(t, "1.1.1.1/24", *apiResponse.Spec.ClusterCIDR)333 assert.Equal(t, "2.2.2.254", apiResponse.Spec.DNSAddress)334 assert.Equal(t, "cluster.local", apiResponse.Spec.DNSDomain)335 assert.Equal(t, "nase", apiResponse.Spec.Name)336 assert.Equal(t, "2.2.2.2/24", apiResponse.Spec.ServiceCIDR)337 assert.Equal(t, "lbid", apiResponse.Spec.Openstack.LBSubnetID)338 assert.Equal(t, "networkid", apiResponse.Spec.Openstack.NetworkID)339 assert.Equal(t, "routerid", apiResponse.Spec.Openstack.RouterID)340 assert.Equal(t, models.KlusterPhaseRunning, apiResponse.Status.Phase)341 assert.Equal(t, "someversion", apiResponse.Status.Version)342 //assert nodepool was updated343 assert.Equal(t, updateObject.Spec.NodePools, apiResponse.Spec.NodePools)344}345func TestVersionUpdate(t *testing.T) {346 kluster := kubernikusv1.Kluster{347 ObjectMeta: metav1.ObjectMeta{348 Name: fmt.Sprintf("%s-%s", "nase", ACCOUNT),349 Namespace: NAMESPACE,350 Labels: map[string]string{"account": ACCOUNT},351 },352 Spec: models.KlusterSpec{353 Version: "1.10.1",354 },355 Status: models.KlusterStatus{356 ApiserverVersion: "1.10.1",357 },358 }359 cases := []struct {360 Version string361 Phase models.KlusterPhase362 ExpectSuccess bool363 }{364 {"1.10.1", models.KlusterPhaseRunning, true},365 {"1.10.0", models.KlusterPhaseRunning, true},366 {"1.10.2", models.KlusterPhaseRunning, true},367 {"1.10.3", models.KlusterPhaseUpgrading, false},368 {"1.11.2", models.KlusterPhaseRunning, true},369 {"1.9.2", models.KlusterPhaseRunning, false},370 {"1.12.2", models.KlusterPhaseRunning, false},371 {"2.0.0", models.KlusterPhaseRunning, false},372 }373 for _, c := range cases {374 k := kluster.DeepCopy()375 k.Status.Phase = c.Phase376 handler, _, cancel := createTestHandler(t, k)377 defer cancel()378 updateObject := models.Kluster{379 Name: "nase",380 Spec: models.KlusterSpec{381 Version: c.Version,382 },383 }384 jsonPayload, err := updateObject.MarshalBinary()385 if !assert.NoError(t, err, "marshaling update payload failed version %s", c.Version) {386 continue387 }388 req := createRequest("PUT", "/api/v1/clusters/nase", string(jsonPayload))389 code, _, body := result(handler, req)390 if c.ExpectSuccess {391 if assert.Equal(t, 200, code, "Update to version %s should be accepted. Response: %d, %s", c.Version, code, string(body)) {392 var apiResponse models.Kluster393 assert.NoError(t, apiResponse.UnmarshalBinary(body), "Failed to parse response for version %s", c.Version)394 assert.Equal(t, c.Version, apiResponse.Spec.Version, "Update to version %s failed", c.Version)395 }396 } else {397 assert.Equal(t, 400, code, "Update to version %s should be rejected. Response: %d, %s", c.Version, code, string(body))398 }399 }400}401func TestClusterBootstrapConfig(t *testing.T) {402 kluster := &kubernikusv1.Kluster{403 ObjectMeta: metav1.ObjectMeta{404 Name: fmt.Sprintf("%s-%s", "nase", ACCOUNT),405 Namespace: NAMESPACE,406 Labels: map[string]string{"account": ACCOUNT},407 },408 Spec: models.KlusterSpec{409 Version: "1.10.1",410 DNSDomain: "example.com",411 },412 Status: models.KlusterStatus{413 ApiserverVersion: "1.10.1",414 },415 }416 handler, rt, cancel := createTestHandler(t, kluster)417 defer cancel()418 _, err := util.EnsureKlusterSecret(rt.Kubernetes, kluster)419 if !assert.NoError(t, err, "failed to ensure kluster secret") {420 return421 }422 req := createRequest("GET", "/api/v1/clusters/nase/bootstrap", "")423 code, _, body := result(handler, req)424 require.Equal(t, 200, code, string(body))425 //I don't want to vendor https://github.com/kubernetes/kubelet sp I'm just checking if the yaml parses correctly426 var apiResponse models.BootstrapConfig427 require.NoError(t, apiResponse.UnmarshalBinary(body), "failed to parse api response")428 type fakeKubeletConfig struct {429 Kind string `yaml:"kind"`430 APIVersion string `yaml:"apiVersion"`431 RotateCertificates bool `yaml:"rotateCertificates,omitempty"`432 ClusterDomain string `yaml:"clusterDomain,omitempty"`433 }434 var config fakeKubeletConfig435 require.NoError(t, yaml.Unmarshal([]byte(apiResponse.Config), &config))436 assert.Equal(t, fakeKubeletConfig{437 Kind: "KubeletConfiguration",438 APIVersion: "kubelet.config.k8s.io/v1beta1",439 ClusterDomain: "example.com",440 RotateCertificates: true,441 }, config)442}...

Full Screen

Full Screen

tests.go

Source:tests.go Github

copy

Full Screen

...278 }279 return c.JSON(results)280 }281}282// CreateTestHandler creates new test CR based on test content283func (s TestkubeAPI) CreateTestHandler() fiber.Handler {284 return func(c *fiber.Ctx) error {285 var request testkube.TestUpsertRequest286 err := c.BodyParser(&request)287 if err != nil {288 return s.Error(c, http.StatusBadRequest, err)289 }290 if c.Accepts(mediaTypeJSON, mediaTypeYAML) == mediaTypeYAML {291 if request.Content != nil && request.Content.Data != "" {292 request.Content.Data = fmt.Sprintf("%q", request.Content.Data)293 }294 if request.ExecutionRequest != nil && request.ExecutionRequest.VariablesFile != "" {295 request.ExecutionRequest.VariablesFile = fmt.Sprintf("%q", request.ExecutionRequest.VariablesFile)296 }297 data, err := crd.GenerateYAML(crd.TemplateTest, []testkube.TestUpsertRequest{request})...

Full Screen

Full Screen

handler_test.go

Source:handler_test.go Github

copy

Full Screen

1/*2Copyright 2020 The Knative Authors3Licensed under the Apache License, Version 2.0 (the "License");4you may not use this file except in compliance with the License.5You may obtain a copy of the License at6 http://www.apache.org/licenses/LICENSE-2.07Unless required by applicable law or agreed to in writing, software8distributed under the License is distributed on an "AS IS" BASIS,9WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10See the License for the specific language governing permissions and11limitations under the License.12*/13package dispatcher14import (15 "context"16 "fmt"17 "net/http"18 "net/url"19 "strings"20 "testing"21 "time"22 "github.com/Shopify/sarama"23 kafkasaramaprotocol "github.com/cloudevents/sdk-go/protocol/kafka_sarama/v2"24 "github.com/cloudevents/sdk-go/v2/binding"25 "github.com/stretchr/testify/assert"26 "go.uber.org/zap"27 "go.uber.org/zap/zapcore"28 "k8s.io/apimachinery/pkg/types"29 eventingduck "knative.dev/eventing/pkg/apis/duck/v1"30 "knative.dev/eventing/pkg/channel"31 "knative.dev/eventing/pkg/kncloudevents"32 "knative.dev/pkg/apis"33 duckv1 "knative.dev/pkg/apis/duck/v1"34 logtesting "knative.dev/pkg/logging/testing"35 dispatchertesting "knative.dev/eventing-kafka/pkg/channel/distributed/dispatcher/testing"36)37// Test Data38const (39 testSubscriberUID = types.UID("123")40 testSubscriberURIString = "https://www.foo.bar/test/path"41 testReplyURIString = "https://www.something.com/"42 testDeadLetterURIString = "https://www.made.up/url"43 testTopic = "TestTopic"44 testPartition = 045 testOffset = 146 testMsgSpecVersion = "1.0"47 testMsgContentType = "application/json"48 testMsgId = "TestMsgId"49 testMsgSource = "TestMsgSource"50 testMsgType = "TestMsgType"51 testMsgEventTypeVersion = "TestMsgEventTypeVersion"52 testMsgKnativeHistory = "TestKnativeHistory"53 testMsgJsonContentString = "{\"content\": \"Test Message 1\"}"54 testB3TraceId = "TestB3TraceId"55)56var (57 testSubscriberURI, _ = apis.ParseURL(testSubscriberURIString)58 testReplyURI, _ = apis.ParseURL(testReplyURIString)59 testRetryCount = int32(4)60 testBackoffPolicy = eventingduck.BackoffPolicyExponential61 testBackoffDelay = "PT1S"62 testDeadLetterURI, _ = apis.ParseURL(testDeadLetterURIString)63 testMsgTime = time.Now().UTC().Format(time.RFC3339)64 testConsumerGroupId = fmt.Sprintf("kafka.%s", testSubscriberUID)65)66// Test The NewHandler() Functionality67func TestNewHandler(t *testing.T) {68 assert.NotNil(t, createTestHandler)69}70type HandleTestCase struct {71 only bool72 name string73 destinationUri *apis.URL74 replyUri *apis.URL75 deadLetterUri *apis.URL76 dispatchErr error77 retry bool78 expectMarkMessage bool79}80// Test The Handler's Handle() Functionality81func TestHandle(t *testing.T) {82 // Define The HandleTestCases83 testCases := []HandleTestCase{84 {85 name: "Complete Subscriber Configuration",86 destinationUri: testSubscriberURI,87 replyUri: testReplyURI,88 deadLetterUri: testDeadLetterURI,89 retry: true,90 expectMarkMessage: true,91 },92 {93 name: "No Subscriber URL",94 replyUri: testReplyURI,95 deadLetterUri: testDeadLetterURI,96 retry: true,97 expectMarkMessage: true,98 },99 {100 name: "No Reply URL",101 destinationUri: testSubscriberURI,102 deadLetterUri: testDeadLetterURI,103 retry: true,104 expectMarkMessage: true,105 },106 {107 name: "No DeadLetter URL",108 destinationUri: testSubscriberURI,109 replyUri: testReplyURI,110 retry: true,111 expectMarkMessage: true,112 },113 {114 name: "No Retry",115 destinationUri: testSubscriberURI,116 replyUri: testReplyURI,117 deadLetterUri: testDeadLetterURI,118 retry: false,119 expectMarkMessage: true,120 },121 {122 name: "Empty Subscriber Configuration",123 retry: false,124 expectMarkMessage: true,125 },126 {127 name: "Context Canceled",128 destinationUri: testSubscriberURI,129 replyUri: testReplyURI,130 deadLetterUri: testDeadLetterURI,131 retry: true,132 dispatchErr: context.Canceled,133 expectMarkMessage: false,134 },135 }136 // Filter To Those With "only" Flag (If Any Specified)137 filteredTestCases := make([]HandleTestCase, 0)138 for _, testCase := range testCases {139 if testCase.only {140 filteredTestCases = append(filteredTestCases, testCase)141 }142 }143 if len(filteredTestCases) == 0 {144 filteredTestCases = testCases145 }146 // Execute The Individual Test Cases147 for _, testCase := range filteredTestCases {148 t.Run(testCase.name, func(t *testing.T) {149 performHandleTest(t, testCase)150 })151 }152}153func TestSetReady(t *testing.T) {154 handler := createTestHandler(t, testSubscriberURI, testReplyURI, nil)155 handler.SetReady(1, true)156}157func TestGetConsumerGroup(t *testing.T) {158 handler := createTestHandler(t, testSubscriberURI, testReplyURI, nil)159 actualConsumerGroupId := handler.GetConsumerGroup()160 assert.Equal(t, testConsumerGroupId, actualConsumerGroupId)161}162// Test One Permutation Of The Handler's Handle() Functionality163func performHandleTest(t *testing.T, testCase HandleTestCase) {164 // Create The Expected Headers165 headers := http.Header{166 "Content-Type": []string{testMsgContentType},167 "X-B3-Traceid": []string{testB3TraceId},168 }169 // Initialize Destination As Specified170 var destinationUrl *url.URL171 if testCase.destinationUri != nil {172 destinationUrl = testCase.destinationUri.URL()173 }174 // Initialize Reply As Specified175 var replyUrl *url.URL176 if testCase.replyUri != nil {177 replyUrl = testCase.replyUri.URL()178 }179 // Initialize DeadLetter As Specified180 var deadLetterUrl *url.URL181 if testCase.deadLetterUri != nil {182 deadLetterUrl = testCase.deadLetterUri.URL()183 }184 // Create The Specified DeliverySpec185 deliverySpec := createDeliverySpec(testCase.deadLetterUri, testCase.retry)186 // Create The Expected RetryConfig187 var retryConfig kncloudevents.RetryConfig188 if testCase.retry {189 var err error190 retryConfig, err = kncloudevents.RetryConfigFromDeliverySpec(deliverySpec)191 assert.NotNil(t, retryConfig)192 assert.Nil(t, err)193 }194 // Create Mocks For Testing195 mockMessageDispatcher := dispatchertesting.NewMockMessageDispatcher(t, headers, destinationUrl, replyUrl, deadLetterUrl, &retryConfig, testCase.dispatchErr)196 // Mock The newMessageDispatcherWrapper Function (And Restore Post-Test)197 newMessageDispatcherWrapperPlaceholder := newMessageDispatcherWrapper198 newMessageDispatcherWrapper = func(logger *zap.Logger) channel.MessageDispatcher {199 return mockMessageDispatcher200 }201 defer func() { newMessageDispatcherWrapper = newMessageDispatcherWrapperPlaceholder }()202 // Create The Handler To Test203 handler := createTestHandler(t, testCase.destinationUri, testCase.replyUri, &deliverySpec)204 // Perform The Test205 consumerMessage := createConsumerMessage(t)206 result, err := handler.Handle(context.TODO(), consumerMessage)207 // Verify The Results208 assert.Nil(t, err)209 assert.Equal(t, testCase.expectMarkMessage, result)210 assert.NotNil(t, mockMessageDispatcher.Message())211 verifyDispatchedMessage(t, mockMessageDispatcher.Message())212}213// Verify The Dispatched Message Contains Test Message Contents (Was Not Corrupted)214func verifyDispatchedMessage(t *testing.T, message binding.MessageReader) {215 dispatchedEvent, err := binding.ToEvent(context.TODO(), message)216 assert.NotNil(t, dispatchedEvent)217 assert.Nil(t, err)218 assert.Equal(t, testMsgId, dispatchedEvent.Context.GetID())219 assert.Equal(t, testMsgSource, dispatchedEvent.Context.GetSource())220 assert.Equal(t, testMsgType, dispatchedEvent.Context.GetType())221 eventTypeVersionExtension, err := dispatchedEvent.Context.GetExtension("eventtypeversion")222 assert.Nil(t, err)223 assert.Equal(t, testMsgEventTypeVersion, eventTypeVersionExtension)224 knativeHistoryExtension, err := dispatchedEvent.Context.GetExtension("knativehistory")225 assert.Nil(t, err)226 assert.Equal(t, testMsgKnativeHistory, knativeHistoryExtension)227 assert.Equal(t, testMsgContentType, dispatchedEvent.Context.GetDataContentType())228 assert.Equal(t, testMsgTime, dispatchedEvent.Context.GetTime().Format(time.RFC3339))229 assert.Equal(t, testMsgJsonContentString, string(dispatchedEvent.DataEncoded))230}231// Utility Function Fro Creating A Test DeliverySpec232func createDeliverySpec(deadLetterUri *apis.URL, retry bool) eventingduck.DeliverySpec {233 // Create An Empty DeliverySpec234 deliverySpec := eventingduck.DeliverySpec{}235 // Populate DeadLetter URL If Specified236 if deadLetterUri != nil {237 deliverySpec.DeadLetterSink = &duckv1.Destination{238 URI: deadLetterUri,239 }240 }241 // Populate Retry Config If Specified242 if retry {243 deliverySpec.Retry = &testRetryCount244 deliverySpec.BackoffPolicy = &testBackoffPolicy245 deliverySpec.BackoffDelay = &testBackoffDelay246 }247 // Return The Configured DeliverySpec248 return deliverySpec249}250// Utility Function For Creating New Handler251func createTestHandler(t *testing.T, subscriberURL *apis.URL, replyUrl *apis.URL, delivery *eventingduck.DeliverySpec) *Handler {252 // Test Data253 logger := logtesting.TestLogger(t).Desugar()254 testSubscriber := &eventingduck.SubscriberSpec{255 UID: testSubscriberUID,256 Generation: 0,257 SubscriberURI: subscriberURL,258 ReplyURI: replyUrl,259 Delivery: delivery,260 }261 // Perform The Test Create The Test Handler262 handler := NewHandler(logger, testConsumerGroupId, testSubscriber)263 // Verify The Results264 assert.NotNil(t, handler)265 assert.Equal(t, logger, handler.Logger)266 assert.Equal(t, testSubscriber, handler.Subscriber)267 assert.NotNil(t, handler.MessageDispatcher)268 // Return The Handler269 return handler270}271// Utility Function For Creating Valid ConsumerMessages272func createConsumerMessage(t *testing.T) *sarama.ConsumerMessage {273 // Create The ConsumerMessage To Test (Matches What Comes Out Of Knative MessageReceiver)274 consumerMessage := &sarama.ConsumerMessage{275 Headers: []*sarama.RecordHeader{276 {277 Key: []byte("content-type"),278 Value: []byte(testMsgContentType),279 },280 {281 Key: []byte("ce_specversion"),282 Value: []byte(testMsgSpecVersion),283 },284 {285 Key: []byte("ce_time"),286 Value: []byte(testMsgTime),287 },288 {289 Key: []byte("ce_id"),290 Value: []byte(testMsgId),291 },292 {293 Key: []byte("ce_source"),294 Value: []byte(testMsgSource),295 },296 {297 Key: []byte("ce_type"),298 Value: []byte(testMsgType),299 },300 {301 Key: []byte("ce_eventtypeversion"),302 Value: []byte(testMsgEventTypeVersion),303 },304 {305 Key: []byte("ce_knativehistory"),306 Value: []byte(testMsgKnativeHistory),307 },308 {309 Key: []byte("x-b3-traceid"),310 Value: []byte(testB3TraceId),311 },312 },313 Timestamp: time.Now(),314 BlockTimestamp: time.Time{},315 Key: nil,316 Value: []byte(testMsgJsonContentString),317 Topic: testTopic,318 Partition: testPartition,319 Offset: testOffset,320 }321 // Quick Run Through Of CloudEvents SDK Binding Message Conversion To Ensure Validity322 assert.Equal(t, binding.EncodingBinary, kafkasaramaprotocol.NewMessageFromConsumerMessage(consumerMessage).ReadEncoding())323 // Return The Test ConsumerMessage324 return consumerMessage325}326func Test_executionInfoWrapper(t *testing.T) {327 for _, testCase := range []struct {328 name string329 info *channel.DispatchExecutionInfo330 want string331 }{332 {333 name: "Empty Info",334 info: &channel.DispatchExecutionInfo{},335 want: `"Time":0,"ResponseCode":0,"Body":""`,336 },337 {338 name: "Short Body",339 info: &channel.DispatchExecutionInfo{340 Time: 123 * time.Microsecond,341 ResponseCode: 200,342 ResponseBody: []byte("shortBody"),343 },344 want: `"Time":123000,"ResponseCode":200,"Body":"shortBody"`,345 },346 {347 name: "Long Body (max length)",348 info: &channel.DispatchExecutionInfo{349 Time: 1234 * time.Microsecond,350 ResponseCode: 500,351 ResponseBody: []byte(strings.Repeat("tencharstr", 50)),352 },353 want: `"Time":1234000,"ResponseCode":500,"Body":"` + strings.Repeat("tencharstr", 50) + `"`,354 },355 {356 name: "Long Body (truncated)",357 info: &channel.DispatchExecutionInfo{358 Time: 12345 * time.Microsecond,359 ResponseCode: 500,360 ResponseBody: []byte(strings.Repeat("tencharstr", 51)),361 },362 want: `"Time":12345000,"ResponseCode":500,"Body":"` + strings.Repeat("tencharstr", 50) + `..."`,363 },364 } {365 t.Run(testCase.name, func(t *testing.T) {366 zapField := zap.Any("test", executionInfoWrapper{testCase.info})367 buffer, err := zapcore.NewJSONEncoder(zapcore.EncoderConfig{}).EncodeEntry(zapcore.Entry{}, []zapcore.Field{zapField})368 assert.Nil(t, err)369 // The buffer contains more than just the encoded field, but this isn't supposed to be testing "the zapcore library"370 // so just see if the JSON string has what we're expecting in the middle of it371 assert.Contains(t, buffer.String(), testCase.want)372 })373 }374}...

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("hello")4 v1.CreateTestHandler()5}6import (7func main() {8 fmt.Println("hello")9 v2.CreateTestHandler()10}11import (12func main() {13 fmt.Println("hello")14 v3.CreateTestHandler()15}16import (17func main() {18 fmt.Println("hello")19 v4.CreateTestHandler()20}21import (22func main() {23 fmt.Println("hello")24 v5.CreateTestHandler()25}26import (27func main() {28 fmt.Println("hello")29 v6.CreateTestHandler()30}31import (32func main() {33 fmt.Println("hello")34 v7.CreateTestHandler()35}36import (37func main() {38 fmt.Println("hello")39 v8.CreateTestHandler()40}41import (42func main() {43 fmt.Println("hello")44 v9.CreateTestHandler()45}46import (47func main() {48 fmt.Println("hello")49 v10.CreateTestHandler()50}

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 http.HandleFunc("/hello", v1.CreateTestHandler())5 http.ListenAndServe(":8080", nil)6}7import (8func main() {9 fmt.Println("Hello World")10 http.HandleFunc("/hello", v1.CreateTestHandler())11 http.ListenAndServe(":8080", nil)12}

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 v1.CreateTestHandler()4 fmt.Println("main method")5}6import "fmt"7func CreateTestHandler() {8 fmt.Println("v1.CreateTestHandler method")9}10import "fmt"11func CreateTestHandler() {12 fmt.Println("v2.CreateTestHandler method")13}14import (15func main() {16 v2.CreateTestHandler()17 fmt.Println("main method")18}19import "fmt"20func CreateTestHandler() {21 fmt.Println("v1.CreateTestHandler method")22}23import "fmt"24func CreateTestHandler() {25 fmt.Println("v2.CreateTestHandler method")26}27import (28func main() {29 v1.CreateTestHandler()30 fmt.Println("main method")31}32import "fmt"33func CreateTestHandler() {34 fmt.Println("v1.CreateTestHandler method")35}36import "fmt"37func CreateTestHandler() {38 fmt.Println("v2.CreateTestHandler method")39}

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.HandleFunc("/test", v1.CreateTestHandler())4 http.ListenAndServe(":8080", nil)5}6import (7func CreateTestHandler() http.HandlerFunc {8 return func(w http.ResponseWriter, r *http.Request) {9 fmt.Fprintf(w, "Test")10 }11}12type User struct {13}14func (u *User) GetUserName() string {15}16import "fmt"17type myFunc func(string) string18func main() {19 f := myFunc(func(s string) string {20 })21 fmt.Println(f("Hello"))22}23cannot use func literal (type func(string) string) as type myFunc in assignment24import "fmt"25type myFunc func(string) string26func main() {27 f := myFunc(func(s string) string {

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println(stringutil.Reverse("Hello, world."))4 fmt.Println(v1.Reverse("Hello, world."))5 fmt.Println(v2.Reverse("Hello, world."))6 fmt.Println(v2.CreateTestHandler())7}

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("2.go")4 v1.CreateTestHandler()5}6import (7func main() {8 fmt.Println("3.go")9 v2.CreateTestHandler()10}11import (12func main() {13 fmt.Println("4.go")14 v1.CreateTestHandler()15}16type SomeStruct struct {17}18func (s *SomeStruct) GetName() string {19}20import (21func main() {22 fmt.Println(s.GetName())23}

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 handler := v1.CreateTestHandler()4 fmt.Println(handler)5}6&{1}7import (8func main() {9 handler := v1.CreateTestHandler()10 fmt.Println(handler)11}12import (13func main() {14 handler := v1.CreateTestHandler()15 fmt.Println(handler)16}17&{1}18import (19func main() {20 data := []byte("hello world")21 err := ioutil.WriteFile("/tmp/data.txt", data, 0644)22 if err != nil {23 panic(err)24 }25 fmt.Println("File created")26}

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 v1 := PackageDemo1.NewVersion1()4 v1.CreateTestHandler()5 fmt.Println("Hello World!")6}7import (

Full Screen

Full Screen

CreateTestHandler

Using AI Code Generation

copy

Full Screen

1import "fmt"2import "github.com/venkyvb/GoLangTest/v1"3func main() {4 fmt.Println("In main")5 v1.CreateTestHandler()6}7import "fmt"8import "github.com/venkyvb/GoLangTest/v2"9func main() {10 fmt.Println("In main")11 v2.CreateTestHandler()12}13import "fmt"14func CreateTestHandler() {15 fmt.Println("In v1")16}17import "fmt"18func CreateTestHandler() {19 fmt.Println("In v2")20}

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 Testkube 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