knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/websocket/hijack_test.go (about)

     1  /*
     2  Copyright 2019 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package websocket
    18  
    19  import (
    20  	"bufio"
    21  	"bytes"
    22  	"net"
    23  	"net/http"
    24  	"testing"
    25  )
    26  
    27  // hijackable is a http.ResponseWriter that implements http.Hijacker
    28  type hijackable struct {
    29  	http.ResponseWriter
    30  	w *bufio.ReadWriter
    31  }
    32  
    33  // Hijack implements http.Hijacker
    34  func (h *hijackable) Hijack() (net.Conn, *bufio.ReadWriter, error) {
    35  	return nil, h.w, nil
    36  }
    37  
    38  func newHijackable() *hijackable {
    39  	var b *bytes.Buffer
    40  	return &hijackable{
    41  		w: bufio.NewReadWriter(bufio.NewReader(b), bufio.NewWriter(b)),
    42  	}
    43  }
    44  
    45  type notHijackable struct {
    46  	http.ResponseWriter
    47  }
    48  
    49  func TestHijackIfPossible(t *testing.T) {
    50  	h := newHijackable()
    51  	for _, test := range []struct {
    52  		name           string
    53  		w              http.ResponseWriter
    54  		wantErr        bool
    55  		wantReadWriter *bufio.ReadWriter
    56  	}{{
    57  		name:           "Hijacker type",
    58  		w:              h,
    59  		wantErr:        false,
    60  		wantReadWriter: h.w,
    61  	}, {
    62  		name:           "non-Hijacker type",
    63  		w:              &notHijackable{},
    64  		wantErr:        true,
    65  		wantReadWriter: nil,
    66  	}} {
    67  		t.Run(test.name, func(t *testing.T) {
    68  			_, w, err := HijackIfPossible(test.w)
    69  			if test.wantErr == (err == nil) {
    70  				t.Errorf("wantErr=%v, but got err=%v", test.wantErr, err)
    71  			}
    72  			if test.wantReadWriter != w {
    73  				t.Errorf("Wanted ReadWriter %v got %v", test.wantReadWriter, w)
    74  			}
    75  		})
    76  	}
    77  }