Skip to content

Commit

Permalink
Added tests for sfmt package
Browse files Browse the repository at this point in the history
  • Loading branch information
evg4b committed Jun 1, 2023
1 parent d4cda47 commit 43a6bc4
Show file tree
Hide file tree
Showing 15 changed files with 405 additions and 49 deletions.
13 changes: 7 additions & 6 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package config

import (
fmt "fmt"

"github.com/evg4b/uncors/internal/config/hooks"
"github.com/evg4b/uncors/internal/sfmt"
"github.com/mitchellh/mapstructure"
"github.com/spf13/pflag"
"github.com/spf13/viper"
Expand Down Expand Up @@ -30,11 +31,11 @@ func (config *UncorsConfig) IsHTTPSEnabled() bool {
func LoadConfiguration(viperInstance *viper.Viper, args []string) (*UncorsConfig, error) {
flags := defineFlags()
if err := flags.Parse(args); err != nil {
return nil, sfmt.Errorf("filed parsing flags: %w", err)
return nil, fmt.Errorf("filed parsing flags: %w", err)
}

if err := viperInstance.BindPFlags(flags); err != nil {
return nil, sfmt.Errorf("filed binding flags: %w", err)
return nil, fmt.Errorf("filed binding flags: %w", err)
}

configuration := &UncorsConfig{
Expand All @@ -44,7 +45,7 @@ func LoadConfiguration(viperInstance *viper.Viper, args []string) (*UncorsConfig
if configPath := viperInstance.GetString("config"); len(configPath) > 0 {
viperInstance.SetConfigFile(configPath)
if err := viperInstance.ReadInConfig(); err != nil {
return nil, sfmt.Errorf("filed to read config file '%s': %w", configPath, err)
return nil, fmt.Errorf("filed to read config file '%s': %w", configPath, err)
}
}

Expand All @@ -55,11 +56,11 @@ func LoadConfiguration(viperInstance *viper.Viper, args []string) (*UncorsConfig
))

if err := viperInstance.Unmarshal(configuration, configOption); err != nil {
return nil, sfmt.Errorf("filed parsing config: %w", err)
return nil, fmt.Errorf("filed parsing config: %w", err)
}

if err := readURLMapping(viperInstance, configuration); err != nil {
return nil, sfmt.Errorf("recognize url mapping: %w", err)
return nil, fmt.Errorf("recognize url mapping: %w", err)
}

return configuration, nil
Expand Down
4 changes: 2 additions & 2 deletions internal/config/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package config

import (
"errors"
"fmt"
"net"
"net/url"
"strconv"
"strings"

"github.com/evg4b/uncors/internal/config/hooks"
"github.com/evg4b/uncors/internal/sfmt"
"github.com/evg4b/uncors/pkg/urlx"
"github.com/mitchellh/mapstructure"
"github.com/samber/lo"
Expand Down Expand Up @@ -80,7 +80,7 @@ func NormaliseMappings(mappings Mappings, httpPort, httpsPort int, useHTTPS bool
for _, mapping := range mappings {
sourceURL, err := urlx.Parse(mapping.From)
if err != nil {
return nil, sfmt.Errorf("failed to parse source url: %w", err)
return nil, fmt.Errorf("failed to parse source url: %w", err)
}

if isApplicableScheme(sourceURL.Scheme, httpScheme) {
Expand Down
7 changes: 3 additions & 4 deletions internal/handler/mock/serve_file_content.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
package mock

import (
"fmt"
"net/http"
"os"

"github.com/evg4b/uncors/internal/sfmt"
)

func (m *Middleware) serveFileContent(writer http.ResponseWriter, request *http.Request) error {
fileName := m.response.File
file, err := m.fs.OpenFile(fileName, os.O_RDONLY, os.ModePerm)
if err != nil {
return sfmt.Errorf("filed to opent file %s: %w", fileName, err)
return fmt.Errorf("filed to opent file %s: %w", fileName, err)
}

stat, err := file.Stat()
if err != nil {
return sfmt.Errorf("filed to recive file infirmation: %w", err)
return fmt.Errorf("filed to recive file infirmation: %w", err)
}

http.ServeContent(writer, request, stat.Name(), stat.ModTime(), file)
Expand Down
10 changes: 5 additions & 5 deletions internal/handler/proxy/middleware.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package proxy

import (
"fmt"
"net/http"
"strings"

"github.com/evg4b/uncors/internal/contracts"
"github.com/evg4b/uncors/internal/helpers"
"github.com/evg4b/uncors/internal/infra"
"github.com/evg4b/uncors/internal/sfmt"
"github.com/evg4b/uncors/internal/urlreplacer"
)

Expand Down Expand Up @@ -44,12 +44,12 @@ func (m *Handler) handle(resp http.ResponseWriter, req *http.Request) error {

targetReplacer, sourceReplacer, err := m.replacers.Make(req.URL)
if err != nil {
return sfmt.Errorf("failed to transform general url: %w", err)
return fmt.Errorf("failed to transform general url: %w", err)
}

originalRequest, err := m.makeOriginalRequest(req, targetReplacer)
if err != nil {
return sfmt.Errorf("failed to create reuest to original source: %w", err)
return fmt.Errorf("failed to create reuest to original source: %w", err)
}

originalResponse, err := m.executeQuery(originalRequest)
Expand All @@ -61,7 +61,7 @@ func (m *Handler) handle(resp http.ResponseWriter, req *http.Request) error {

err = m.makeUncorsResponse(originalResponse, resp, sourceReplacer)
if err != nil {
return sfmt.Errorf("failed to make uncors response: %w", err)
return fmt.Errorf("failed to make uncors response: %w", err)
}

return nil
Expand All @@ -70,7 +70,7 @@ func (m *Handler) handle(resp http.ResponseWriter, req *http.Request) error {
func (m *Handler) executeQuery(request *http.Request) (*http.Response, error) {
originalResponse, err := m.http.Do(request)
if err != nil {
return nil, sfmt.Errorf("failed to do reuest: %w", err)
return nil, fmt.Errorf("failed to do reuest: %w", err)
}
m.logger.PrintResponse(originalResponse)

Expand Down
6 changes: 3 additions & 3 deletions internal/handler/proxy/request.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package proxy

import (
"fmt"
"net/http"

"github.com/evg4b/uncors/internal/sfmt"
"github.com/evg4b/uncors/internal/urlreplacer"
"github.com/go-http-utils/headers"
)
Expand All @@ -15,7 +15,7 @@ func (m *Handler) makeOriginalRequest(
url, _ := replacer.Replace(req.URL.String())
originalRequest, err := http.NewRequestWithContext(req.Context(), req.Method, url, req.Body)
if err != nil {
return nil, sfmt.Errorf("failed to make requst to original server: %w", err)
return nil, fmt.Errorf("failed to make requst to original server: %w", err)
}

err = copyHeaders(req.Header, originalRequest.Header, modificationsMap{
Expand All @@ -28,7 +28,7 @@ func (m *Handler) makeOriginalRequest(
}

if err = copyCookiesToTarget(req, replacer, originalRequest); err != nil {
return nil, sfmt.Errorf("failed to copy cookies in request: %w", err)
return nil, fmt.Errorf("failed to copy cookies in request: %w", err)
}

return originalRequest, nil
Expand Down
6 changes: 3 additions & 3 deletions internal/handler/proxy/responce.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package proxy

import (
"fmt"
"io"
"net/http"

"github.com/evg4b/uncors/internal/infra"
"github.com/evg4b/uncors/internal/sfmt"
"github.com/evg4b/uncors/internal/urlreplacer"
"github.com/go-http-utils/headers"
)
Expand All @@ -16,7 +16,7 @@ func (m *Handler) makeUncorsResponse(
replacer *urlreplacer.Replacer,
) error {
if err := copyCookiesToSource(original, replacer, target); err != nil {
return sfmt.Errorf("failed to copy cookies in request: %w", err)
return fmt.Errorf("failed to copy cookies in request: %w", err)
}

err := copyHeaders(original.Header, target.Header(), modificationsMap{
Expand All @@ -35,7 +35,7 @@ func copyResponseData(resp http.ResponseWriter, targetResp *http.Response) error
resp.WriteHeader(targetResp.StatusCode)

if _, err := io.Copy(resp, targetResp.Body); err != nil {
return sfmt.Errorf("failed to copy body to response: %w", err)
return fmt.Errorf("failed to copy body to response: %w", err)
}

return nil
Expand Down
10 changes: 5 additions & 5 deletions internal/handler/static/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package static

import (
"errors"
"fmt"
"io/fs"
"net/http"
"os"
Expand All @@ -11,7 +12,6 @@ import (
"github.com/evg4b/uncors/internal/contracts"
"github.com/evg4b/uncors/internal/helpers"
"github.com/evg4b/uncors/internal/infra"
"github.com/evg4b/uncors/internal/sfmt"
"github.com/spf13/afero"
)

Expand Down Expand Up @@ -67,7 +67,7 @@ func (m *Middleware) openFile(filePath string) (afero.File, os.FileInfo, error)
file, err := m.fs.Open(filePath)
if err != nil {
if !errors.Is(err, fs.ErrNotExist) {
return nil, nil, sfmt.Errorf("filed to open file: %w", err)
return nil, nil, fmt.Errorf("filed to open file: %w", err)
}

indexFile, err := m.openIndexFile()
Expand All @@ -80,7 +80,7 @@ func (m *Middleware) openFile(filePath string) (afero.File, os.FileInfo, error)

stat, err := file.Stat()
if err != nil {
return file, nil, sfmt.Errorf("filed to get information about file: %w", err)
return file, nil, fmt.Errorf("filed to get information about file: %w", err)
}

if stat.IsDir() {
Expand All @@ -91,7 +91,7 @@ func (m *Middleware) openFile(filePath string) (afero.File, os.FileInfo, error)

indexFileStat, err := indexFile.Stat()
if err != nil {
return file, stat, sfmt.Errorf("filed to get information about index file: %w", err)
return file, stat, fmt.Errorf("filed to get information about index file: %w", err)
}

file = indexFile
Expand All @@ -108,7 +108,7 @@ func (m *Middleware) openIndexFile() (afero.File, error) {

file, err := m.fs.Open(m.index)
if err != nil {
return nil, sfmt.Errorf("filed to opend index file: %w", err)
return nil, fmt.Errorf("filed to opend index file: %w", err)
}

return file, nil
Expand Down
4 changes: 2 additions & 2 deletions internal/infra/httpclient.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package infra

import (
"fmt"
"net/http"
"time"

"github.com/evg4b/uncors/internal/sfmt"
"github.com/evg4b/uncors/pkg/urlx"
)

Expand All @@ -25,7 +25,7 @@ func MakeHTTPClient(proxy string) (*http.Client, error) {
if len(proxy) > 0 {
parsedURL, err := urlx.Parse(proxy)
if err != nil {
return nil, sfmt.Errorf("failed to create http client: %w", err)
return nil, fmt.Errorf("failed to create http client: %w", err)
}

httpClient := defaultHTTPClient
Expand Down
7 changes: 0 additions & 7 deletions internal/sfmt/error.go

This file was deleted.

9 changes: 3 additions & 6 deletions internal/sfmt/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ import (
)

func Fprint(w io.Writer, payload ...any) {
_, err := fmt.Fprint(w, payload...)
if err != nil {
if _, err := fmt.Fprint(w, payload...); err != nil {
panic(err)
}
}

func Fprintf(w io.Writer, format string, a ...any) {
_, err := fmt.Fprintf(w, format, a...)
if err != nil {
if _, err := fmt.Fprintf(w, format, a...); err != nil {
panic(err)
}
}
Expand All @@ -24,8 +22,7 @@ func Sprintf(format string, a ...any) string {
}

func Fprintln(w io.Writer, a ...any) {
_, err := fmt.Fprintln(w, a...)
if err != nil {
if _, err := fmt.Fprintln(w, a...); err != nil {
panic(err)
}
}
81 changes: 81 additions & 0 deletions internal/sfmt/print_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package sfmt_test

import (
"strings"
"testing"

"github.com/evg4b/uncors/internal/sfmt"
"github.com/evg4b/uncors/testing/mocks"
"github.com/stretchr/testify/assert"
)

const (
rawPayload = "test-data"
fPayload = "pint f %s %d"
fPayloadExpected = "pint f demo 555"
)

var fPayloadArgs = []any{"demo", 555}

func TestFprint(t *testing.T) {
t.Run("print correctly", func(t *testing.T) {
writer := &strings.Builder{}

sfmt.Fprint(writer, rawPayload)

assert.Equal(t, rawPayload, writer.String())
})

t.Run("panic on error", func(t *testing.T) {
assert.Panics(t, func() {
writer := mocks.NewWriterMock(t).
WriteMock.Return(0, mocks.ErrTest1)

sfmt.Fprint(writer, rawPayload)
})
})
}

func TestFprintf(t *testing.T) {
t.Run("print correctly", func(t *testing.T) {
writer := &strings.Builder{}

sfmt.Fprintf(writer, fPayload, fPayloadArgs...)

assert.Equal(t, fPayloadExpected, writer.String())
})

t.Run("panic on error", func(t *testing.T) {
assert.Panics(t, func() {
writer := mocks.NewWriterMock(t).
WriteMock.Return(0, mocks.ErrTest1)

sfmt.Fprintf(writer, fPayload, fPayloadArgs...)
})
})
}

func TestFprintln(t *testing.T) {
t.Run("print correctly", func(t *testing.T) {
writer := &strings.Builder{}

sfmt.Fprintln(writer, rawPayload)

assert.Equal(t, rawPayload+"\n", writer.String())
})

t.Run("panic on error", func(t *testing.T) {
assert.Panics(t, func() {
writer := mocks.NewWriterMock(t).
WriteMock.Return(0, mocks.ErrTest1)

sfmt.Fprintln(writer, rawPayload)
})
})
}

func TestSprintf(t *testing.T) {
actual := sfmt.Sprintf(fPayload, fPayloadArgs...)

assert.Equal(t, fPayloadExpected, actual)
}
Loading

0 comments on commit 43a6bc4

Please sign in to comment.