Skip to content

Commit

Permalink
Add end-to-end tests for json subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
keynmol committed May 2, 2023
1 parent 796df20 commit aece669
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 3 deletions.
7 changes: 4 additions & 3 deletions cmd/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"fmt"
"io"

"github.com/sourcegraph/sourcegraph/lib/errors"
"github.com/urfave/cli/v2"
Expand Down Expand Up @@ -32,14 +33,14 @@ func jsonCommand() cli.Command {
if jsonFlags.from == "" {
return errors.New("missing argument for path to SCIP index")
}
return jsonMain(jsonFlags)
return jsonMain(jsonFlags, c.App.Writer)
},
}

return json
}

func jsonMain(flags jsonFlags) error {
func jsonMain(flags jsonFlags, out io.Writer) error {

fmt.Println(flags)

Expand All @@ -53,7 +54,7 @@ func jsonMain(flags jsonFlags) error {
}

jsonBytes, _ := options.Marshal(scipIndex)
fmt.Println(string(jsonBytes))
out.Write(jsonBytes)

return nil
}
69 changes: 69 additions & 0 deletions cmd/json_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package main

import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"log"
"os"
"testing"

"github.com/sourcegraph/scip/bindings/go/scip"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
)

func TestJSONCommand(t *testing.T) {
app := scipApp()
// Redirect CLI writer to a buffer
var buff bytes.Buffer
app.Writer = io.Writer(&buff)
idx := makeIndex([]string{"a"}, stringMap{"f": {"b"}}, stringMap{"f": {"a", "b"}})

idx.Metadata = &scip.Metadata{ProjectRoot: "howdy"}

// Serialise SCIP index
indexBytes, err := proto.Marshal(idx)

// Write SCIP index to a temp file
dir := os.TempDir()
file, err := ioutil.TempFile(dir, "scip-cli-json-test*.scip")
if err != nil {
log.Fatal(err)
}
defer os.Remove(file.Name())

_, fErr := file.Write(indexBytes)
if fErr != nil {
log.Fatal(fErr)
}

// Run the JSON command with the temporary file
runErr := app.Run([]string{"scip", "json", "--from", file.Name()})
if runErr != nil {
log.Fatal(runErr)
}

type JsonIndex struct {
Metadata struct {
ProjectRoot string `json:"projectRoot"`
}
Documents []struct {
RelativePath string `json:"relativePath"`
} `json:"documents"`
}

var roundtripResult JsonIndex

bytes := buff.Bytes()

jsonErr := json.Unmarshal(bytes, &roundtripResult)
if jsonErr != nil {
log.Fatal(jsonErr)
}

require.Equal(t, roundtripResult.Metadata.ProjectRoot, "howdy")
require.Equal(t, len(roundtripResult.Documents), 1)
require.Equal(t, roundtripResult.Documents[0].RelativePath, "f")
}

0 comments on commit aece669

Please sign in to comment.