Skip to content

Commit

Permalink
Add testing feature
Browse files Browse the repository at this point in the history
  • Loading branch information
hwbrzzl committed Jul 30, 2023
1 parent 5c6fdac commit 0c27c02
Show file tree
Hide file tree
Showing 10 changed files with 242 additions and 11 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ This project exists thanks to all the people who contribute, to participate in t
<a href="https://github.com/mauri870" target="_blank"><img src="https://avatars.githubusercontent.com/u/10168637?v=4" width="48" height="48"></a>
<a href="https://github.com/Marian0" target="_blank"><img src="https://avatars.githubusercontent.com/u/624592?v=4" width="48" height="48"></a>
<a href="https://github.com/ahmed3mar" target="_blank"><img src="https://avatars.githubusercontent.com/u/12982325?v=4" width="48" height="48"></a>
<a href="https://github.com/flc1125" target="_blank"><img src="https://avatars.githubusercontent.com/u/14297703?v=4" width="48" height="48"></a>

## Group

Expand Down
1 change: 1 addition & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ Laravel!
<a href="https://github.com/mauri870" target="_blank"><img src="https://avatars.githubusercontent.com/u/10168637?v=4" width="48" height="48"></a>
<a href="https://github.com/Marian0" target="_blank"><img src="https://avatars.githubusercontent.com/u/624592?v=4" width="48" height="48"></a>
<a href="https://github.com/ahmed3mar" target="_blank"><img src="https://avatars.githubusercontent.com/u/12982325?v=4" width="48" height="48"></a>
<a href="https://github.com/flc1125" target="_blank"><img src="https://avatars.githubusercontent.com/u/14297703?v=4" width="48" height="48"></a>

## 群组

Expand Down
66 changes: 58 additions & 8 deletions foundation/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ var (
App foundation.Application
)

var flagEnv = flag.String("env", ".env", "custom .env path")

Check failure on line 21 in foundation/application.go

View workflow job for this annotation

GitHub Actions / lint

var `flagEnv` is unused (unused)

