Skip to content

Commit

Permalink
test: added tests
Browse files Browse the repository at this point in the history
  • Loading branch information
szkiba committed Jul 8, 2024
1 parent ceed3c0 commit 35ff928
Show file tree
Hide file tree
Showing 8 changed files with 513 additions and 0 deletions.
233 changes: 233 additions & 0 deletions build_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,233 @@
package k6exec

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"

"github.com/grafana/k6build"
"github.com/grafana/k6deps"
"github.com/stretchr/testify/require"
)

func Test_depsConvert(t *testing.T) {
t.Parallel()

src := make(k6deps.Dependencies)

err := src.UnmarshalText([]byte("k6>0.50;k6/x/faker>0.2.0"))

require.NoError(t, err)

k6Constraints, deps := depsConvert(src)

require.Equal(t, ">0.50", k6Constraints)

require.Equal(t, "k6/x/faker", deps[0].Name)
require.Equal(t, src["k6/x/faker"].Constraints.String(), deps[0].Constraints)

err = src.UnmarshalText([]byte("k6/x/faker*"))

require.NoError(t, err)

k6Constraints, deps = depsConvert(src)

require.Equal(t, "*", k6Constraints)

require.Equal(t, "k6/x/faker", deps[0].Name)
require.Equal(t, "*", deps[0].Constraints)
}

func Test_newBuildService(t *testing.T) {
t.Parallel()

u, _ := url.Parse("http://localhost:8000")

svc, err := newBuildService(context.Background(), &Options{BuildServiceURL: u})

require.NoError(t, err)
require.IsType(t, new(k6build.BuildClient), svc)
require.Equal(t, "*k6build.BuildClient", fmt.Sprintf("%T", svc))

srv := testWebServer(t)
defer srv.Close()

u, err = url.Parse(srv.URL + "/empty-catalog.json")
require.NoError(t, err)

svc, err = newBuildService(context.Background(), &Options{ExtensionCatalogURL: u})

require.NoError(t, err)

require.NotEqual(t, "*k6build.BuildClient", fmt.Sprintf("%T", svc))
}

//nolint:forbidigo
func Test_httpDownload(t *testing.T) {
t.Parallel()

srv := testWebServer(t)
defer srv.Close()

tmp := t.TempDir()
ctx := context.Background()
from, err := url.Parse(srv.URL + "/empty-catalog.json")

require.NoError(t, err)

dest, err := os.Create(filepath.Clean(filepath.Join(tmp, "catalog.json")))

require.NoError(t, err)

err = httpDownload(ctx, from, dest, http.DefaultClient)
require.NoError(t, err)

require.NoError(t, dest.Close())

contents, err := os.ReadFile(dest.Name())

require.NoError(t, err)
require.Equal(t, "{}\n", string(contents))
}

//nolint:forbidigo
func Test_fileDownload(t *testing.T) {
t.Parallel()

srv := testWebServer(t)
defer srv.Close()

tmp := t.TempDir()
abs, err := filepath.Abs(filepath.Join("testdata", "empty-catalog.json"))

require.NoError(t, err)

from, err := url.Parse("file:///" + filepath.ToSlash(abs))

require.NoError(t, err)

dest, err := os.Create(filepath.Clean(filepath.Join(tmp, "catalog.json")))

require.NoError(t, err)

err = fileDownload(from, dest)
require.NoError(t, err)

require.NoError(t, dest.Close())

contents, err := os.ReadFile(dest.Name())

require.NoError(t, err)
require.Equal(t, "{}\n", string(contents))

from, err = url.Parse("file:///" + tmp + "/no_such_file")

require.NoError(t, err)

err = fileDownload(from, dest)

require.Error(t, err)
}

//nolint:forbidigo
func Test_download(t *testing.T) {
t.Parallel()

srv := testWebServer(t)
defer srv.Close()

tmp := t.TempDir()
ctx := context.Background()
from, err := url.Parse(srv.URL + "/empty-catalog.json")

require.NoError(t, err)

dest := filepath.Clean(filepath.Join(tmp, "catalog.json"))

require.NoError(t, err)

err = download(ctx, from, dest, http.DefaultClient)
require.NoError(t, err)

contents, err := os.ReadFile(dest)

require.NoError(t, err)
require.Equal(t, "{}\n", string(contents))

abs, err := filepath.Abs(filepath.Join("testdata", "empty-catalog.json"))

require.NoError(t, err)

from, err = url.Parse("file:///" + filepath.ToSlash(abs))

require.NoError(t, err)

err = download(ctx, from, dest, http.DefaultClient)
require.NoError(t, err)

contents, err = os.ReadFile(dest)

require.NoError(t, err)
require.Equal(t, "{}\n", string(contents))
}

func testWebServer(t *testing.T) *httptest.Server {
t.Helper()

return httptest.NewServer(http.FileServer(http.Dir("testdata")))
}

