Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Go Test

on:
push:

jobs:
test:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17

- name: Install Dependencies
run: |
go mod download

- name: Run Tests
run: go test ./...
27 changes: 27 additions & 0 deletions cmd/testdata/config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
gitdiff:
url: "${TEST_SERVER_URL}/v1/chat/completions"
header:
- "Content-Type: application/json"
- "Authorization: Bearer ${TEST_API_KEY}"
data:
model: "gpt-3.5-turbo"
messages:
- role: "user"
content: "Hello"
output: "choices[0].message.content"
env:
- "TEST_API_KEY"
- "TEST_SERVER_URL"
translate:
url: "${TEST_SERVER_URL}/v2/translate"
header:
- "Content-Type: application/json"
- "Authorization: DeepL-Auth-Key ${TEST_API_KEY}"
data:
text:
- "Apple"
target_lang: "FR"
output: "translations[0].text"
env:
- "TEST_API_KEY"
- "TEST_SERVER_URL"
24 changes: 9 additions & 15 deletions cmd/tpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,16 @@ func tplCommand(cmd *cobra.Command, args []string) {
if !ok {
panic("No config found for function: " + args[0])
}

fc.handleFunc()
fmt.Fprintf(cmd.OutOrStdout(), fc.handleFunc())
}

func (fc *FunctionConfig) handleFunc() {
func (fc *FunctionConfig) handleFunc() string {
jsonData := fc.getJSONData()

req, err := http.NewRequest("POST", fc.Url, bytes.NewBuffer(jsonData))
req, err := http.NewRequest("POST", fc.replaceEnvVariables(fc.Url), bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Failed to create request:", err)
return
panic("Failed to create request: " + err.Error())
}

for _, header := range fc.Header {
Expand All @@ -71,22 +70,18 @@ func (fc *FunctionConfig) handleFunc() {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Failed to send request:", err)
return
panic("Failed to send request: " + err.Error())
}
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Failed to read response body:", err)
return
panic("Failed to read response body: " + err.Error())
}
defer resp.Body.Close()

// Check if the request was successful
if resp.StatusCode != http.StatusOK {
fmt.Println("Request failed with status:", resp.Status)
fmt.Println("Response body:", string(body))
return
panic("Request failed, Status: " + resp.Status + ", Body: " + string(body))
}

// Parse the JSON response
Expand All @@ -96,8 +91,7 @@ func (fc *FunctionConfig) handleFunc() {
}

// Extract the desired output from the JSON response
output := util.GetOutputField(responseData, fc.Output)
fmt.Print(output)
return util.GetOutputField(responseData, fc.Output)
}

func (fc *FunctionConfig) getJSONData() []byte {
Expand Down
77 changes: 77 additions & 0 deletions cmd/tpl_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package cmd

import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"testing"

)

var testServer *httptest.Server

func TestMain(m *testing.M) {
testServer = startTestHTTPServer()
exitCode := m.Run()
testServer.Close()
os.Exit(exitCode)
}

func startTestHTTPServer() *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/v1/chat/completions":
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
}

var data ChatGptPayload
err = json.Unmarshal(body, &data)
if err != nil {
http.Error(w, "Bad Request", http.StatusBadRequest)
}

w.Write([]byte(`{"choices": [{"message": {"content": "` + data.Messages[0].Content + `"}}]}`))
case "/v2/translate":
w.Write([]byte(`{"translations": [{"text": "Pomme"}]}`))
default:
http.Error(w, "Not found", http.StatusNotFound)
}
}))
os.Setenv("TEST_SERVER_URL", server.URL)
return server
}

func TestGitDiff(t *testing.T) {
b := bytes.NewBufferString("")
rootCmd.SetOut(b)
rootCmd.SetArgs([]string{"gitdiff", "--config", "./testdata/config.yaml"})
rootCmd.Execute()
out, err := ioutil.ReadAll(b)
if err != nil {
t.Fatal(err)
}
expected := "Hello"
if string(out) != expected {
t.Fatalf("expected \"%s\" got \"%s\"", expected, string(out))
}
}

func TestTranslate(t *testing.T) {
b := bytes.NewBufferString("")
rootCmd.SetOut(b)
rootCmd.SetArgs([]string{"translate", "--config", "./testdata/config.yaml"})
rootCmd.Execute()
out, err := ioutil.ReadAll(b)
if err != nil {
t.Fatal(err)
}
expected := "Pomme"
if string(out) != expected {
t.Fatalf("expected \"%s\" got \"%s\"", expected, string(out))
}
}
11 changes: 11 additions & 0 deletions cmd/tpl_test_structs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package cmd

type GptMessage struct {
Role string `json:"role"`
Content string `json:"content"`
}

type ChatGptPayload struct {
Model string `json:"model"`
Messages []GptMessage `json:"messages"`
}
12 changes: 12 additions & 0 deletions util/handleError.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package util

import (
"fmt"
"os"
)

func HandleError(err error, msg string) {
// fmt.Println(err)
fmt.Println(msg)
os.Exit(1)
}