Skip to content

Commit

Permalink
test: add native parse file API test
Browse files Browse the repository at this point in the history
Signed-off-by: peefy <xpf6677@163.com>
  • Loading branch information
Peefy committed Mar 20, 2024
1 parent cf82a2e commit 2420401
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions pkg/native/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
package native

import (
"fmt"
"io"
"path"
"strings"
"testing"
"time"

_ "kcl-lang.io/kcl-go/pkg/plugin/hello_plugin"
"kcl-lang.io/kcl-go/pkg/spec/gpyrpc"
Expand Down Expand Up @@ -79,3 +83,76 @@ func TestExecArtifactWithPlugin(t *testing.T) {
t.Fatal("error message must be empty")
}
}

func TestParseFile(t *testing.T) {
// Example: Test with string source
src := `schema Name:
name: str
n = Name {name = "name"}` // Sample KCL source code
astJson, err := ParseFileASTJson("", src)
if err != nil {
t.Errorf("ParseFileASTJson failed with string source: %v", err)
}
if astJson == "" {
t.Errorf("Expected non-empty AST JSON with string source")
}

// Example: Test with byte slice source
srcBytes := []byte(src)
astJson, err = ParseFileASTJson("", srcBytes)
if err != nil {
t.Errorf("ParseFileASTJson failed with byte slice source: %v", err)
}
if astJson == "" {
t.Errorf("Expected non-empty AST JSON with byte slice source")
}

startTime := time.Now()
// Example: Test with io.Reader source
srcReader := strings.NewReader(src)
astJson, err = ParseFileASTJson("", srcReader)
if err != nil {
t.Errorf("ParseFileASTJson failed with io.Reader source: %v", err)
}
if astJson == "" {
t.Errorf("Expected non-empty AST JSON with io.Reader source")
}
elapsed := time.Since(startTime)
t.Logf("ParseFileASTJson took %s", elapsed)
if !strings.Contains(astJson, "Schema") {
t.Errorf("Expected Schema Node AST JSON with io.Reader source")
}
if !strings.Contains(astJson, "Assign") {
t.Errorf("Expected Assign Node AST JSON with io.Reader source")
}
}

func ParseFileASTJson(filename string, src interface{}) (result string, err error) {
var code string
if src != nil {
switch src := src.(type) {
case []byte:
code = string(src)
case string:
code = string(src)
case io.Reader:
d, err := io.ReadAll(src)
if err != nil {
return "", err
}
code = string(d)
default:
return "", fmt.Errorf("unsupported src type: %T", src)
}
}
client := NewNativeServiceClient()
resp, err := client.ParseFile(&gpyrpc.ParseFile_Args{
Path: filename,
Source: code,
})
if err != nil {
return "", err
}
return resp.AstJson, nil
}

0 comments on commit 2420401

Please sign in to comment.