func Test_build(t *testing.T) {
t.Parallel()

srv := testWebServer(t)
defer srv.Close()

u, err := url.Parse(srv.URL + "/minimal-catalog.json")

require.NoError(t, err)

ctx := context.Background()

loc, err := build(ctx, make(k6deps.Dependencies), &Options{ExtensionCatalogURL: u})

require.NoError(t, err)

tmp := t.TempDir()

dest := filepath.Join(tmp, k6binary)

err = download(ctx, loc, dest, nil)

require.NoError(t, err)

cmd := exec.Command(filepath.Clean(dest), "version")

out, err := cmd.Output()

require.NoError(t, err)
require.True(t, strings.HasPrefix(string(out), "k6 "))

u, err = url.Parse(srv.URL + "/empty-catalog.json")

require.NoError(t, err)

_, err = build(ctx, make(k6deps.Dependencies), &Options{ExtensionCatalogURL: u})

require.Error(t, err)

u, err = url.Parse(srv.URL + "/missing-catalog.json")

require.NoError(t, err)

_, err = build(ctx, make(k6deps.Dependencies), &Options{ExtensionCatalogURL: u})

require.Error(t, err)
}
51 changes: 51 additions & 0 deletions cleanup_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package k6exec_test

import (
"os"
"path/filepath"
"strconv"
"strings"
"testing"

"github.com/grafana/k6exec"
"github.com/stretchr/testify/require"
)

func exists(t *testing.T, filename string) bool {
t.Helper()

_, err := os.Stat(filename)

Check failure on line 17 in cleanup_test.go

View workflow job for this annotation

GitHub Actions / lint

use of `os.Stat` forbidden because "Using anything except Signal and SyscallError from the os package is forbidden" (forbidigo)

return err == nil
}

//nolint:forbidigo
func TestCleanupState(t *testing.T) {
t.Parallel()

tmp := t.TempDir()

opts := &k6exec.Options{StateDir: tmp}

subdir := filepath.Join(tmp, strconv.Itoa(os.Getpid()))

require.NoError(t, os.MkdirAll(subdir, 0700))

Check failure on line 32 in cleanup_test.go

View workflow job for this annotation

GitHub Actions / lint

File is not `gofumpt`-ed (gofumpt)

name := filepath.Join(subdir, "hello.txt")

err := os.WriteFile(name, []byte("Hello, World!\n"), 0o600)

require.NoError(t, err)

require.True(t, exists(t, name))

err = k6exec.CleanupState(opts)
require.NoError(t, err)

require.False(t, exists(t, subdir))
require.True(t, exists(t, tmp))

opts = &k6exec.Options{AppName: strings.Repeat("too long", 2048)}
err = k6exec.CleanupState(opts)
require.Error(t, err)
}
41 changes: 41 additions & 0 deletions command_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package k6exec_test

import (
"context"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

"github.com/grafana/k6exec"
"github.com/stretchr/testify/require"
)

func TestCommand(t *testing.T) {
t.Parallel()

srv := testWebServer(t)
defer srv.Close()

u, err := url.Parse(srv.URL + "/minimal-catalog.json")
require.NoError(t, err)

ctx := context.Background()

cmd, err := k6exec.Command(ctx, []string{"version"}, nil, &k6exec.Options{ExtensionCatalogURL: u})

require.NoError(t, err)

out, err := cmd.Output()

require.NoError(t, err)

require.True(t, strings.HasPrefix(string(out), "k6 "))
}

func testWebServer(t *testing.T) *httptest.Server {
t.Helper()

return httptest.NewServer(http.FileServer(http.Dir("testdata")))
}
4 changes: 4 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,27 @@ require (
github.com/samber/slog-logrus/v2 v2.4.0
github.com/sirupsen/logrus v1.9.3
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.9.0
golang.org/x/term v0.18.0
)

require (
github.com/Masterminds/semver v1.5.0 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/evanw/esbuild v0.21.5 // indirect
github.com/google/btree v1.1.2 // indirect
github.com/grafana/k6catalog v0.1.0 // indirect
github.com/grafana/k6foundry v0.1.3 // indirect
github.com/grafana/k6pack v0.2.1 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/samber/lo v1.44.0 // indirect
github.com/samber/slog-common v0.17.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/mod v0.18.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,16 @@ github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 h1:+ngKgrYPPJr
github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI=
github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=
github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/samber/lo v1.44.0 h1:5il56KxRE+GHsm1IR+sZ/6J42NODigFiqCWpSc2dybA=
github.com/samber/lo v1.44.0/go.mod h1:RmDH9Ct32Qy3gduHQuKJ3gW1fMHAnE/fAzQuf6He5cU=
Expand Down Expand Up @@ -62,6 +68,8 @@ golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading

0 comments on commit 35ff928

Please sign in to comment.