Skip to content

Commit

Permalink
Merge branch 'jmartin82:master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
jdietrich-tc authored Apr 9, 2024
2 parents 14d9622 + 7d8e723 commit 22afc79
Show file tree
Hide file tree
Showing 23 changed files with 374 additions and 120 deletions.
36 changes: 36 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: CI

on:
push:
branches:
- master
pull_request:
branches:
- master

jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
go-version: [1.21]

steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: ${{ matrix.go-version }}
id: go

- name: Check out code into the Go module directory
uses: actions/checkout@v3

- name: Build
run: make test

- name: Test with coverage
run: make coverage

- name: Upload coverage to Codecov
run: bash <(curl -s https://codecov.io/bash)
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ debug.test
data/*
/vendor
coverage.txt
.github
dist
.vscode
.idea
10 changes: 0 additions & 10 deletions .travis.yml

This file was deleted.

20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ I am maintaining all of my changes to this fork in the [jcd-all](https://github.

![Mmock](/docs/logo.png "Mmock logo")
=========
[![Build Status](https://app.travis-ci.com/jmartin82/mmock.svg?branch=master)](https://app.travis-ci.com/jmartin82/mmock)


Mmock is a testing and fast prototyping tool for developers:

Expand Down Expand Up @@ -128,6 +126,16 @@ To configure Mmock, use command line flags described in help.
TLS config folder (server.crt and server.key should be inside) (default "execution_path/tls")
```

The default logging level is INFO, but you can change it by setting the
environment variable LOG_LEVEL to one of the following:

* CRITICAL
* ERROR
* WARNING
* NOTICE
* INFO
* DEBUG

### Mock

Mock definition:
Expand Down Expand Up @@ -220,6 +228,12 @@ Query strings and headers support also global matches (*) in the header/paramete
}
```

Regexp matching is available for:
- body
- query strings

See https://pkg.go.dev/regexp/syntax for regexp syntax

#### Response (Optional on proxy call)

* *statusCode*: Response status code
Expand Down Expand Up @@ -614,6 +628,8 @@ You can always disable this behavior adding the following flag `-server-statisti
- Thanks to [@joel-44](https://github.com/joel-44) for bug fixing
- Enviroment variables as mock variables thanks to [@marcoreni](https://github.com/marcoreni)
- Support Regular Expressions for Field Values in JSON Request Body thanks to [@rosspatil](https://github.com/rosspatil)
- Improved logging with levels thanks to [@jcdietrich](https://github.com/jcdietrich) [@jdietrich-tc](https://github.com/jdietrich-tc)
- Support for Regular Expressions for QueryStringParameters [@jcdietrich](https://github.com/jcdietrich) [@jdietrich-tc](https://github.com/jdietrich-tc)

### Contributing

Expand Down
14 changes: 8 additions & 6 deletions cmd/mmock/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import (
"errors"
"flag"
"fmt"
"log"
"net"
"os"
"path/filepath"
"strings"

"github.com/jmartin82/mmock/v3/internal/config"
"github.com/jmartin82/mmock/v3/internal/config/logger"
"github.com/jmartin82/mmock/v3/internal/config/parser"
"github.com/jmartin82/mmock/v3/internal/console"
"github.com/jmartin82/mmock/v3/internal/server"
Expand All @@ -34,6 +34,8 @@ var ErrNotFoundDefaultPath = errors.New("We can't determinate the current path")
// ErrNotFoundAnyMock when we don't found any valid mock config to load
var ErrNotFoundAnyMock = errors.New("No valid mock config found")

var log = logger.Log

func banner() {
fmt.Printf("MMock v %s", VERSION)
fmt.Print(`
Expand Down Expand Up @@ -65,7 +67,7 @@ func getOutboundIP() string {
}
defer conn.Close()

log.Println("Getting external IP")
log.Info("Getting external IP")
localAddr := conn.LocalAddr().String()
idx := strings.LastIndex(localAddr, ":")

Expand All @@ -90,7 +92,7 @@ func existsConfigPath(path string) bool {
func getMapping(path string) config.Mapping {
path, _ = filepath.Abs(path)
if !existsConfigPath(path) {
log.Fatalln(ErrNotFoundPath.Error())
log.Fatal(ErrNotFoundPath.Error())
}

fsMapper := config.NewFileSystemMapper()
Expand Down Expand Up @@ -196,11 +198,11 @@ func main() {
defer statistics.Stop()

go startServer(*sIP, *sPort, *sPortTLS, *cTLS, done, router, mLog, scenario, varsProcessor, spy)
log.Printf("HTTP Server running at http://%s:%d\n", *sIP, *sPort)
log.Printf("HTTPS Server running at https://%s:%d\n", *sIP, *sPortTLS)
log.Infof("HTTP Server running at http://%s:%d\n", *sIP, *sPort)
log.Infof("HTTPS Server running at https://%s:%d\n", *sIP, *sPortTLS)
if *console {
go startConsole(*cIP, *cPort, *cResultsPerPage, spy, scenario, mapping, done, mLog)
log.Printf("Console running at http://%s:%d\n", *cIP, *cPort)
log.Infof("Console running at http://%s:%d\n", *cIP, *cPort)
}

<-done
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ require (
github.com/kr/pretty v0.2.0 // indirect
github.com/labstack/echo/v4 v4.11.4
github.com/myesui/uuid v1.0.0 // indirect
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7
github.com/radovskyb/watcher v1.0.7
github.com/ryanuber/go-glob v1.0.0
github.com/stathat/go v1.0.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrk
github.com/myesui/uuid v1.0.0 h1:xCBmH4l5KuvLYc5L7AS7SZg9/jKdIFubM7OVoLqaQUI=
github.com/myesui/uuid v1.0.0/go.mod h1:2CDfNgU0LR8mIdO8vdWd8i9gWWxLlcoIGGpSNgafq84=
github.com/ngdinhtoan/glide-cleanup v0.2.0/go.mod h1:UQzsmiDOb8YV3nOsCxK/c9zPpCZVNoHScRE3EO9pVMM=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88=
github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk=
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/radovskyb/watcher v1.0.7 h1:AYePLih6dpmS32vlHfhCeli8127LzkIgwJGcwwe8tUE=
Expand Down
7 changes: 3 additions & 4 deletions internal/config/filesystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"github.com/jmartin82/mmock/v3/pkg/mock"
"io/ioutil"
"log"
"reflect"
"strings"
)
Expand Down Expand Up @@ -66,13 +65,13 @@ func (fd *FSMapper) Read(filename string) (mock.Definition, error) {
if parser.CanParse(filename) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
log.Printf("Invalid mock config in: %s\n", filename)
log.Errorf("Invalid mock config in: %s\n", filename)
return mock.Definition{}, ErrInvalidMockDefinition
}
log.Printf("Loading config file: %s\n", filename)
log.Infof("Loading config file: %s\n", filename)
mock, erd := parser.Parse(buf)
if erd != nil {
log.Printf("Invalid mock format in: %s Err: %s", filename, erd)
log.Errorf("Invalid mock format in: %s Err: %s", filename, erd)
}
if reflect.TypeOf(parser).String() == "parser.YAMLReader" {
if mock.Request.Body != "" {
Expand Down
56 changes: 56 additions & 0 deletions internal/config/logger/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package logger

import (
"github.com/op/go-logging"
"os"
"strings"
)

var Log *logging.Logger

func init() {
var log = logging.MustGetLogger("initialization")
var level logging.Level
var format = logging.MustStringFormatter(
`%{time:15:04:05.000} %{color}%{level:.6s} ▶%{color:reset} %{message}`,
)

var prebackend = logging.NewLogBackend(os.Stdout, "", 0)
var formattedBackend = logging.NewBackendFormatter(prebackend, format)
var backend = logging.AddModuleLevel(formattedBackend)

logLevelEnv, ok := os.LookupEnv("LOG_LEVEL")

if !ok || logLevelEnv == "" {
log.Info("No LOG_LEVEL environment variable found, defaulting to INFO")
level = logging.INFO
} else {
level, ok = ParseStringToLevel(logLevelEnv)
if !ok {
log.Errorf("Invalid log level: %s Defaulting to INFO", logLevelEnv)
level = logging.INFO
} else {
log.Infof("Setting log level to: %s", strings.ToUpper(logLevelEnv))
}
}

backend.SetLevel(level, "mmock")
logging.SetBackend(backend)

Log = logging.MustGetLogger("mmock")
log.Infof("Logger initialized with level: %s", strings.ToUpper(logging.GetLevel("mmock").String()))
}

var levelMap = map[string]logging.Level{
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"NOTICE": logging.NOTICE,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
}

func ParseStringToLevel(str string) (logging.Level, bool) {
level, ok := levelMap[strings.ToUpper(str)]
return level, ok
}
11 changes: 6 additions & 5 deletions internal/config/mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@ package config

import (
"errors"
"log"
"github.com/jmartin82/mmock/v3/internal/config/logger"
"github.com/jmartin82/mmock/v3/pkg/mock"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"

"github.com/jmartin82/mmock/v3/pkg/mock"
)

var log = logger.Log

var ErrFilePathIsNotUnderConfigPath = errors.New("File path is not under config path")
var ErrMockDoesntExist = errors.New("Definition doesn't exist")

Expand Down Expand Up @@ -127,7 +128,7 @@ func (fm *ConfigMapping) populate() {
if !fileInfo.IsDir() {
URI := strings.TrimPrefix(filePath, fm.path)
if err := fm.load(URI); err != nil {
log.Printf("Error %v. Loading config: %v\n", err, URI)
log.Errorf("Error %v. Loading config: %v\n", err, URI)
}
}
return nil
Expand Down Expand Up @@ -162,7 +163,7 @@ func (fm *ConfigMapping) resolveFile(URI string) (string, error) {
}

if !strings.HasPrefix(filename, fm.path) {
log.Printf("File path not under the config path\n")
log.Error("File path not under the config path\n")
return "", ErrFilePathIsNotUnderConfigPath
}
return filename, nil
Expand Down
14 changes: 6 additions & 8 deletions internal/config/watcher.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
package config

import (
"log"
"time"

"github.com/radovskyb/watcher"
"time"
)

// Watcher interface contains the function watching process
Expand Down Expand Up @@ -40,24 +38,24 @@ func (fw *FileWatcher) Bind() {
for {
select {
case event := <-fw.watcher.Event:
log.Println("Changes detected in mock definitions ", event.String())
log.Infof("Changes detected in mock definitions ", event.String())
fw.fsUpdate <- struct{}{}
case err := <-fw.watcher.Error:
log.Println("File monitor error", err)
log.Errorf("File monitor error", err)
}
}
}()

// Watch dir recursively for changes.
if err := fw.watcher.AddRecursive(fw.path); err != nil {
log.Println("Impossible bind the config folder to the files monitor: ", err)
log.Errorf("Impossible bind the config folder to the files monitor: ", err)
return
}

go func() {
log.Println("File monitor started")
log.Info("File monitor started")
if err := fw.watcher.Start(time.Millisecond * 100); err != nil {
log.Println("Impossible to start the config files monitor: ", err)
log.Errorf("Impossible to start the config files monitor: ", err)
}
}()

Expand Down
19 changes: 9 additions & 10 deletions internal/console/dispatcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,22 @@ package console
import (
"errors"
"fmt"
"log"
"net/http"
"regexp"
"strconv"

"strings"

assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/jmartin82/mmock/v3/internal/config"
"github.com/jmartin82/mmock/v3/internal/config/logger"
"github.com/jmartin82/mmock/v3/internal/statistics"
"github.com/jmartin82/mmock/v3/pkg/match"
"github.com/jmartin82/mmock/v3/pkg/mock"

"github.com/jmartin82/mmock/v3/internal/statistics"
"github.com/labstack/echo/v4"
"golang.org/x/net/websocket"
"net/http"
"regexp"
"strconv"
"strings"
)

var log = logger.Log

var pagePattern = regexp.MustCompile(`^[1-9]([0-9]+)?$`)

// ErrInvalidPage the page parameters is invalid
Expand Down Expand Up @@ -351,7 +350,7 @@ func (di *Dispatcher) pageParamToInt(c echo.Context) (int, error) {

page, err := strconv.Atoi(pageParam)
if err != nil {
log.Println(ErrInvalidPage, err)
log.Errorf("%v %v", ErrInvalidPage, err)
return 0, ErrInvalidPage
}

Expand Down
Loading

0 comments on commit 22afc79

Please sign in to comment.