func init() {
setEnv()

Expand Down Expand Up @@ -46,6 +48,7 @@ func (app *Application) Boot() {
app.registerConfiguredServiceProviders()
app.bootConfiguredServiceProviders()
app.registerCommands([]consolecontract.Command{
console.NewTestMakeCommand(),
console.NewPackageMakeCommand(),
console.NewVendorPublishCommand(app.publishes, app.publishGroups),
})
Expand Down Expand Up @@ -183,16 +186,32 @@ func setEnv() {
}
}

var env *string
if !flag.Parsed() && support.Env != support.EnvTest {
env = flag.String("env", ".env", "custom .env path")
flag.Parse()
} else {
testEnv := ".env"
env = &testEnv
env := getEnvPath()
if support.Env == support.EnvTest {
var (
relativePath string
envExist bool
testEnv = env
)

for i := 0; i < 50; i++ {
if _, err := os.Stat(testEnv); err == nil {
envExist = true

break
} else {
testEnv = filepath.Join("../", testEnv)
relativePath = filepath.Join("../", relativePath)
}
}

if envExist {
env = testEnv
support.RelativePath = relativePath
}
}

support.EnvPath = *env
support.EnvPath = env
}

func setRootPath() {
Expand All @@ -206,3 +225,34 @@ func setRootPath() {

support.RootPath = rootPath
}

func getEnvPath() string {
envPath := ".env"
args := os.Args
for index, arg := range args {
if strings.HasPrefix(arg, "--env=") {
path := strings.TrimPrefix(arg, "--env=")

if path != "" {
envPath = path
break
}
}
if strings.HasPrefix(arg, "-env=") {
path := strings.TrimPrefix(arg, "-env=")

if path != "" {
envPath = path
break
}
}
if arg == "--env" || arg == "-env" {
if len(args) >= index+1 && !strings.HasPrefix(args[index+1], "-") {
envPath = args[index+1]
break
}
}
}

return envPath
}
38 changes: 38 additions & 0 deletions foundation/console/stubs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package console

type Stubs struct {
}

func (r Stubs) Test() string {
return `package DummyPackage
import (
"testing"
"github.com/stretchr/testify/suite"
"goravel/tests"
)
type DummyTestSuite struct {
suite.Suite
tests.TestCase
}
func TestDummyTestSuite(t *testing.T) {
suite.Run(t, new(DummyTestSuite))
}
// SetupTest will run before each test in the suite.
func (s *UserTestSuite) SetupTest() {
}
// TearDownTest will run after each test in the suite.
func (s *UserTestSuite) TearDownTest() {
}
func (s *UserTestSuite) TestIndex() {
// TODO
}
`
}
99 changes: 99 additions & 0 deletions foundation/console/test_make_command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package console

import (
"errors"
"os"
"path/filepath"
"strings"

"github.com/gookit/color"

"github.com/goravel/framework/contracts/console"
"github.com/goravel/framework/contracts/console/command"
"github.com/goravel/framework/support/file"
"github.com/goravel/framework/support/str"
)

type TestMakeCommand struct {
}

func NewTestMakeCommand() *TestMakeCommand {
return &TestMakeCommand{}
}

// Signature The name and signature of the console command.
func (receiver *TestMakeCommand) Signature() string {
return "make:test"
}

// Description The console command description.
func (receiver *TestMakeCommand) Description() string {
return "Create a new test class"
}

// Extend The console command extend.
func (receiver *TestMakeCommand) Extend() command.Extend {
return command.Extend{
Category: "make",
}
}

// Handle Execute the console command.
func (receiver *TestMakeCommand) Handle(ctx console.Context) error {
name := ctx.Argument(0)
if name == "" {
return errors.New("Not enough arguments (missing: name) ")
}

stub := receiver.getStub()

if err := file.Create(receiver.getPath(name), receiver.populateStub(stub, name)); err != nil {
return err
}

color.Greenln("Test created successfully")

return nil
}

func (receiver *TestMakeCommand) getStub() string {
return Stubs{}.Test()
}

// populateStub Populate the place-holders in the command stub.
func (receiver *TestMakeCommand) populateStub(stub string, name string) string {
controllerName, packageName, _ := receiver.parseName(name)

stub = strings.ReplaceAll(stub, "DummyTest", str.Case2Camel(controllerName))
stub = strings.ReplaceAll(stub, "DummyPackage", packageName)

return stub
}

// getPath Get the full path to the command.
func (receiver *TestMakeCommand) getPath(name string) string {
pwd, _ := os.Getwd()

controllerName, _, folderPath := receiver.parseName(name)

return filepath.Join(pwd, "tests", folderPath, str.Camel2Case(controllerName)+".go")
}

// parseName Parse the name to get the controller name, package name and folder path.
func (receiver *TestMakeCommand) parseName(name string) (string, string, string) {
name = strings.TrimSuffix(name, ".go")

segments := strings.Split(name, "/")

controllerName := segments[len(segments)-1]

packageName := "tests"
folderPath := ""

if len(segments) > 1 {
folderPath = filepath.Join(segments[:len(segments)-1]...)
packageName = segments[len(segments)-2]
}

return controllerName, packageName, folderPath
}
32 changes: 32 additions & 0 deletions foundation/console/test_make_command_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package console

import (
"testing"

"github.com/stretchr/testify/assert"

consolemocks "github.com/goravel/framework/contracts/console/mocks"
"github.com/goravel/framework/support/file"
)

func TestTestMakeCommand(t *testing.T) {
testMakeCommand := &TestMakeCommand{}
mockContext := &consolemocks.Context{}
mockContext.On("Argument", 0).Return("").Once()
err := testMakeCommand.Handle(mockContext)
assert.EqualError(t, err, "Not enough arguments (missing: name) ")

mockContext.On("Argument", 0).Return("UserTest").Once()
err = testMakeCommand.Handle(mockContext)
assert.Nil(t, err)
assert.True(t, file.Exists("tests/user_test.go"))

mockContext.On("Argument", 0).Return("user/UserTest").Once()
err = testMakeCommand.Handle(mockContext)
assert.Nil(t, err)
assert.True(t, file.Exists("tests/user/user_test.go"))
assert.True(t, file.Contain("tests/user/user_test.go", "package user"))
assert.True(t, file.Contain("tests/user/user_test.go", "type UserTestSuite struct"))
assert.True(t, file.Contain("tests/user/user_test.go", "func (s *UserTestSuite) SetupTest() {"))
assert.Nil(t, file.Remove("tests"))
}
2 changes: 2 additions & 0 deletions log/logger/daily.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/goravel/framework/contracts/config"
"github.com/goravel/framework/log/formatter"
"github.com/goravel/framework/support"
)

type Daily struct {
Expand All @@ -33,6 +34,7 @@ func (daily *Daily) Handle(channel string) (logrus.Hook, error) {

ext := filepath.Ext(logPath)
logPath = strings.ReplaceAll(logPath, ext, "")
logPath = filepath.Join(support.RelativePath, logPath)

writer, err := rotatelogs.New(
logPath+"-%Y-%m-%d"+ext,
Expand Down
3 changes: 3 additions & 0 deletions log/logger/single.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package logger

import (
"errors"
"path/filepath"

"github.com/rifflock/lfshook"
"github.com/sirupsen/logrus"

"github.com/goravel/framework/contracts/config"
"github.com/goravel/framework/log/formatter"
"github.com/goravel/framework/support"
)

type Single struct {
Expand All @@ -26,6 +28,7 @@ func (single *Single) Handle(channel string) (logrus.Hook, error) {
return nil, errors.New("error log path")
}

logPath = filepath.Join(support.RelativePath, logPath)
levels := getLevels(single.config.GetString(channel + ".level"))
pathMap := lfshook.PathMap{}
for _, level := range levels {
Expand Down
7 changes: 4 additions & 3 deletions support/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ const (
)

var (
Env = EnvRuntime
EnvPath = ".env"
RootPath string
Env = EnvRuntime
EnvPath string
RelativePath string
RootPath string
)
4 changes: 4 additions & 0 deletions testing/test_case.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package testing

type TestCase struct {
}

0 comments on commit 0c27c02

Please sign in to comment.