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

Include unit tests in additional functionalities #23

Merged
merged 6 commits into from
Oct 3, 2023
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
Binary file added assets/tests/test.whl
Binary file not shown.
7 changes: 7 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ func TestReadConfig(t *testing.T) {
assert.Equal("/home/ubuntu/bodystats", c.Dir)
}

func TestReadConfigError(t *testing.T) {
assert := assert.New(t)
c, err := ReadConfig("../unknown/assets/tests/jerm.json")
assert.Nil(c)
assert.EqualError(err, "open ../unknown/assets/tests/jerm.json: no such file or directory")
}

func TestIgnoredFiles(t *testing.T) {
assert := assert.New(t)
files, err := ReadIgnoredFiles("../assets/tests/.jermignore")
Expand Down
6 changes: 4 additions & 2 deletions config/golang.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ func (g *Go) getVersion() (string, error) {
return "", err
}
s := strings.Split(goVersion, " ")
if len(s) > 1 {
if len(s) > 2 {
version := strings.Split(s[2], "go")
return strings.TrimSpace(version[1]), nil
if len(version) > 1 {
return strings.TrimSpace(version[1]), nil
}
}
return "", errors.New("encountered error on go version")
}
Expand Down
11 changes: 9 additions & 2 deletions config/golang_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,13 @@ func TestGoGetVersionError(t *testing.T) {
r := NewGoRuntime(fakeCommandExecutor{})
g := r.(*Go)
v, err := g.getVersion()
assert.NotNil(err)
assert.Error(err)
assert.Equal(RuntimeGo, g.Name)
assert.Equal("", v)

fakeOutput = "go w e"
v, err = g.getVersion()
assert.EqualError(err, "encountered error on go version")
assert.Equal(RuntimeGo, g.Name)
assert.Equal("", v)
}
Expand All @@ -61,6 +67,7 @@ func TestGoBuild(t *testing.T) {
fakeOutput = "go version go1.21.0 linux/amd64"
r := NewGoRuntime(fakeCommandExecutor{})
cfg := &Config{Name: "test", Stage: "env"}

p, f, err := r.Build(cfg)
assert.Nil(err)
assert.Equal("main", p)
Expand All @@ -73,7 +80,7 @@ func TestGoBuildError(t *testing.T) {
r := NewGoRuntime(fakeCommandExecutor{})
cfg := &Config{Name: "test", Stage: "env"}
p, f, err := r.Build(cfg)
assert.NotNil(err)
assert.Error(err)
assert.Equal("", p)
assert.Equal("", f)
}
2 changes: 1 addition & 1 deletion config/platform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func TestPlaformDefaults(t *testing.T) {
assert.Equal(0, p.Timeout)
assert.Equal("", p.Runtime)
err := p.Defaults()
assert.ErrorContains(err, "cannot detect runtime. please specify runtime in your Jerm.json file")
assert.EqualError(err, "cannot detect runtime. please specify runtime in your Jerm.json file")
assert.Equal("", p.Runtime)
assert.Equal(DefaultMemory, p.Memory)
assert.Equal(DefaultTimeout, p.Timeout)
Expand Down
10 changes: 5 additions & 5 deletions config/python.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func (p *Python) Build(config *Config) (string, string, error) {
log.Debug(err.Error())
}
handler := strings.ReplaceAll(p.handlerTemplate, ".wsgi", djangoProject+".wsgi")
function, err = p.createFunctionHandler(config, handlerFilepath, handler)
function, err = p.createFunctionHandler(handlerFilepath, []byte(handler))
if err != nil {
return "", "", err
}
Expand All @@ -147,15 +147,15 @@ func (p *Python) Build(config *Config) (string, string, error) {
}

// createFunctionHandler creates a serverless function handler file
func (p *Python) createFunctionHandler(config *Config, file, handler string) (string, error) {
func (p *Python) createFunctionHandler(file string, content []byte) (string, error) {
log.Debug("creating lambda handler...")
f, err := os.Create(file)
if err != nil {
return "", err
}
defer f.Close()

_, err = f.Write([]byte(handler))
_, err = f.Write(content)
if err != nil {
return "", err
}
Expand Down Expand Up @@ -249,7 +249,7 @@ func (p *Python) downloadDependencies(url, filename, dir string) error {

// Extracts python wheel from wheelPath to outputDir
func (p *Python) extractWheel(wheelPath, outputDir string) error {
log.Debug("extracting python wheel...")
log.Debug(fmt.Sprintf("extracting python wheel %s...", wheelPath))
var eg errgroup.Group

reader, err := zip.OpenReader(wheelPath)
Expand All @@ -261,7 +261,7 @@ func (p *Python) extractWheel(wheelPath, outputDir string) error {
for _, file := range reader.File {
func(file *zip.File) {
eg.Go(func() error {
os.MkdirAll(filepath.Join(outputDir, filepath.Dir(file.Name)), 0755)
err = os.MkdirAll(filepath.Join(outputDir, filepath.Dir(file.Name)), 0755)
if err != nil {
return err
}
Expand Down
36 changes: 35 additions & 1 deletion config/python_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package config

import (
"fmt"
"path/filepath"
"testing"

"github.com/spatocode/jerm/internal/utils"
"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -42,7 +44,7 @@ func TestPythonGetVersionError(t *testing.T) {
r := NewPythonRuntime(fakeCommandExecutor{})
p := r.(*Python)
v, err := p.getVersion()
assert.NotNil(err)
assert.Error(err)
assert.Equal(RuntimePython, p.Name)
assert.Equal("", v)
}
Expand All @@ -69,6 +71,7 @@ func TestPythonLambdaRuntime(t *testing.T) {

func TestPythonIsDjango(t *testing.T) {
assert := assert.New(t)

fakeOutput = "Python 3.9.0"
r := NewPythonRuntime(fakeCommandExecutor{})
p := r.(*Python)
Expand All @@ -79,3 +82,34 @@ func TestPythonIsDjango(t *testing.T) {
assert.True(is)
helperCleanup(t, []string{managePy})
}

func TestPythonCreateFunctionHandler(t *testing.T) {
assert := assert.New(t)

fakeOutput = "Python 3.9.0"
r := NewPythonRuntime(fakeCommandExecutor{})
p := r.(*Python)

handlerFile := filepath.Join("../assets/tests", "handler.py")
handler, err := p.createFunctionHandler(handlerFile, []byte("This is a test handler"))

assert.Nil(err)
assert.Equal("handler.handler", handler)
helperCleanup(t, []string{handlerFile})
}

func TestPythonExtractWheel(t *testing.T) {
assert := assert.New(t)

fakeOutput = "Python 3.9.0"
r := NewPythonRuntime(fakeCommandExecutor{})
p := r.(*Python)

file1 := "../assets/tests/test"
file2 := "../assets/tests/test.txt"
p.extractWheel("../assets/tests/test.whl", "../assets/tests")
assert.True(utils.FileExists(file1))
assert.True(utils.FileExists(file2))

helperCleanup(t, []string{file1, file2})
}
6 changes: 3 additions & 3 deletions config/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ func (r *Runtime) Build(config *Config) (string, string, error) {

if r.Name == RuntimeStatic && function == "" {
handlerFilepath := filepath.Join(tempDir, "index.js")
function, err = r.createFunctionHandler(config, handlerFilepath)
function, err = r.createFunctionHandler(handlerFilepath, []byte(r.handlerTemplate))
if err != nil {
return "", "", err
}
Expand All @@ -109,15 +109,15 @@ func (r *Runtime) Build(config *Config) (string, string, error) {
}

// createFunctionHandler creates a serverless function handler file
func (r *Runtime) createFunctionHandler(config *Config, file string) (string, error) {
func (r *Runtime) createFunctionHandler(file string, content []byte) (string, error) {
log.Debug("creating lambda handler...")
f, err := os.Create(file)
if err != nil {
return "", err
}
defer f.Close()

_, err = f.Write([]byte(r.handlerTemplate))
_, err = f.Write(content)
if err != nil {
return "", err
}
Expand Down
22 changes: 19 additions & 3 deletions config/runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,17 +73,33 @@ func TestRuntimeBuild(t *testing.T) {
assert.True(utils.FileExists(testfile2))
assert.True(utils.FileExists(jermJson))
assert.True(utils.FileExists(jermIgnore))

r.Name = RuntimeStatic
_, f, err = r.Build(cfg)
assert.Nil(err)
assert.Equal("index.handler", f)
}

func TestRuntimeBuildError(t *testing.T) {
assert := assert.New(t)

fakeOutput = ""
r := NewRuntime()
cfg := &Config{Name: "test", Stage: "env"}
p, f, err := r.Build(cfg)
assert.EqualError(err, "lstat : no such file or directory")
assert.Equal("", p)
assert.Equal("", f)
}

func TestRuntimeCreateFunctionHandler(t *testing.T) {
assert := assert.New(t)

cfg := &Config{Name: "test", Stage: "env", Dir: "../assets/tests"}
ri := NewRuntime()
r := ri.(*Runtime)

handlerFile := filepath.Join("../assets/tests", "index.js")
handler, err := r.createFunctionHandler(cfg, handlerFile)
handler, err := r.createFunctionHandler(handlerFile, []byte("This is a test handler"))

assert.Nil(err)
assert.Equal("index.handler", handler)
Expand Down Expand Up @@ -128,7 +144,7 @@ func TestNewRuntime(t *testing.T) {

func helperCleanup(t *testing.T, files []string) {
for _, file := range files {
err := os.Remove(file)
err := os.RemoveAll(file)
if err != nil {
t.Fatal(err)
}
Expand Down
74 changes: 74 additions & 0 deletions internal/log/log_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package log

import (
"io"
"os"
"testing"

"github.com/stretchr/testify/assert"
)

func TestInfoLog(t *testing.T) {
assert := assert.New(t)

r, w, stdout := pipeStd(t)
Info("testing")
w.Close()
out, _ := io.ReadAll(r)
os.Stdout = stdout

assert.Contains(string(out), "INFO testing\n")
}

func TestDebugLog(t *testing.T) {
assert := assert.New(t)

r, w, stdout := pipeStd(t)
Debug("testing")
w.Close()
out, _ := io.ReadAll(r)
os.Stdout = stdout
assert.NotContains(string(out), "DEBUG testing\n")

os.Setenv("JERM_VERBOSE", "1")
r, w, stdout = pipeStd(t)
Debug("testing")
w.Close()
out, _ = io.ReadAll(r)
os.Stdout = stdout
assert.Contains(string(out), "DEBUG testing\n")
}

func TestWarnLog(t *testing.T) {
assert := assert.New(t)

r, w, stdout := pipeStd(t)
Warn("testing")
w.Close()
out, _ := io.ReadAll(r)
os.Stdout = stdout

assert.Contains(string(out), "WARN testing\n")
}

func TestErrorLog(t *testing.T) {
assert := assert.New(t)

r, w, stdout := pipeStd(t)
Error("testing")
w.Close()
out, _ := io.ReadAll(r)
os.Stdout = stdout

assert.Contains(string(out), "ERROR testing\n")
}

func pipeStd(t *testing.T) (r, w, stdout *os.File) {
stdout = os.Stdout
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stdout = w
return
}
44 changes: 44 additions & 0 deletions internal/utils/utils_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package utils

import (
"os"
"os/exec"
"strings"
"testing"

Expand All @@ -14,3 +16,45 @@ func TestReadPromptInput(t *testing.T) {
assert.Nil(err)
assert.Equal("Foo", input)
}

func TestRunCommandWith(t *testing.T) {
assert := assert.New(t)
ce := cmdExecutor{cmd: fakeExecCommand}
out, err := ce.RunCommand("test", "arg")
assert.Nil(err)
out = strings.Split(out, "\n")[0]
assert.Equal("PASS", out)
}

func TestRunCommandWithEnv(t *testing.T) {
assert := assert.New(t)
ce := cmdExecutor{cmd: fakeExecCommand}
out, err := ce.RunCommandWithEnv([]string{"JERM_ENV"}, "test", "arg")
assert.Nil(err)
out = strings.Split(out, "\n")[0]
assert.Equal("PASS", out)
}

func TestRemoveLocalFile(t *testing.T) {
assert := assert.New(t)
file := "../../assets/test.whl"
helperCreateFile(t, file)
err := RemoveLocalFile(file)
assert.Nil(err)
assert.False(FileExists(file))
}

func fakeExecCommand(command string, args ...string) *exec.Cmd {
cs := []string{"-test.run=TestHelperProcess", "--", command}
cs = append(cs, args...)
cmd := exec.Command(os.Args[0], cs...)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
return cmd
}

func helperCreateFile(t *testing.T, file string) {
_, err := os.Create(file)
if err != nil {
t.Fatal(err)
}
}
Loading