github.com/decred/politeia@v1.4.0/politeiawww/legacy/www_test.go (about)

     1  // Copyright (c) 2017-2020 The Decred developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package legacy
     6  
     7  import (
     8  	"encoding/hex"
     9  	"encoding/json"
    10  	"io"
    11  	"net/http"
    12  	"net/http/httptest"
    13  	"testing"
    14  
    15  	"github.com/davecgh/go-spew/spew"
    16  	www "github.com/decred/politeia/politeiawww/api/www/v1"
    17  	"github.com/go-test/deep"
    18  )
    19  
    20  func TestHandleVersion(t *testing.T) {
    21  	p, cleanup := newTestPoliteiawww(t)
    22  	defer cleanup()
    23  
    24  	expectedReply := www.VersionReply{
    25  		Version:      www.PoliteiaWWWAPIVersion,
    26  		BuildVersion: p.cfg.Version,
    27  		Route:        www.PoliteiaWWWAPIRoute,
    28  		PubKey:       hex.EncodeToString(p.cfg.Identity.Key[:]),
    29  		TestNet:      p.cfg.TestNet,
    30  	}
    31  
    32  	var tests = []struct {
    33  		name       string
    34  		wantReply  www.VersionReply
    35  		wantStatus int
    36  		wantError  error
    37  	}{
    38  		{
    39  			"success",
    40  			expectedReply,
    41  			http.StatusOK,
    42  			nil,
    43  		},
    44  	}
    45  
    46  	for _, v := range tests {
    47  		t.Run(v.name, func(t *testing.T) {
    48  			// Setup request
    49  			r := httptest.NewRequest(http.MethodGet, www.RouteVersion, nil)
    50  			w := httptest.NewRecorder()
    51  
    52  			// Run test case
    53  			p.handleVersion(w, r)
    54  			res := w.Result()
    55  			body, _ := io.ReadAll(res.Body)
    56  			res.Body.Close()
    57  
    58  			// Unmarshal body response
    59  			var gotReply www.VersionReply
    60  			err := json.Unmarshal(body, &gotReply)
    61  			if err != nil {
    62  				t.Errorf("unmarshal error with body %v", body)
    63  			}
    64  
    65  			// Validate response status
    66  			if res.StatusCode != v.wantStatus {
    67  				t.Errorf("got status code %v, want %v",
    68  					res.StatusCode, v.wantStatus)
    69  			}
    70  
    71  			// Validate response body
    72  			diff := deep.Equal(gotReply, v.wantReply)
    73  			if diff != nil {
    74  				t.Errorf("VersionReply got/want diff:\n%v",
    75  					spew.Sdump(diff))
    76  			}
    77  		})
    78  	}
    79  }