github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/api/util/requests_test.go (about)

     1  package util
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"testing"
     7  )
     8  
     9  func TestRequestParamInt(t *testing.T) {
    10  	cases := []struct {
    11  		value       string
    12  		expect, def int
    13  	}{
    14  		{"", 0, 0},
    15  		{"", 1, 1},
    16  		{"", -1, -1},
    17  		{"-1", -1, 0},
    18  		{"10", 10, 0},
    19  	}
    20  
    21  	for _, c := range cases {
    22  		t.Run(fmt.Sprintf("def_%d_input_%s", c.def, c.value), func(t *testing.T) {
    23  			r, err := http.NewRequest("GET", "https://example.com", nil)
    24  			if err != nil {
    25  				t.Fatal(err)
    26  			}
    27  
    28  			q := r.URL.Query()
    29  			q.Set("key", c.value)
    30  			r.URL.RawQuery = q.Encode()
    31  
    32  			got := ReqParamInt(r, "key", c.def)
    33  
    34  			if c.expect != got {
    35  				t.Errorf("result mismatch. expected: %d got: %d", c.expect, got)
    36  			}
    37  		})
    38  	}
    39  }
    40  
    41  func TestRequestParamBool(t *testing.T) {
    42  	cases := []struct {
    43  		value       string
    44  		expect, def bool
    45  	}{
    46  		{"", false, false},
    47  		{"", true, true},
    48  		{"false", false, true},
    49  		{"true", true, false},
    50  	}
    51  
    52  	for _, c := range cases {
    53  		t.Run(fmt.Sprintf("def_%t_input_%s", c.def, c.value), func(t *testing.T) {
    54  			r, err := http.NewRequest("GET", "https://example.com", nil)
    55  			if err != nil {
    56  				t.Fatal(err)
    57  			}
    58  
    59  			q := r.URL.Query()
    60  			q.Set("key", c.value)
    61  			r.URL.RawQuery = q.Encode()
    62  
    63  			got := ReqParamBool(r, "key", c.def)
    64  
    65  			if c.expect != got {
    66  				t.Errorf("result mismatch. expected: %t got: %t", c.expect, got)
    67  			}
    68  		})
    69  	}
    70  }