Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: add native parse file API test #262

Merged
merged 1 commit into from
Mar 20, 2024
Merged
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
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
}
Loading