文章同步發佈於https://kevinyay945.com/ironman2022/day28
目前建立好了Get的功能,所以就可以開始測試取得PCloud的功能了
package pcloud
import (
"github.com/joho/godotenv"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
"os")
type IClient interface {
SetAccessToken(s string)
CheckAuthorization() (err error)
}
var _ = Describe("PCloud", func() {
BeforeEach(func() {
err := godotenv.Load("../../.env.development")
Expect(err).ShouldNot(HaveOccurred())
})
When("Check Auth", func() {
var PCloud IClient
BeforeEach(func() {
PCloud = NewClient()
})
It("Success", func() {
PCloud.SetAccessToken(os.Getenv("PCLOUD_ACCESS_TOKEN"))
err := PCloud.CheckAuthorization()
Expect(err).ShouldNot(HaveOccurred())
})
It("Fail", func() {
err := PCloud.CheckAuthorization()
Expect(err).Should(HaveOccurred())
})
})
})
type Client struct {
}
func (c *Client) SetAccessToken(s string) {
}
func (c *Client) CheckAuthorization() (err error) {
return nil
}
func NewClient() IClient {
return &Client{}
}
完成這段內容後,可以發現,Success的案例是會過的,所以我們才增加Fail的案例來讓我們要強迫去改動實際程式碼
接著,就來將下方的Client需要的code做一定的更新
type Client struct {
accessToken string
httpClient httpClient.IHttpClient
}
func (c *Client) SetAccessToken(s string) {
c.accessToken = s
c.httpClient.SetAuthToken(s)
}
func (c *Client) CheckAuthorization() (err error) {
resp, err := c.httpClient.Get("https://api.pcloud.com/userinfo")
if err != nil {
return err
}
result := new(struct {
Result int `json:"result"`
Error string `json:"error"`
})
err = json.Unmarshal(resp.Body, &result)
if err != nil {
return err
}
if result.Result != 0 {
return errors.New(result.Error)
}
return
}
func NewClient() IClient {
httpClient := httpClient.NewHttpClient()
return &Client{
httpClient: httpClient,
}
}
如此就可以將上方的測試都通過了