github.com/c3pm-labs/c3pm@v0.3.0/ctpm/login_test.go (about)

     1  package ctpm_test
     2  
     3  import (
     4  	"encoding/json"
     5  	"github.com/c3pm-labs/c3pm/api"
     6  	"github.com/c3pm-labs/c3pm/ctpm"
     7  	. "github.com/onsi/ginkgo"
     8  	. "github.com/onsi/gomega"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"net/http/httptest"
    12  	"os"
    13  	"path"
    14  )
    15  
    16  var _ = Describe("Login", func() {
    17  	c3pmHomeDir := getTestFolder("LoginUserHome")
    18  	testLogin := "demo@demo.com"
    19  	testPassword := "demodemo"
    20  	testApiKey := "demo"
    21  
    22  	It("should login without error", func() {
    23  		server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
    24  			Ω(req.URL.String()).To(Equal("/auth/login"))
    25  			Ω(req.Method).To(Equal(http.MethodPost))
    26  
    27  			type loginPayload struct {
    28  				Login    string `json:"login"`
    29  				Password string `json:"password"`
    30  			}
    31  			want := loginPayload{testLogin, testPassword}
    32  
    33  			var got loginPayload
    34  			body, err := ioutil.ReadAll(req.Body)
    35  			Ω(err).ShouldNot(HaveOccurred())
    36  
    37  			err = json.Unmarshal(body, &got)
    38  			Ω(err).ShouldNot(HaveOccurred())
    39  
    40  			Ω(want).To(Equal(got))
    41  
    42  			res, err := json.Marshal(struct{ ApiKey string }{testApiKey})
    43  			Ω(err).ShouldNot(HaveOccurred())
    44  
    45  			_, err = rw.Write(res)
    46  			Ω(err).ShouldNot(HaveOccurred())
    47  
    48  		}))
    49  		defer server.Close()
    50  		apiClient := api.New(server.Client(), "")
    51  
    52  		err := os.MkdirAll(c3pmHomeDir, os.ModePerm)
    53  		Ω(err).ShouldNot(HaveOccurred())
    54  
    55  		err = os.Setenv("C3PM_USER_DIR", c3pmHomeDir)
    56  		Ω(err).ShouldNot(HaveOccurred())
    57  
    58  		defer os.Unsetenv("C3PM_USER_DIR")
    59  
    60  		err = os.Setenv("C3PM_API_ENDPOINT", server.URL)
    61  		Ω(err).ShouldNot(HaveOccurred())
    62  
    63  		defer os.Unsetenv("C3PM_API_ENDPOINT")
    64  
    65  		err = ctpm.Login(apiClient, testLogin, testPassword)
    66  		Ω(err).ShouldNot(HaveOccurred())
    67  
    68  	})
    69  
    70  	It("should create auth file", func() {
    71  		got, err := ioutil.ReadFile(path.Join(c3pmHomeDir, "auth.cfg"))
    72  		Ω(err).ShouldNot(HaveOccurred())
    73  
    74  		Ω(string(got)).To(Equal(testApiKey))
    75  	})
    76  })