Best Testkube code snippet using oauth.GetEndpoint
oauth_integration_test.go
Source:oauth_integration_test.go
1// Copyright © 2018 Camunda Services GmbH (info@camunda.com)2//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.14package test15import (16 "bytes"17 "context"18 "encoding/json"19 "github.com/camunda/zeebe/clients/go/v8/pkg/zbc"20 "github.com/docker/go-connections/nat"21 "github.com/stretchr/testify/suite"22 "github.com/testcontainers/testcontainers-go"23 "github.com/testcontainers/testcontainers-go/wait"24 "io/ioutil"25 "net/http"26 "os"27 "strings"28 "testing"29 "time"30)31var publicPort nat.Port32var adminPort nat.Port33func init() {34 publicPort, _ = nat.NewPort("tcp", "4444")35 adminPort, _ = nat.NewPort("tcp", "4445")36}37type oauthIntegrationTestSuite struct {38 suite.Suite39 container testcontainers.Container40}41func TestOAuthIntegration(t *testing.T) {42 suite.Run(t, &oauthIntegrationTestSuite{})43}44func (s *oauthIntegrationTestSuite) SetupSuite() {45 req := testcontainers.GenericContainerRequest{46 ContainerRequest: testcontainers.ContainerRequest{47 Image: "oryd/hydra:v1.11",48 ExposedPorts: []string{"4444", "4445"},49 Env: map[string]string{"DSN": "memory"},50 WaitingFor: wait.ForAll(wait.ForListeningPort(publicPort), wait.ForListeningPort(adminPort)),51 Cmd: []string{"serve", "all", "--dangerous-force-http"},52 },53 Started: true,54 }55 container, err := testcontainers.GenericContainer(context.Background(), req)56 s.Require().NoError(err)57 s.container = container58 s.ensureOAuthClientExists()59}60func (s *oauthIntegrationTestSuite) TearDownSuite() {61 if s.container != nil {62 _ = s.container.Terminate(context.Background())63 }64}65func (s *oauthIntegrationTestSuite) TestFetchOAuthToken() {66 // given67 headers := make(map[string]string, 1)68 endpoint, err := s.getEndpoint(publicPort, "oauth2/token")69 s.Require().NoError(err)70 file, err := ioutil.TempFile("/tmp", "oauthCredsCache")71 s.Require().NoError(err)72 defer os.Remove(file.Name())73 cache, err := zbc.NewOAuthYamlCredentialsCache(file.Name())74 s.Require().NoError(err)75 credsProvider, err := zbc.NewOAuthCredentialsProvider(&zbc.OAuthProviderConfig{76 ClientID: "zeebe",77 ClientSecret: "secret",78 Audience: "zeebe",79 AuthorizationServerURL: endpoint,80 Cache: cache,81 })82 s.Require().NoError(err)83 // when84 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)85 defer cancel()86 err = credsProvider.ApplyCredentials(ctx, headers)87 s.Require().NoError(err)88 // then89 s.validateToken(headers["Authorization"])90}91func (s *oauthIntegrationTestSuite) validateToken(authHeaderValue string) {92 httpClient := &http.Client{}93 endpoint, err := s.getEndpoint(adminPort, "oauth2/introspect")94 s.Require().NoError(err)95 body := []byte(`token=` + strings.TrimPrefix(authHeaderValue, "Bearer "))96 request, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(body))97 s.Require().NoError(err)98 request.Header.Add("Content-Type", "application/x-www-form-urlencoded")99 request.Header.Add("Accept", "application/json")100 response, err := httpClient.Do(request)101 s.Require().NoError(err)102 defer response.Body.Close()103 s.Require().Equal(response.StatusCode, 200)104 payload := make(map[string]interface{}, 1)105 err = json.NewDecoder(response.Body).Decode(&payload)106 s.Require().NoError(err)107 s.Require().Equal(payload["active"], true)108}109func (s *oauthIntegrationTestSuite) ensureOAuthClientExists() {110 endpoint, err := s.getEndpoint(adminPort, "clients")111 s.Require().NoError(err)112 body := []byte(`{113 "client_id": "zeebe", "client_secret": "secret", "client_name": "zeebe",114 "grant_types": ["client_credentials"], "audience": ["zeebe"], "response_types": ["code"],115 "token_endpoint_auth_method": "client_secret_post"116 }`)117 response, err := http.Post(endpoint, "application/json", bytes.NewBuffer(body))118 s.Require().NoError(err)119 s.Require().Equal(response.StatusCode, 201)120}121func (s *oauthIntegrationTestSuite) getEndpoint(port nat.Port, path string) (string, error) {122 endpoint, err := s.container.PortEndpoint(context.Background(), port, "http")123 if err != nil {124 return "", err125 }126 return endpoint + "/" + path, nil127}...
oauth.go
Source:oauth.go
...44}45type IOAuthProvider interface {46 OAuth(req *Request) (*Response, error)47 Init()48 GetEndpoint(name string) (*Endpoint, error)49 AddEndpoint(name string, endpoint Endpoint)50}51type BaseOAuth struct {52 Http *resty.Client53 Endpoints map[string]Endpoint54}55func (s *BaseOAuth) GetEndpoint(name string) (*Endpoint, error) {56 ep, exist := s.Endpoints[name]57 if !exist {58 return nil, errors.New("Endpoint Not Found ")59 }60 return &ep, nil61}62func (s *BaseOAuth) Init() {63 s.Http = sptty.CreateHttpClient(sptty.DefaultHttpClientConfig())64}65func (s *BaseOAuth) AddEndpoint(name string, endpoint Endpoint) {66 if s.Endpoints == nil {67 s.Endpoints = map[string]Endpoint{}68 }69 s.Endpoints[name] = endpoint70}71func (s *BaseOAuth) PreAuth(req *Request) (*Endpoint, error) {72 if req == nil {73 return nil, errors.New("Request Data Is Nil ")74 }75 endpoint, err := s.GetEndpoint(req.Endpoint)76 if err != nil {77 return nil, err78 }79 return endpoint, nil80}...
service.go
Source:service.go
...60 provider, err := s.getProvider(oauthType)61 if err != nil {62 return nil, err63 }64 return provider.GetEndpoint(endpoint)65}66func (s *Service) setupProviders() {67 s.oauthProviders = map[string]base.IOAuthProvider{68 base.WeChat: &wechat.OAuth{},69 base.WeChatMiniProgram: &wechat.MiniProgram{},70 base.AliPay: &alipay.OAuth{},71 }72}...
GetEndpoint
Using AI Code Generation
1import (2func main() {3 golenv.Load()4 var oauth = golhttp.OAuth{5 ConsumerKey: golenv.OverrideIfEnv("TWITTER_CONSUMER_KEY", ""),6 ConsumerSecret: golenv.OverrideIfEnv("TWITTER_CONSUMER_SECRET", ""),7 CallbackURL: golenv.OverrideIfEnv("TWITTER_CALLBACK_URL", ""),8 }9 fmt.Println(oauth.GetEndpoint())10}11import (12func main() {13 golenv.Load()14 var oauth = golhttp.OAuth{15 ConsumerKey: golenv.OverrideIfEnv("TWITTER_CONSUMER_KEY", ""),16 ConsumerSecret: golenv.OverrideIfEnv("TWITTER_CONSUMER_SECRET", ""),17 CallbackURL: golenv.OverrideIfEnv("TWITTER_CALLBACK_URL", ""),18 }19 fmt.Println(oauth.GetClient())20}21import (22func main() {23 golenv.Load()24 var oauth = golhttp.OAuth{25 ConsumerKey: golenv.OverrideIfEnv("TWITTER_CONSUMER_KEY", ""),26 ConsumerSecret: golenv.OverrideIfEnv("TWITTER_CONSUMER_SECRET", ""),27 CallbackURL: golenv.OverrideIfEnv("TWITTER_CALLBACK_URL", ""),28 }29 fmt.Println(oauth.GetRequestToken())30}31import (32func main() {33 golenv.Load()34 var oauth = golhttp.OAuth{35 ConsumerKey: golenv.OverrideIfEnv("TWITTER_CONSUMER_KEY", ""),36 ConsumerSecret: golenv.OverrideIfEnv("
GetEndpoint
Using AI Code Generation
1import "fmt"2import "github.com/golang/oauth2"3func main() {4 oauth := oauth2.OAuth2{}5 endpoint := oauth.GetEndpoint()6 fmt.Println(endpoint)7}8import "fmt"9import "github.com/golang/oauth2"10func main() {11 oauth := oauth2.OAuth2{}12 token, err := oauth.GetToken()13 if err != nil {14 fmt.Println(err)15 } else {16 fmt.Println(token)17 }18}
GetEndpoint
Using AI Code Generation
1import (2func main() {3 o := oauth.OAuth{}4 endpoint := o.GetEndpoint()5 fmt.Println(endpoint)6}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!