Skip to content

Commit

Permalink
feat: add more unittests
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanbagabas committed Nov 30, 2023
1 parent bac2ff3 commit cf28318
Show file tree
Hide file tree
Showing 22 changed files with 319 additions and 26 deletions.
2 changes: 1 addition & 1 deletion cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func InitBackendContext(cmd *cobra.Command, _ []string) error {
ctx = db.WithContext(ctx, dbx)
dbstore := database.New(ctx, dbx)
ctx = store.WithContext(ctx, dbstore)
be := backend.New(ctx, cfg, dbx)
be := backend.New(ctx, cfg, dbx, dbstore)
ctx = backend.WithContext(ctx, be)

cmd.SetContext(ctx)
Expand Down
20 changes: 20 additions & 0 deletions pkg/access/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package access

import (
"context"
"testing"
)

func TestGoodFromContext(t *testing.T) {
ctx := WithContext(context.TODO(), AdminAccess)
if ac := FromContext(ctx); ac != AdminAccess {
t.Errorf("FromContext(ctx) => %d, want %d", ac, AdminAccess)
}
}

func TestBadFromContext(t *testing.T) {
ctx := context.TODO()
if ac := FromContext(ctx); ac != -1 {
t.Errorf("FromContext(ctx) => %d, want %d", ac, -1)
}
}
5 changes: 2 additions & 3 deletions pkg/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,13 @@ type Backend struct {
}

// New returns a new Soft Serve backend.
func New(ctx context.Context, cfg *config.Config, db *db.DB) *Backend {
dbstore := store.FromContext(ctx)
func New(ctx context.Context, cfg *config.Config, db *db.DB, st store.Store) *Backend {
logger := log.FromContext(ctx).WithPrefix("backend")
b := &Backend{
ctx: ctx,
cfg: cfg,
db: db,
store: dbstore,
store: st,
logger: logger,
manager: task.NewManager(ctx),
}
Expand Down
29 changes: 29 additions & 0 deletions pkg/config/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package config

import (
"context"
"reflect"
"testing"
)

func TestBadFromContext(t *testing.T) {
ctx := context.TODO()
if c := FromContext(ctx); c != nil {
t.Errorf("FromContext(ctx) => %v, want %v", c, nil)
}
}

func TestGoodFromContext(t *testing.T) {
ctx := WithContext(context.TODO(), &Config{})
if c := FromContext(ctx); c == nil {
t.Errorf("FromContext(ctx) => %v, want %v", c, &Config{})
}
}

func TestGoodFromContextWithDefaultConfig(t *testing.T) {
cfg := DefaultConfig()
ctx := WithContext(context.TODO(), cfg)
if c := FromContext(ctx); c == nil || !reflect.DeepEqual(c, cfg) {
t.Errorf("FromContext(ctx) => %v, want %v", c, cfg)
}
}
15 changes: 15 additions & 0 deletions pkg/config/file_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package config

import "testing"

func TestNewConfigFile(t *testing.T) {
for _, cfg := range []*Config{
nil,
DefaultConfig(),
&Config{},
} {
if s := newConfigFile(cfg); s == "" {
t.Errorf("newConfigFile(nil) => %q, want non-empty string", s)
}
}
}
27 changes: 26 additions & 1 deletion pkg/config/ssh.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,33 @@
package config

import "github.com/charmbracelet/keygen"
import (
"errors"

"github.com/charmbracelet/keygen"
)

var (
// ErrNilConfig is returned when a nil config is passed to a function.
ErrNilConfig = errors.New("nil config")

// ErrEmptySSHKeyPath is returned when the SSH key path is empty.
ErrEmptySSHKeyPath = errors.New("empty SSH key path")
)

// KeyPair returns the server's SSH key pair.
func (c SSHConfig) KeyPair() (*keygen.SSHKeyPair, error) {
return keygen.New(c.KeyPath, keygen.WithKeyType(keygen.Ed25519))
}

// KeyPair returns the server's SSH key pair.
func KeyPair(cfg *Config) (*keygen.SSHKeyPair, error) {
if cfg == nil {
return nil, ErrNilConfig
}

if cfg.SSH.KeyPath == "" {
return nil, ErrEmptySSHKeyPath
}

return keygen.New(cfg.SSH.KeyPath, keygen.WithKeyType(keygen.Ed25519))

Check failure on line 32 in pkg/config/ssh.go

View workflow job for this annotation

GitHub Actions / lint-soft

error returned from external package is unwrapped: sig: func github.com/charmbracelet/keygen.New(path string, opts ...github.com/charmbracelet/keygen.Option) (*github.com/charmbracelet/keygen.KeyPair, error) (wrapcheck)
}
26 changes: 26 additions & 0 deletions pkg/config/ssh_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package config

import "testing"

func TestBadSSHKeyPair(t *testing.T) {
for _, cfg := range []*Config{
nil,
{},
} {
if _, err := KeyPair(cfg); err == nil {
t.Errorf("cfg.SSH.KeyPair() => _, nil, want non-nil error")
}
}
}

func TestGoodSSHKeyPair(t *testing.T) {
cfg := &Config{
SSH: SSHConfig{
KeyPath: "testdata/ssh_host_ed25519_key",
},
}

if _, err := KeyPair(cfg); err != nil {
t.Errorf("cfg.SSH.KeyPair() => _, %v, want nil error", err)
}
}
31 changes: 31 additions & 0 deletions pkg/cron/cron_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package cron

import (
"bytes"
"context"
"fmt"
"testing"

"github.com/charmbracelet/log"
)

func TestCronLogger(t *testing.T) {
var buf bytes.Buffer
logger := log.New(&buf)
logger.SetLevel(log.DebugLevel)
clogger := cronLogger{logger}
clogger.Info("foo")
clogger.Error(fmt.Errorf("bar"), "test")
if buf.String() != "DEBU foo\nERRO test err=bar\n" {
t.Errorf("unexpected log output: %s", buf.String())
}
}

func TestSchedularAddRemove(t *testing.T) {
s := NewScheduler(context.TODO())
id, err := s.AddFunc("* * * * *", func() {})
if err != nil {
t.Fatal(err)
}
s.Remove(id)
}
2 changes: 1 addition & 1 deletion pkg/daemon/daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func TestMain(m *testing.M) {
}
datastore := database.New(ctx, dbx)
ctx = store.WithContext(ctx, datastore)
be := backend.New(ctx, cfg, dbx)
be := backend.New(ctx, cfg, dbx, datastore)
ctx = backend.WithContext(ctx, be)
d, err := NewGitDaemon(ctx)
if err != nil {
Expand Down
25 changes: 25 additions & 0 deletions pkg/db/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package db

import (
"context"
"testing"
)

func TestBadFromContext(t *testing.T) {
ctx := context.TODO()
if c := FromContext(ctx); c != nil {
t.Errorf("FromContext(ctx) => %v, want %v", c, nil)
}
}

func TestGoodFromContext(t *testing.T) {
ctx := context.TODO()
dbx, err := testOpenSqlite(t, ctx)
if err != nil {
t.Fatal(err)
}
ctx = WithContext(ctx, dbx)
if c := FromContext(ctx); c == nil {
t.Errorf("FromContext(ctx) => %v, want %v", c, dbx)
}
}
38 changes: 38 additions & 0 deletions pkg/db/db_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package db

import (
"context"
"path/filepath"
"strings"
"testing"
)

// testOpenSqlite opens a new temp SQLite database for testing.
// It removes the database file when the test is done using tb.Cleanup.
// If ctx is nil, context.TODO() is used.
func testOpenSqlite(tb testing.TB, ctx context.Context) (*DB, error) {
if ctx == nil {
ctx = context.TODO()
}
dbpath := filepath.Join(tb.TempDir(), "test.db")
dbx, err := Open(ctx, "sqlite", dbpath)
if err != nil {
return nil, err
}
tb.Cleanup(func() {
if err := dbx.Close(); err != nil {
tb.Error(err)
}
})
return dbx, nil
}

func TestOpenUnknownDriver(t *testing.T) {
_, err := Open(context.TODO(), "invalid", "")
if err == nil {
t.Error("Open(invalid) => nil, want error")
}
if !strings.Contains(err.Error(), "unknown driver") {
t.Errorf("Open(invalid) => %v, want error containing 'unknown driver'", err)
}
}
25 changes: 25 additions & 0 deletions pkg/db/errors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package db

import (
"database/sql"
"errors"
"fmt"
"testing"
)

func TestWrapErrorBadNoRows(t *testing.T) {
for _, e := range []error{
fmt.Errorf("foo"),
errors.New("bar"),
} {
if err := WrapError(e); err != e {
t.Errorf("WrapError(%v) => %v, want %v", e, err, e)
}
}
}

func TestWrapErrorGoodNoRows(t *testing.T) {
if err := WrapError(sql.ErrNoRows); err != ErrRecordNotFound {
t.Errorf("WrapError(sql.ErrNoRows) => %v, want %v", err, ErrRecordNotFound)
}
}
16 changes: 11 additions & 5 deletions pkg/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package git

import (
"context"
"errors"
"fmt"
"io"
"path/filepath"
Expand All @@ -13,6 +14,11 @@ import (
"github.com/go-git/go-git/v5/plumbing/format/pktline"
)

var (
// ErrNoBranches is returned when a repo has no branches.
ErrNoBranches = errors.New("no branches found")
)

// WritePktline encodes and writes a pktline to the given writer.
func WritePktline(w io.Writer, v ...interface{}) error {
msg := fmt.Sprintln(v...)
Expand Down Expand Up @@ -57,18 +63,18 @@ func EnsureWithin(reposDir string, repo string) error {

// EnsureDefaultBranch ensures the repo has a default branch.
// It will prefer choosing "main" or "master" if available.
func EnsureDefaultBranch(ctx context.Context, scmd ServiceCommand) error {
r, err := git.Open(scmd.Dir)
func EnsureDefaultBranch(ctx context.Context, repoPath string) error {
r, err := git.Open(repoPath)
if err != nil {
return err
}
brs, err := r.Branches()
if len(brs) == 0 {
return ErrNoBranches
}
if err != nil {
return err
}
if len(brs) == 0 {
return fmt.Errorf("no branches found")
}
// Rename the default branch to the first branch available
_, err = r.HEAD()
if err == git.ErrReferenceNotExist {
Expand Down
41 changes: 41 additions & 0 deletions pkg/git/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ package git

import (
"bytes"
"context"
"errors"
"fmt"
"testing"

"github.com/charmbracelet/soft-serve/git"
)

func TestPktline(t *testing.T) {
Expand Down Expand Up @@ -54,3 +58,40 @@ func TestPktline(t *testing.T) {
})
}
}

func TestEnsureWithinBad(t *testing.T) {
tmp := t.TempDir()
for _, f := range []string{
"..",
"../../../",
} {
if err := EnsureWithin(tmp, f); err == nil {
t.Errorf("EnsureWithin(%q, %q) => nil, want non-nil error", tmp, f)
}
}
}

func TestEnsureWithinGood(t *testing.T) {
tmp := t.TempDir()
for _, f := range []string{
tmp,
tmp + "/foo",
tmp + "/foo/bar",
} {
if err := EnsureWithin(tmp, f); err != nil {
t.Errorf("EnsureWithin(%q, %q) => %v, want nil error", tmp, f, err)
}
}
}

func TestEnsureDefaultBranchEmpty(t *testing.T) {
tmp := t.TempDir()
r, err := git.Init(tmp, false)
if err != nil {
t.Fatal(err)
}

if err := EnsureDefaultBranch(context.TODO(), r.Path); !errors.Is(err, ErrNoBranches) {
t.Errorf("EnsureDefaultBranch(%q) => %v, want ErrNoBranches", tmp, err)
}
}
Loading

0 comments on commit cf28318

Please sign in to comment.