Best Syzkaller code snippet using vmware.Forward
api_test.go
Source:api_test.go
...12 "github.com/stretchr/testify/assert"13 "github.com/stretchr/testify/require"14 "github.com/vmware-tanzu/octant/internal/gvk"15 "github.com/vmware-tanzu/octant/internal/portforward"16 portForwardFake "github.com/vmware-tanzu/octant/internal/portforward/fake"17 "github.com/vmware-tanzu/octant/internal/testutil"18 "github.com/vmware-tanzu/octant/pkg/plugin/api"19 "github.com/vmware-tanzu/octant/pkg/store"20 storeFake "github.com/vmware-tanzu/octant/pkg/store/fake"21)22type apiMocks struct {23 objectStore *storeFake.MockStore24 pf *portForwardFake.MockPortForwarder25}26func TestAPI(t *testing.T) {27 listKey := store.Key{28 Namespace: "default",29 APIVersion: "apps/v1",30 Kind: "Deployment",31 }32 objects := testutil.ToUnstructuredList(t,33 testutil.CreateDeployment("deployment"),34 )35 getKey := store.Key{36 Namespace: "default",37 APIVersion: "apps/v1",38 Kind: "Deployment",39 Name: "deployment",40 }41 object := testutil.ToUnstructured(t, testutil.CreateDeployment("deployment"))42 pfRequest := api.PortForwardRequest{43 Namespace: "default",44 PodName: "pod",45 Port: uint16(8080),46 }47 pfResponse := api.PortForwardResponse{48 ID: "12345",49 Port: uint16(54321),50 }51 cases := []struct {52 name string53 initFunc func(t *testing.T, mocks *apiMocks)54 doFunc func(t *testing.T, client *api.Client)55 }{56 {57 name: "list",58 initFunc: func(t *testing.T, mocks *apiMocks) {59 mocks.objectStore.EXPECT().60 List(gomock.Any(), gomock.Eq(listKey)).Return(objects, false, nil)61 },62 doFunc: func(t *testing.T, client *api.Client) {63 clientCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second)64 defer cancel()65 got, err := client.List(clientCtx, listKey)66 require.NoError(t, err)67 expected := objects68 assert.Equal(t, expected, got)69 },70 },71 {72 name: "get",73 initFunc: func(t *testing.T, mocks *apiMocks) {74 mocks.objectStore.EXPECT().75 Get(gomock.Any(), gomock.Eq(getKey)).Return(object, true, nil)76 },77 doFunc: func(t *testing.T, client *api.Client) {78 clientCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second)79 defer cancel()80 got, found, err := client.Get(clientCtx, getKey)81 require.NoError(t, err)82 require.True(t, found)83 expected := object84 assert.Equal(t, expected, got)85 },86 },87 {88 name: "port forward",89 initFunc: func(t *testing.T, mocks *apiMocks) {90 resp := portforward.CreateResponse{91 ID: "12345",92 Ports: []portforward.PortForwardPortSpec{93 {Local: uint16(54321)},94 },95 }96 mocks.pf.EXPECT().97 Create(98 gomock.Any(), gvk.Pod, "pod", "default", uint16(8080)).99 Return(resp, nil)100 },101 doFunc: func(t *testing.T, client *api.Client) {102 clientCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second)103 defer cancel()104 got, err := client.PortForward(clientCtx, pfRequest)105 require.NoError(t, err)106 expected := pfResponse107 assert.Equal(t, expected, got)108 },109 },110 {111 name: "port forward cancel",112 initFunc: func(t *testing.T, mocks *apiMocks) {113 mocks.pf.EXPECT().114 StopForwarder("12345")115 },116 doFunc: func(t *testing.T, client *api.Client) {117 clientCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second)118 defer cancel()119 client.CancelPortForward(clientCtx, "12345")120 },121 },122 {123 name: "port forward",124 initFunc: func(t *testing.T, mocks *apiMocks) {125 resp := portforward.CreateResponse{126 ID: "12345",127 Ports: []portforward.PortForwardPortSpec{128 {Local: uint16(54321)},129 },130 }131 mocks.pf.EXPECT().132 Create(133 gomock.Any(), gvk.Pod, "pod", "default", uint16(8080)).134 Return(resp, nil)135 },136 doFunc: func(t *testing.T, client *api.Client) {137 clientCtx, cancel := context.WithTimeout(context.Background(), 1*time.Second)138 defer cancel()139 got, err := client.PortForward(clientCtx, pfRequest)140 require.NoError(t, err)141 expected := pfResponse142 assert.Equal(t, expected, got)143 },144 },145 }146 for _, tc := range cases {147 t.Run(tc.name, func(t *testing.T) {148 controller := gomock.NewController(t)149 defer controller.Finish()150 appObjectStore := storeFake.NewMockStore(controller)151 pf := portForwardFake.NewMockPortForwarder(controller)152 tc.initFunc(t, &apiMocks{153 objectStore: appObjectStore,154 pf: pf})155 service := &api.GRPCService{156 ObjectStore: appObjectStore,157 PortForwarder: pf,158 }159 a, err := api.New(service)160 require.NoError(t, err)161 ctx := context.Background()162 err = a.Start(ctx)163 require.NoError(t, err)164 checkPort(t, true, a.Addr())165 client, err := api.NewClient(a.Addr())166 require.NoError(t, err)167 tc.doFunc(t, client)168 })169 }170}171func checkPort(t *testing.T, isListen bool, addr string) {...
client.go
Source:client.go
...101 }102 _, err = client.Update(ctx, req)103 return err104}105// PortForward creates a port forward.106func (c *Client) PortForward(ctx context.Context, req PortForwardRequest) (PortForwardResponse, error) {107 client := c.DashboardConnection.Client()108 pfRequest := &proto.PortForwardRequest{109 Namespace: req.Namespace,110 PodName: req.PodName,111 PortNumber: uint32(req.Port),112 }113 resp, err := client.PortForward(ctx, pfRequest)114 if err != nil {115 return PortForwardResponse{}, err116 }117 return PortForwardResponse{118 ID: resp.PortForwardID,119 Port: uint16(resp.PortNumber),120 }, nil121}122// CancelPortForward cancels a port forward.123func (c *Client) CancelPortForward(ctx context.Context, id string) {124 client := c.DashboardConnection.Client()125 req := &proto.CancelPortForwardRequest{126 PortForwardID: id,127 }128 _, err := client.CancelPortForward(ctx, req)129 if err != nil {130 logger := log.From(ctx)131 logger.Errorf("unable to cancel port forward: %v", err)132 }133}134// ForceFrontendUpdate forces the frontend to update itself.135func (c *Client) ForceFrontendUpdate(ctx context.Context) error {136 client := c.DashboardConnection.Client()137 _, err := client.ForceFrontendUpdate(ctx, &proto.Empty{})138 return err139}...
portforward.go
Source:portforward.go
...15 "github.com/vmware-tanzu/octant/internal/mime"16 "github.com/vmware-tanzu/octant/internal/portforward"17 "github.com/vmware-tanzu/octant/pkg/log"18)19type portForwardCreateRequest struct {20 APIVersion string `json:"apiVersion,omitempty"`21 Kind string `json:"kind,omitempty"`22 Type string `json:"type,omitempty"`23 Name string `json:"name,omitempty"`24 Namespace string `json:"namespace,omitempty"`25 Port uint16 `json:"port,omitempty"`26}27func (req *portForwardCreateRequest) Validate() error {28 if req.APIVersion != "v1" && req.Kind == "Pod" {29 return errors.New("only supports forwards for v1 Pods")30 }31 if req.Name == "" {32 return errors.New("pod name is blank")33 }34 if req.Namespace == "" {35 return errors.New("pod namespace is blank")36 }37 if req.Port < 1 {38 return errors.New("port must be greater than 0")39 }40 return nil41}42func (req *portForwardCreateRequest) gvk() schema.GroupVersionKind {43 return schema.FromAPIVersionAndKind(req.APIVersion, req.Kind)44}45type portForwardError struct {46 code int47 message string48 extraErr error49}50var _ error = (*portForwardError)(nil)51func (e *portForwardError) Error() string {52 return e.message53}54func createPortForward(ctx context.Context, body io.Reader, pfs portforward.PortForwarder, w http.ResponseWriter) error {55 if pfs == nil {56 return errors.New("port forward service is nil")57 }58 logger := internalLog.From(ctx)59 req := portForwardCreateRequest{}60 if err := json.NewDecoder(body).Decode(&req); err != nil {61 return &portForwardError{code: http.StatusBadRequest, message: "unable to decode request"}62 }63 if err := req.Validate(); err != nil {64 return &portForwardError{65 code: http.StatusBadRequest,66 message: "request is invalid",67 extraErr: err,68 }69 }70 resp, err := pfs.Create(ctx, nil, req.gvk(), req.Name, req.Namespace, req.Port)71 if err != nil {72 return &portForwardError{73 code: http.StatusInternalServerError,74 message: "create port forward",75 extraErr: err,76 }77 }78 w.Header().Set("Content-Type", mime.JSONContentType)79 w.WriteHeader(http.StatusOK)80 if err := json.NewEncoder(w).Encode(resp); err != nil {81 logger.With("err", err.Error()).Errorf("encoding JSON response")82 }83 return nil84}85func deletePortForward(_ context.Context, id string, pfs portforward.PortForwarder, w http.ResponseWriter) error {86 if pfs == nil {87 return errors.New("port forward service is nil")88 }89 pfs.StopForwarder(id)90 w.WriteHeader(http.StatusNoContent)91 return nil92}93func handlePortForwardError(w http.ResponseWriter, err error, logger log.Logger) {94 if err == nil {95 return96 }97 code := http.StatusInternalServerError98 message := err.Error()99 if cause, ok := errors.Cause(err).(*portForwardError); ok {100 code = cause.code101 message = cause.message102 }103 api.RespondWithError(w, code, message, logger)104}...
Forward
Using AI Code Generation
1import (2func main() {3 ctx, cancel := context.WithCancel(context.Background())4 defer cancel()5 if err != nil {6 fmt.Println(err)7 os.Exit(1)8 }9 u.User = url.UserPassword("username", "password")10 c, err := govmomi.NewClient(ctx, u, true)11 if err != nil {12 fmt.Println(err)13 os.Exit(1)14 }15 f := find.NewFinder(c.Client, true)16 dc, err := f.DefaultDatacenter(ctx)17 if err != nil {18 fmt.Println(err)19 os.Exit(1)20 }21 f.SetDatacenter(dc)22 vm, err := f.VirtualMachine(ctx, "vmname")23 if err != nil {24 fmt.Println(err)25 os.Exit(1)26 }27 devices, err := vm.Device(ctx)28 if err != nil {29 fmt.Println(err)30 os.Exit(1)31 }32 for _, d := range devices {33 if d.GetVirtualDevice().DeviceInfo.GetDescription().Label == "Network adapter 1" {34 }35 }36 if device == nil {37 fmt.Println("device not found")38 os.Exit(1)39 }40 devices = object.VirtualDeviceList{device}.SelectByBackingInfo((*types.VirtualEthernetCardNetworkBackingInfo)(nil))41 if len(devices) == 0 {42 fmt.Println("devices not found")43 os.Exit(1)44 }45 for _, device := range devices {46 backing := device.GetVirtualDevice().Backing.(*types.VirtualEthernetCardNetworkBackingInfo)47 deviceChange = append(deviceChange, &types.VirtualDeviceConfigSpec{48 })49 }50 spec := types.VirtualMachineConfigSpec{DeviceChange: deviceChange}
Forward
Using AI Code Generation
1import (2func main() {3 ctx, cancel := context.WithCancel(context.Background())4 defer cancel()5 u, err := url.Parse(os.Args[1])6 if err != nil {7 fmt.Println(err)8 }9 finder := find.NewFinder(u.Client, true)10 dc, err := finder.DefaultDatacenter(ctx)11 if err != nil {12 fmt.Println(err)13 }14 finder.SetDatacenter(dc)15 vm, err := finder.VirtualMachine(ctx, os.Args[2])16 if err != nil {17 fmt.Println(err)18 }19 vmRef.Value = vm.Reference().Value20 task, err := vm.PowerOn(ctx)21 if err != nil {22 fmt.Println(err)23 }24 info, err := task.WaitForResult(ctx, nil)25 if err != nil {26 fmt.Println(err)27 }28 fmt.Printf("%s: %s29 task, err = vm.PowerOff(ctx)30 if err != nil {31 fmt.Println(err)32 }33 info, err = task.WaitForResult(ctx, nil)34 if err != nil {35 fmt.Println(err)36 }37 fmt.Printf("%s: %s38 task, err = vm.Suspend(ctx)39 if err != nil {40 fmt.Println(err)41 }42 info, err = task.WaitForResult(ctx, nil)43 if err != nil {44 fmt.Println(err)45 }46 fmt.Printf("%s: %s47 task, err = vm.Reset(ctx)48 if err != nil {49 fmt.Println(err)50 }51 info, err = task.WaitForResult(ctx, nil)52 if err != nil {53 fmt.Println(err)54 }55 fmt.Printf("%s: %s
Forward
Using AI Code Generation
1import "fmt"2import "vmware"3func main() {4 v.Forward()5 v.Reverse()6 v.Forward()7 v.Reverse()8}9import "fmt"10import "vmware"11func main() {12 v.Forward()13 v.Reverse()14 v.Forward()15 v.Reverse()16}17import "fmt"18import "vmware"19func main() {20 v.Forward()21 v.Reverse()22 v.Forward()23 v.Reverse()24}25import "fmt"26import "vmware"27func main() {28 v.Forward()29 v.Reverse()30 v.Forward()31 v.Reverse()32}33import "fmt"34import "vmware"35func main() {36 v.Forward()37 v.Reverse()38 v.Forward()39 v.Reverse()40}41import "fmt"42import "vmware"43func main() {44 v.Forward()45 v.Reverse()46 v.Forward()47 v.Reverse()48}49import "fmt"50import "vmware"51func main() {52 v.Forward()53 v.Reverse()54 v.Forward()55 v.Reverse()56}57import "fmt"58import "vmware"59func main() {60 v.Forward()61 v.Reverse()62 v.Forward()63 v.Reverse()64}65import "fmt"66import "vmware"67func main() {68 v.Forward()69 v.Reverse()70 v.Forward()71 v.Reverse()72}
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!!