prompt
stringlengths 183
7.33M
| completion
stringlengths 13
833k
| __index_level_0__
int64 0
215k
|
---|---|---|
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
//go:generate go-enum --sql --marshal --file $GOFILE
package img
import (
"bytes"
"context"
"errors"
"fmt"
"image"
"io"
"github.com/disintegration/imaging"
"github.com/dsoprea/go-exif/v3"
"github.com/marusama/semaphore/v2"
exifcommon "github.com/dsoprea/go-exif/v3/common"
)
// ErrUnsupportedFormat means the given image format is not supported.
var ErrUnsupportedFormat = errors.New("unsupported image format")
// Service
type Service struct {
sem semaphore.Semaphore
}
func New(workers int) *Service {
return &Service{
sem: semaphore.New(workers),
}
}
// Format is an image file format.
/*
ENUM(
jpeg
png
gif
tiff
bmp
)
*/
type Format int
func (x Format) toImaging() imaging.Format {
switch x {
case FormatJpeg:
return imaging.JPEG
case FormatPng:
return imaging.PNG
case FormatGif:
return imaging.GIF
case FormatTiff:
return imaging.TIFF
case FormatBmp:
return imaging.BMP
default:
return imaging.JPEG
}
}
/*
ENUM(
high
medium
low
)
*/
type Quality int
func (x Quality) resampleFilter() imaging.ResampleFilter {
switch x {
case QualityHigh:
return imaging.Lanczos
case QualityMedium:
return imaging.Box
case QualityLow:
return imaging.NearestNeighbor
default:
return imaging.Box
}
}
/*
ENUM(
fit
fill
)
*/
type ResizeMode int
func (s *Service) FormatFromExtension(ext string) (Format, error) {
format, err := imaging.FormatFromExtension(ext)
if err != nil {
return -1, ErrUnsupportedFormat
}
switch format {
case imaging.JPEG:
return FormatJpeg, nil
case imaging.PNG:
return FormatPng, nil
case imaging.GIF:
return FormatGif, nil
case imaging.TIFF:
return FormatTiff, nil
case imaging.BMP:
return FormatBmp, nil
}
return -1, ErrUnsupportedFormat
}
type resizeConfig struct {
format Format
resizeMode ResizeMode
quality Quality
}
type Option func(*resizeConfig)
func WithFormat(format Format) Option {
return func(config *resizeConfig) {
config.format = format
}
}
func WithMode(mode ResizeMode) Option {
return func(config *resizeConfig) {
config.resizeMode = mode
}
}
func WithQuality(quality Quality) Option {
return func(config *resizeConfig) {
config.quality = quality
}
}
func (s *Service) Resize(ctx context.Context, in io.Reader, width, height int, out io.Writer, options ...Option) error {
if err := s.sem.Acquire(ctx, 1); err != nil {
return err
}
defer s.sem.Release(1)
format, wrappedReader, err := s.detectFormat(in)
if err != nil {
return err
}
config := resizeConfig{
format: format,
resizeMode: ResizeModeFit,
quality: QualityMedium,
}
for _, option := range options {
option(&config)
}
if config.quality == QualityLow && format == FormatJpeg {
thm, newWrappedReader, errThm := getEmbeddedThumbnail(wrappedReader)
wrappedReader = newWrappedReader
if errThm == nil {
_, err = out.Write(thm)
if err == nil {
return nil
}
}
}
img, err := imaging.Decode(wrappedReader, imaging.AutoOrientation(true))
if err != nil {
return err
}
switch config.resizeMode {
case ResizeModeFill:
img = imaging.Fill(img, width, height, imaging.Center, config.quality.resampleFilter())
case ResizeModeFit:
fallthrough //nolint:gocritic
default:
img = imaging.Fit(img, width, height, config.quality.resampleFilter())
}
return imaging.Encode(out, img, config.format.toImaging())
}
func (s *Service) detectFormat(in io.Reader) (Format, io.Reader, error) {
buf := &bytes.Buffer{}
r := io.TeeReader(in, buf)
_, imgFormat, err := image.DecodeConfig(r)
if err != nil {
return 0, nil, fmt.Errorf("%s: %w", err.Error(), ErrUnsupportedFormat)
}
format, err := ParseFormat(imgFormat)
if err != nil {
return 0, nil, ErrUnsupportedFormat
}
return format, io.MultiReader(buf, in), nil
}
func getEmbeddedThumbnail(in io.Reader) ([]byte, io.Reader, error) {
buf := &bytes.Buffer{}
r := io.TeeReader(in, buf)
wrappedReader := io.MultiReader(buf, in)
offset := 0
offsets := []int{12, 30}
head := make([]byte, 0xffff) //nolint:gomnd
_, err := r.Read(head)
if err != nil {
return nil, wrappedReader, err
}
for _, offset = range offsets {
if _, err = exif.ParseExifHeader(head[offset:]); err == nil {
break
}
}
if err != nil {
return nil, wrappedReader, err
}
im, err := exifcommon.NewIfdMappingWithStandard()
if err != nil {
return nil, wrappedReader, err
}
_, index, err := exif.Collect(im, exif.NewTagIndex(), head[offset:])
if err != nil {
return nil, wrappedReader, err
}
ifd := index.RootIfd.NextIfd()
if ifd == nil {
return nil, wrappedReader, exif.ErrNoThumbnail
}
thm, err := ifd.Thumbnail()
return thm, wrappedReader, err
}
| package img
import (
"bytes"
"context"
"errors"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
"golang.org/x/image/bmp"
"golang.org/x/image/tiff"
)
func TestService_Resize(t *testing.T) {
testCases := map[string]struct {
options []Option
width int
height int
source func(t *testing.T) afero.File
matcher func(t *testing.T, reader io.Reader)
wantErr bool
}{
"fill upscale": {
options: []Option{WithMode(ResizeModeFill)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 50, 20)
},
matcher: sizeMatcher(100, 100),
},
"fill downscale": {
options: []Option{WithMode(ResizeModeFill)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"fit upscale": {
options: []Option{WithMode(ResizeModeFit)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 50, 20)
},
matcher: sizeMatcher(50, 20),
},
"fit downscale": {
options: []Option{WithMode(ResizeModeFit)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: sizeMatcher(100, 75),
},
"keep original format": {
options: []Option{},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayPng(t, 200, 150)
},
matcher: formatMatcher(FormatPng),
},
"convert to jpeg": {
options: []Option{WithFormat(FormatJpeg)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: formatMatcher(FormatJpeg),
},
"convert to png": {
options: []Option{WithFormat(FormatPng)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: formatMatcher(FormatPng),
},
"convert to gif": {
options: []Option{WithFormat(FormatGif)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: formatMatcher(FormatGif),
},
"convert to tiff": {
options: []Option{WithFormat(FormatTiff)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: formatMatcher(FormatTiff),
},
"convert to bmp": {
options: []Option{WithFormat(FormatBmp)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: formatMatcher(FormatBmp),
},
"convert to unknown": {
options: []Option{WithFormat(Format(-1))},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: formatMatcher(FormatJpeg),
},
"resize png": {
options: []Option{WithMode(ResizeModeFill)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayPng(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"resize gif": {
options: []Option{WithMode(ResizeModeFill)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayGif(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"resize tiff": {
options: []Option{WithMode(ResizeModeFill)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayTiff(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"resize bmp": {
options: []Option{WithMode(ResizeModeFill)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayBmp(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"resize with high quality": {
options: []Option{WithMode(ResizeModeFill), WithQuality(QualityHigh)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"resize with medium quality": {
options: []Option{WithMode(ResizeModeFill), WithQuality(QualityMedium)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"resize with low quality": {
options: []Option{WithMode(ResizeModeFill), WithQuality(QualityLow)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"resize with unknown quality": {
options: []Option{WithMode(ResizeModeFill), WithQuality(Quality(-1))},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return newGrayJpeg(t, 200, 150)
},
matcher: sizeMatcher(100, 100),
},
"get thumbnail from file with APP0 JFIF": {
options: []Option{WithMode(ResizeModeFill), WithQuality(QualityLow)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return openFile(t, "testdata/gray-sample.jpg")
},
matcher: sizeMatcher(125, 128),
},
"get thumbnail from file without APP0 JFIF": {
options: []Option{WithMode(ResizeModeFill), WithQuality(QualityLow)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return openFile(t, "testdata/20130612_142406.jpg")
},
matcher: sizeMatcher(320, 240),
},
"resize from file without IFD1 thumbnail": {
options: []Option{WithMode(ResizeModeFill), WithQuality(QualityLow)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return openFile(t, "testdata/IMG_2578.JPG")
},
matcher: sizeMatcher(100, 100),
},
"resize for higher quality levels": {
options: []Option{WithMode(ResizeModeFill), WithQuality(QualityMedium)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
return openFile(t, "testdata/gray-sample.jpg")
},
matcher: sizeMatcher(100, 100),
},
"broken file": {
options: []Option{WithMode(ResizeModeFit)},
width: 100,
height: 100,
source: func(t *testing.T) afero.File {
t.Helper()
fs := afero.NewMemMapFs()
file, err := fs.Create("image.jpg")
require.NoError(t, err)
_, err = file.WriteString("this is not an image")
require.NoError(t, err)
return file
},
wantErr: true,
},
}
for name, test := range testCases {
t.Run(name, func(t *testing.T) {
svc := New(1)
source := test.source(t)
defer source.Close()
buf := &bytes.Buffer{}
err := svc.Resize(context.Background(), source, test.width, test.height, buf, test.options...)
if (err != nil) != test.wantErr {
t.Fatalf("GetMarketSpecs() error = %v, wantErr %v", err, test.wantErr)
}
if err != nil {
return
}
test.matcher(t, buf)
})
}
}
func sizeMatcher(width, height int) func(t *testing.T, reader io.Reader) {
return func(t *testing.T, reader io.Reader) {
resizedImg, _, err := image.Decode(reader)
require.NoError(t, err)
require.Equal(t, width, resizedImg.Bounds().Dx())
require.Equal(t, height, resizedImg.Bounds().Dy())
}
}
func formatMatcher(format Format) func(t *testing.T, reader io.Reader) {
return func(t *testing.T, reader io.Reader) {
_, decodedFormat, err := image.DecodeConfig(reader)
require.NoError(t, err)
require.Equal(t, format.String(), decodedFormat)
}
}
func newGrayJpeg(t *testing.T, width, height int) afero.File {
fs := afero.NewMemMapFs()
file, err := fs.Create("image.jpg")
require.NoError(t, err)
img := image.NewGray(image.Rect(0, 0, width, height))
err = jpeg.Encode(file, img, &jpeg.Options{Quality: 90})
require.NoError(t, err)
_, err = file.Seek(0, io.SeekStart)
require.NoError(t, err)
return file
}
func newGrayPng(t *testing.T, width, height int) afero.File {
fs := afero.NewMemMapFs()
file, err := fs.Create("image.png")
require.NoError(t, err)
img := image.NewGray(image.Rect(0, 0, width, height))
err = png.Encode(file, img)
require.NoError(t, err)
_, err = file.Seek(0, io.SeekStart)
require.NoError(t, err)
return file
}
func newGrayGif(t *testing.T, width, height int) afero.File {
fs := afero.NewMemMapFs()
file, err := fs.Create("image.gif")
require.NoError(t, err)
img := image.NewGray(image.Rect(0, 0, width, height))
err = gif.Encode(file, img, nil)
require.NoError(t, err)
_, err = file.Seek(0, io.SeekStart)
require.NoError(t, err)
return file
}
func newGrayTiff(t *testing.T, width, height int) afero.File {
fs := afero.NewMemMapFs()
file, err := fs.Create("image.tiff")
require.NoError(t, err)
img := image.NewGray(image.Rect(0, 0, width, height))
err = tiff.Encode(file, img, nil)
require.NoError(t, err)
_, err = file.Seek(0, io.SeekStart)
require.NoError(t, err)
return file
}
func newGrayBmp(t *testing.T, width, height int) afero.File {
fs := afero.NewMemMapFs()
file, err := fs.Create("image.bmp")
require.NoError(t, err)
img := image.NewGray(image.Rect(0, 0, width, height))
err = bmp.Encode(file, img)
require.NoError(t, err)
_, err = file.Seek(0, io.SeekStart)
require.NoError(t, err)
return file
}
func openFile(t *testing.T, name string) afero.File {
appfs := afero.NewOsFs()
file, err := appfs.Open(name)
require.NoError(t, err)
return file
}
func TestService_FormatFromExtension(t *testing.T) {
testCases := map[string]struct {
ext string
want Format
wantErr error
}{
"jpg": {
ext: ".jpg",
want: FormatJpeg,
},
"jpeg": {
ext: ".jpeg",
want: FormatJpeg,
},
"png": {
ext: ".png",
want: FormatPng,
},
"gif": {
ext: ".gif",
want: FormatGif,
},
"tiff": {
ext: ".tiff",
want: FormatTiff,
},
"bmp": {
ext: ".bmp",
want: FormatBmp,
},
"unknown": {
ext: ".mov",
wantErr: ErrUnsupportedFormat,
},
}
for name, test := range testCases {
t.Run(name, func(t *testing.T) {
svc := New(1)
got, err := svc.FormatFromExtension(test.ext)
require.Truef(t, errors.Is(err, test.wantErr), "error = %v, wantErr %v", err, test.wantErr)
if err != nil {
return
}
require.Equal(t, test.want, got)
})
}
}
| 0 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package diskcache
import (
"context"
"crypto/sha1" //nolint:gosec
"encoding/hex"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"sync"
"github.com/spf13/afero"
)
type FileCache struct {
fs afero.Fs
// granular locks
scopedLocks struct {
sync.Mutex
sync.Once
locks map[string]sync.Locker
}
}
func New(fs afero.Fs, root string) *FileCache {
return &FileCache{
fs: afero.NewBasePathFs(fs, root),
}
}
func (f *FileCache) Store(ctx context.Context, key string, value []byte) error {
mu := f.getScopedLocks(key)
mu.Lock()
defer mu.Unlock()
fileName := f.getFileName(key)
if err := f.fs.MkdirAll(filepath.Dir(fileName), 0700); err != nil { //nolint:gomnd
return err
}
if err := afero.WriteFile(f.fs, fileName, value, 0700); err != nil { //nolint:gomnd
return err
}
return nil
}
func (f *FileCache) Load(ctx context.Context, key string) (value []byte, exist bool, err error) {
r, ok, err := f.open(key)
if err != nil || !ok {
return nil, ok, err
}
defer r.Close()
value, err = io.ReadAll(r)
if err != nil {
return nil, false, err
}
return value, true, nil
}
func (f *FileCache) Delete(ctx context.Context, key string) error {
mu := f.getScopedLocks(key)
mu.Lock()
defer mu.Unlock()
fileName := f.getFileName(key)
if err := f.fs.Remove(fileName); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
func (f *FileCache) open(key string) (afero.File, bool, error) {
fileName := f.getFileName(key)
file, err := f.fs.Open(fileName)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, false, nil
}
return nil, false, err
}
return file, true, nil
}
// getScopedLocks pull lock from the map if found or create a new one
func (f *FileCache) getScopedLocks(key string) (lock sync.Locker) {
f.scopedLocks.Do(func() { f.scopedLocks.locks = map[string]sync.Locker{} })
f.scopedLocks.Lock()
lock, ok := f.scopedLocks.locks[key]
if !ok {
lock = &sync.Mutex{}
f.scopedLocks.locks[key] = lock
}
f.scopedLocks.Unlock()
return lock
}
func (f *FileCache) getFileName(key string) string {
hasher := sha1.New() //nolint:gosec
_, _ = hasher.Write([]byte(key))
hash := hex.EncodeToString(hasher.Sum(nil))
return fmt.Sprintf("%s/%s/%s", hash[:1], hash[1:3], hash)
}
| package diskcache
import (
"context"
"path/filepath"
"testing"
"github.com/spf13/afero"
"github.com/stretchr/testify/require"
)
func TestFileCache(t *testing.T) {
ctx := context.Background()
const (
key = "key"
value = "some text"
newValue = "new text"
cacheRoot = "/cache"
cachedFilePath = "a/62/a62f2225bf70bfaccbc7f1ef2a397836717377de"
)
fs := afero.NewMemMapFs()
cache := New(fs, "/cache")
// store new key
err := cache.Store(ctx, key, []byte(value))
require.NoError(t, err)
checkValue(t, ctx, fs, filepath.Join(cacheRoot, cachedFilePath), cache, key, value)
// update existing key
err = cache.Store(ctx, key, []byte(newValue))
require.NoError(t, err)
checkValue(t, ctx, fs, filepath.Join(cacheRoot, cachedFilePath), cache, key, newValue)
// delete key
err = cache.Delete(ctx, key)
require.NoError(t, err)
exists, err := afero.Exists(fs, filepath.Join(cacheRoot, cachedFilePath))
require.NoError(t, err)
require.False(t, exists)
}
func checkValue(t *testing.T, ctx context.Context, fs afero.Fs, fileFullPath string, cache *FileCache, key, wantValue string) { //nolint:golint
t.Helper()
// check actual file content
b, err := afero.ReadFile(fs, fileFullPath)
require.NoError(t, err)
require.Equal(t, wantValue, string(b))
// check cache content
b, ok, err := cache.Load(ctx, key)
require.NoError(t, err)
require.True(t, ok)
require.Equal(t, wantValue, string(b))
}
| 1 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package rules
import (
"path/filepath"
"regexp"
"strings"
)
// Checker is a Rules checker.
type Checker interface {
Check(path string) bool
}
// Rule is a allow/disallow rule.
type Rule struct {
Regex bool `json:"regex"`
Allow bool `json:"allow"`
Path string `json:"path"`
Regexp *Regexp `json:"regexp"`
}
// MatchHidden matches paths with a basename
// that begins with a dot.
func MatchHidden(path string) bool {
return path != "" && strings.HasPrefix(filepath.Base(path), ".")
}
// Matches matches a path against a rule.
func (r *Rule) Matches(path string) bool {
if r.Regex {
return r.Regexp.MatchString(path)
}
return strings.HasPrefix(path, r.Path)
}
// Regexp is a wrapper to the native regexp type where we
// save the raw expression.
type Regexp struct {
Raw string `json:"raw"`
regexp *regexp.Regexp
}
// MatchString checks if a string matches the regexp.
func (r *Regexp) MatchString(s string) bool {
if r.regexp == nil {
r.regexp = regexp.MustCompile(r.Raw)
}
return r.regexp.MatchString(s)
}
| package rules
import "testing"
func TestMatchHidden(t *testing.T) {
cases := map[string]bool{
"/": false,
"/src": false,
"/src/": false,
"/.circleci": true,
"/a/b/c/.docker.json": true,
".docker.json": true,
"Dockerfile": false,
"/Dockerfile": false,
}
for path, want := range cases {
got := MatchHidden(path)
if got != want {
t.Errorf("MatchHidden(%s)=%v; want %v", path, got, want)
}
}
}
| 2 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/filebrowser/filebrowser/v2/rules"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/storage"
"github.com/filebrowser/filebrowser/v2/users"
)
func init() {
rootCmd.AddCommand(rulesCmd)
rulesCmd.PersistentFlags().StringP("username", "u", "", "username of user to which the rules apply")
rulesCmd.PersistentFlags().UintP("id", "i", 0, "id of user to which the rules apply")
}
var rulesCmd = &cobra.Command{
Use: "rules",
Short: "Rules management utility",
Long: `On each subcommand you'll have available at least two flags:
"username" and "id". You must either set only one of them
or none. If you set one of them, the command will apply to
an user, otherwise it will be applied to the global set or
rules.`,
Args: cobra.NoArgs,
}
func runRules(st *storage.Storage, cmd *cobra.Command, usersFn func(*users.User), globalFn func(*settings.Settings)) {
id := getUserIdentifier(cmd.Flags())
if id != nil {
user, err := st.Users.Get("", id)
checkErr(err)
if usersFn != nil {
usersFn(user)
}
printRules(user.Rules, id)
return
}
s, err := st.Settings.Get()
checkErr(err)
if globalFn != nil {
globalFn(s)
}
printRules(s.Rules, id)
}
func getUserIdentifier(flags *pflag.FlagSet) interface{} {
id := mustGetUint(flags, "id")
username := mustGetString(flags, "username")
if id != 0 {
return id
} else if username != "" {
return username
}
return nil
}
func printRules(rulez []rules.Rule, id interface{}) {
if id == nil {
fmt.Printf("Global Rules:\n\n")
} else {
fmt.Printf("Rules for user %v:\n\n", id)
}
for id, rule := range rulez {
fmt.Printf("(%d) ", id)
if rule.Regex {
if rule.Allow {
fmt.Printf("Allow Regex: \t%s\n", rule.Regexp.Raw)
} else {
fmt.Printf("Disallow Regex: \t%s\n", rule.Regexp.Raw)
}
} else {
if rule.Allow {
fmt.Printf("Allow Path: \t%s\n", rule.Path)
} else {
fmt.Printf("Disallow Path: \t%s\n", rule.Path)
}
}
}
}
| package rules
import "testing"
func TestMatchHidden(t *testing.T) {
cases := map[string]bool{
"/": false,
"/src": false,
"/src/": false,
"/.circleci": true,
"/a/b/c/.docker.json": true,
".docker.json": true,
"Dockerfile": false,
"/Dockerfile": false,
}
for path, want := range cases {
got := MatchHidden(path)
if got != want {
t.Errorf("MatchHidden(%s)=%v; want %v", path, got, want)
}
}
}
| 3 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2015 Light Code Labs, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runner
import (
"errors"
"runtime"
"unicode"
"github.com/flynn/go-shlex"
)
const (
osWindows = "windows"
osLinux = "linux"
)
var runtimeGoos = runtime.GOOS
// SplitCommandAndArgs takes a command string and parses it shell-style into the
// command and its separate arguments.
func SplitCommandAndArgs(command string) (cmd string, args []string, err error) {
var parts []string
if runtimeGoos == osWindows {
parts = parseWindowsCommand(command) // parse it Windows-style
} else {
parts, err = parseUnixCommand(command) // parse it Unix-style
if err != nil {
err = errors.New("error parsing command: " + err.Error())
return
}
}
if len(parts) == 0 {
err = errors.New("no command contained in '" + command + "'")
return
}
cmd = parts[0]
if len(parts) > 1 {
args = parts[1:]
}
return
}
// parseUnixCommand parses a unix style command line and returns the
// command and its arguments or an error
func parseUnixCommand(cmd string) ([]string, error) {
return shlex.Split(cmd)
}
// parseWindowsCommand parses windows command lines and
// returns the command and the arguments as an array. It
// should be able to parse commonly used command lines.
// Only basic syntax is supported:
// - spaces in double quotes are not token delimiters
// - double quotes are escaped by either backspace or another double quote
// - except for the above case backspaces are path separators (not special)
//
// Many sources point out that escaping quotes using backslash can be unsafe.
// Use two double quotes when possible. (Source: http://stackoverflow.com/a/31413730/2616179 )
//
// This function has to be used on Windows instead
// of the shlex package because this function treats backslash
// characters properly.
func parseWindowsCommand(cmd string) []string {
const backslash = '\\'
const quote = '"'
var parts []string
var part string
var inQuotes bool
var lastRune rune
for i, ch := range cmd {
if i != 0 {
lastRune = rune(cmd[i-1])
}
if ch == backslash {
// put it in the part - for now we don't know if it's an
// escaping char or path separator
part += string(ch)
continue
}
if ch == quote {
if lastRune == backslash {
// remove the backslash from the part and add the escaped quote instead
part = part[:len(part)-1]
part += string(ch)
continue
}
if lastRune == quote {
// revert the last change of the inQuotes state
// it was an escaping quote
inQuotes = !inQuotes
part += string(ch)
continue
}
// normal escaping quotes
inQuotes = !inQuotes
continue
}
if unicode.IsSpace(ch) && !inQuotes && len(part) > 0 {
parts = append(parts, part)
part = ""
continue
}
part += string(ch)
}
if len(part) > 0 {
parts = append(parts, part)
}
return parts
}
| // Copyright 2015 Light Code Labs, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runner
import (
"fmt"
"runtime"
"strings"
"testing"
)
func TestParseUnixCommand(t *testing.T) {
tests := []struct {
input string
expected []string
}{
// 0 - empty command
{
input: ``,
expected: []string{},
},
// 1 - command without arguments
{
input: `command`,
expected: []string{`command`},
},
// 2 - command with single argument
{
input: `command arg1`,
expected: []string{`command`, `arg1`},
},
// 3 - command with multiple arguments
{
input: `command arg1 arg2`,
expected: []string{`command`, `arg1`, `arg2`},
},
// 4 - command with single argument with space character - in quotes
{
input: `command "arg1 arg1"`,
expected: []string{`command`, `arg1 arg1`},
},
// 5 - command with multiple spaces and tab character
{
input: "command arg1 arg2\targ3",
expected: []string{`command`, `arg1`, `arg2`, `arg3`},
},
// 6 - command with single argument with space character - escaped with backspace
{
input: `command arg1\ arg2`,
expected: []string{`command`, `arg1 arg2`},
},
// 7 - single quotes should escape special chars
{
input: `command 'arg1\ arg2'`,
expected: []string{`command`, `arg1\ arg2`},
},
}
for i, test := range tests {
errorPrefix := fmt.Sprintf("Test [%d]: ", i)
errorSuffix := fmt.Sprintf(" Command to parse: [%s]", test.input)
actual, _ := parseUnixCommand(test.input)
if len(actual) != len(test.expected) {
t.Errorf(errorPrefix+"Expected %d parts, got %d: %#v."+errorSuffix, len(test.expected), len(actual), actual)
continue
}
for j := 0; j < len(actual); j++ {
if expectedPart, actualPart := test.expected[j], actual[j]; expectedPart != actualPart {
t.Errorf(errorPrefix+"Expected: %v Actual: %v (index %d)."+errorSuffix, expectedPart, actualPart, j)
}
}
}
}
func TestParseWindowsCommand(t *testing.T) {
tests := []struct {
input string
expected []string
}{
{ // 0 - empty command - do not fail
input: ``,
expected: []string{},
},
{ // 1 - cmd without args
input: `cmd`,
expected: []string{`cmd`},
},
{ // 2 - multiple args
input: `cmd arg1 arg2`,
expected: []string{`cmd`, `arg1`, `arg2`},
},
{ // 3 - multiple args with space
input: `cmd "combined arg" arg2`,
expected: []string{`cmd`, `combined arg`, `arg2`},
},
{ // 4 - path without spaces
input: `mkdir C:\Windows\foo\bar`,
expected: []string{`mkdir`, `C:\Windows\foo\bar`},
},
{ // 5 - command with space in quotes
input: `"command here"`,
expected: []string{`command here`},
},
{ // 6 - argument with escaped quotes (two quotes)
input: `cmd ""arg""`,
expected: []string{`cmd`, `"arg"`},
},
{ // 7 - argument with escaped quotes (backslash)
input: `cmd \"arg\"`,
expected: []string{`cmd`, `"arg"`},
},
{ // 8 - two quotes (escaped) inside an inQuote element
input: `cmd "a ""quoted value"`,
expected: []string{`cmd`, `a "quoted value`},
},
// TODO - see how many quotes are displayed if we use "", """, """""""
{ // 9 - two quotes outside an inQuote element
input: `cmd a ""quoted value`,
expected: []string{`cmd`, `a`, `"quoted`, `value`},
},
{ // 10 - path with space in quotes
input: `mkdir "C:\directory name\foobar"`,
expected: []string{`mkdir`, `C:\directory name\foobar`},
},
{ // 11 - space without quotes
input: `mkdir C:\ space`,
expected: []string{`mkdir`, `C:\`, `space`},
},
{ // 12 - space in quotes
input: `mkdir "C:\ space"`,
expected: []string{`mkdir`, `C:\ space`},
},
{ // 13 - UNC
input: `mkdir \\?\C:\Users`,
expected: []string{`mkdir`, `\\?\C:\Users`},
},
{ // 14 - UNC with space
input: `mkdir "\\?\C:\Program Files"`,
expected: []string{`mkdir`, `\\?\C:\Program Files`},
},
{ // 15 - unclosed quotes - treat as if the path ends with quote
input: `mkdir "c:\Program files`,
expected: []string{`mkdir`, `c:\Program files`},
},
{ // 16 - quotes used inside the argument
input: `mkdir "c:\P"rogra"m f"iles`,
expected: []string{`mkdir`, `c:\Program files`},
},
}
for i, test := range tests {
errorPrefix := fmt.Sprintf("Test [%d]: ", i)
errorSuffix := fmt.Sprintf(" Command to parse: [%s]", test.input)
actual := parseWindowsCommand(test.input)
if len(actual) != len(test.expected) {
t.Errorf(errorPrefix+"Expected %d parts, got %d: %#v."+errorSuffix, len(test.expected), len(actual), actual)
continue
}
for j := 0; j < len(actual); j++ {
if expectedPart, actualPart := test.expected[j], actual[j]; expectedPart != actualPart {
t.Errorf(errorPrefix+"Expected: %v Actual: %v (index %d)."+errorSuffix, expectedPart, actualPart, j)
}
}
}
}
func TestSplitCommandAndArgs(t *testing.T) {
// force linux parsing. It's more robust and covers error cases
runtimeGoos = osLinux
defer func() {
runtimeGoos = runtime.GOOS
}()
var parseErrorContent = "error parsing command:"
var noCommandErrContent = "no command contained in"
tests := []struct {
input string
expectedCommand string
expectedArgs []string
expectedErrContent string
}{
// 0 - empty command
{
input: ``,
expectedCommand: ``,
expectedArgs: nil,
expectedErrContent: noCommandErrContent,
},
// 1 - command without arguments
{
input: `command`,
expectedCommand: `command`,
expectedArgs: nil,
expectedErrContent: ``,
},
// 2 - command with single argument
{
input: `command arg1`,
expectedCommand: `command`,
expectedArgs: []string{`arg1`},
expectedErrContent: ``,
},
// 3 - command with multiple arguments
{
input: `command arg1 arg2`,
expectedCommand: `command`,
expectedArgs: []string{`arg1`, `arg2`},
expectedErrContent: ``,
},
// 4 - command with unclosed quotes
{
input: `command "arg1 arg2`,
expectedCommand: "",
expectedArgs: nil,
expectedErrContent: parseErrorContent,
},
// 5 - command with unclosed quotes
{
input: `command 'arg1 arg2"`,
expectedCommand: "",
expectedArgs: nil,
expectedErrContent: parseErrorContent,
},
}
for i, test := range tests {
errorPrefix := fmt.Sprintf("Test [%d]: ", i)
errorSuffix := fmt.Sprintf(" Command to parse: [%s]", test.input)
actualCommand, actualArgs, actualErr := SplitCommandAndArgs(test.input)
// test if error matches expectation
if test.expectedErrContent != "" {
if actualErr == nil {
t.Errorf(errorPrefix+"Expected error with content [%s], found no error."+errorSuffix, test.expectedErrContent)
} else if !strings.Contains(actualErr.Error(), test.expectedErrContent) {
t.Errorf(errorPrefix+"Expected error with content [%s], found [%v]."+errorSuffix, test.expectedErrContent, actualErr)
}
} else if actualErr != nil {
t.Errorf(errorPrefix+"Expected no error, found [%v]."+errorSuffix, actualErr)
}
// test if command matches
if test.expectedCommand != actualCommand {
t.Errorf(errorPrefix+"Expected command: [%s], actual: [%s]."+errorSuffix, test.expectedCommand, actualCommand)
}
// test if arguments match
if len(test.expectedArgs) != len(actualArgs) {
t.Errorf(errorPrefix+"Wrong number of arguments! Expected [%v], actual [%v]."+errorSuffix, test.expectedArgs, actualArgs)
} else {
// test args only if the count matches.
for j, actualArg := range actualArgs {
expectedArg := test.expectedArgs[j]
if actualArg != expectedArg {
t.Errorf(errorPrefix+"Argument at position [%d] differ! Expected [%s], actual [%s]"+errorSuffix, j, expectedArg, actualArg)
}
}
}
}
}
func ExampleSplitCommandAndArgs() {
var commandLine string
var command string
var args []string
// just for the test - change GOOS and reset it at the end of the test
runtimeGoos = osWindows
defer func() {
runtimeGoos = runtime.GOOS
}()
commandLine = `mkdir /P "C:\Program Files"`
command, args, _ = SplitCommandAndArgs(commandLine)
fmt.Printf("Windows: %s: %s [%s]\n", commandLine, command, strings.Join(args, ","))
// set GOOS to linux
runtimeGoos = osLinux
commandLine = `mkdir -p /path/with\ space`
command, args, _ = SplitCommandAndArgs(commandLine)
fmt.Printf("Linux: %s: %s [%s]\n", commandLine, command, strings.Join(args, ","))
// Output:
// Windows: mkdir /P "C:\Program Files": mkdir [/P,C:\Program Files]
// Linux: mkdir -p /path/with\ space: mkdir [-p,/path/with space]
}
| 4 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package http
import (
"bufio"
"io"
"log"
"net/http"
"os/exec"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/filebrowser/filebrowser/v2/runner"
)
const (
WSWriteDeadline = 10 * time.Second
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
var (
cmdNotAllowed = []byte("Command not allowed.")
)
//nolint:unparam
func wsErr(ws *websocket.Conn, r *http.Request, status int, err error) {
txt := http.StatusText(status)
if err != nil || status >= 400 {
log.Printf("%s: %v %s %v", r.URL.Path, status, r.RemoteAddr, err)
}
if err := ws.WriteControl(websocket.CloseInternalServerErr, []byte(txt), time.Now().Add(WSWriteDeadline)); err != nil {
log.Print(err)
}
}
var commandsHandler = withUser(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return http.StatusInternalServerError, err
}
defer conn.Close()
var raw string
for {
_, msg, err := conn.ReadMessage() //nolint:govet
if err != nil {
wsErr(conn, r, http.StatusInternalServerError, err)
return 0, nil
}
raw = strings.TrimSpace(string(msg))
if raw != "" {
break
}
}
command, err := runner.ParseCommand(d.settings, raw)
if err != nil {
if err := conn.WriteMessage(websocket.TextMessage, []byte(err.Error())); err != nil { //nolint:govet
wsErr(conn, r, http.StatusInternalServerError, err)
}
return 0, nil
}
if !d.server.EnableExec || !d.user.CanExecute(command[0]) {
if err := conn.WriteMessage(websocket.TextMessage, cmdNotAllowed); err != nil { //nolint:govet
wsErr(conn, r, http.StatusInternalServerError, err)
}
return 0, nil
}
cmd := exec.Command(command[0], command[1:]...) //nolint:gosec
cmd.Dir = d.user.FullPath(r.URL.Path)
stdout, err := cmd.StdoutPipe()
if err != nil {
wsErr(conn, r, http.StatusInternalServerError, err)
return 0, nil
}
stderr, err := cmd.StderrPipe()
if err != nil {
wsErr(conn, r, http.StatusInternalServerError, err)
return 0, nil
}
if err := cmd.Start(); err != nil {
wsErr(conn, r, http.StatusInternalServerError, err)
return 0, nil
}
s := bufio.NewScanner(io.MultiReader(stdout, stderr))
for s.Scan() {
if err := conn.WriteMessage(websocket.TextMessage, s.Bytes()); err != nil {
log.Print(err)
}
}
if err := cmd.Wait(); err != nil {
wsErr(conn, r, http.StatusInternalServerError, err)
}
return 0, nil
})
| // Copyright 2015 Light Code Labs, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package runner
import (
"fmt"
"runtime"
"strings"
"testing"
)
func TestParseUnixCommand(t *testing.T) {
tests := []struct {
input string
expected []string
}{
// 0 - empty command
{
input: ``,
expected: []string{},
},
// 1 - command without arguments
{
input: `command`,
expected: []string{`command`},
},
// 2 - command with single argument
{
input: `command arg1`,
expected: []string{`command`, `arg1`},
},
// 3 - command with multiple arguments
{
input: `command arg1 arg2`,
expected: []string{`command`, `arg1`, `arg2`},
},
// 4 - command with single argument with space character - in quotes
{
input: `command "arg1 arg1"`,
expected: []string{`command`, `arg1 arg1`},
},
// 5 - command with multiple spaces and tab character
{
input: "command arg1 arg2\targ3",
expected: []string{`command`, `arg1`, `arg2`, `arg3`},
},
// 6 - command with single argument with space character - escaped with backspace
{
input: `command arg1\ arg2`,
expected: []string{`command`, `arg1 arg2`},
},
// 7 - single quotes should escape special chars
{
input: `command 'arg1\ arg2'`,
expected: []string{`command`, `arg1\ arg2`},
},
}
for i, test := range tests {
errorPrefix := fmt.Sprintf("Test [%d]: ", i)
errorSuffix := fmt.Sprintf(" Command to parse: [%s]", test.input)
actual, _ := parseUnixCommand(test.input)
if len(actual) != len(test.expected) {
t.Errorf(errorPrefix+"Expected %d parts, got %d: %#v."+errorSuffix, len(test.expected), len(actual), actual)
continue
}
for j := 0; j < len(actual); j++ {
if expectedPart, actualPart := test.expected[j], actual[j]; expectedPart != actualPart {
t.Errorf(errorPrefix+"Expected: %v Actual: %v (index %d)."+errorSuffix, expectedPart, actualPart, j)
}
}
}
}
func TestParseWindowsCommand(t *testing.T) {
tests := []struct {
input string
expected []string
}{
{ // 0 - empty command - do not fail
input: ``,
expected: []string{},
},
{ // 1 - cmd without args
input: `cmd`,
expected: []string{`cmd`},
},
{ // 2 - multiple args
input: `cmd arg1 arg2`,
expected: []string{`cmd`, `arg1`, `arg2`},
},
{ // 3 - multiple args with space
input: `cmd "combined arg" arg2`,
expected: []string{`cmd`, `combined arg`, `arg2`},
},
{ // 4 - path without spaces
input: `mkdir C:\Windows\foo\bar`,
expected: []string{`mkdir`, `C:\Windows\foo\bar`},
},
{ // 5 - command with space in quotes
input: `"command here"`,
expected: []string{`command here`},
},
{ // 6 - argument with escaped quotes (two quotes)
input: `cmd ""arg""`,
expected: []string{`cmd`, `"arg"`},
},
{ // 7 - argument with escaped quotes (backslash)
input: `cmd \"arg\"`,
expected: []string{`cmd`, `"arg"`},
},
{ // 8 - two quotes (escaped) inside an inQuote element
input: `cmd "a ""quoted value"`,
expected: []string{`cmd`, `a "quoted value`},
},
// TODO - see how many quotes are displayed if we use "", """, """""""
{ // 9 - two quotes outside an inQuote element
input: `cmd a ""quoted value`,
expected: []string{`cmd`, `a`, `"quoted`, `value`},
},
{ // 10 - path with space in quotes
input: `mkdir "C:\directory name\foobar"`,
expected: []string{`mkdir`, `C:\directory name\foobar`},
},
{ // 11 - space without quotes
input: `mkdir C:\ space`,
expected: []string{`mkdir`, `C:\`, `space`},
},
{ // 12 - space in quotes
input: `mkdir "C:\ space"`,
expected: []string{`mkdir`, `C:\ space`},
},
{ // 13 - UNC
input: `mkdir \\?\C:\Users`,
expected: []string{`mkdir`, `\\?\C:\Users`},
},
{ // 14 - UNC with space
input: `mkdir "\\?\C:\Program Files"`,
expected: []string{`mkdir`, `\\?\C:\Program Files`},
},
{ // 15 - unclosed quotes - treat as if the path ends with quote
input: `mkdir "c:\Program files`,
expected: []string{`mkdir`, `c:\Program files`},
},
{ // 16 - quotes used inside the argument
input: `mkdir "c:\P"rogra"m f"iles`,
expected: []string{`mkdir`, `c:\Program files`},
},
}
for i, test := range tests {
errorPrefix := fmt.Sprintf("Test [%d]: ", i)
errorSuffix := fmt.Sprintf(" Command to parse: [%s]", test.input)
actual := parseWindowsCommand(test.input)
if len(actual) != len(test.expected) {
t.Errorf(errorPrefix+"Expected %d parts, got %d: %#v."+errorSuffix, len(test.expected), len(actual), actual)
continue
}
for j := 0; j < len(actual); j++ {
if expectedPart, actualPart := test.expected[j], actual[j]; expectedPart != actualPart {
t.Errorf(errorPrefix+"Expected: %v Actual: %v (index %d)."+errorSuffix, expectedPart, actualPart, j)
}
}
}
}
func TestSplitCommandAndArgs(t *testing.T) {
// force linux parsing. It's more robust and covers error cases
runtimeGoos = osLinux
defer func() {
runtimeGoos = runtime.GOOS
}()
var parseErrorContent = "error parsing command:"
var noCommandErrContent = "no command contained in"
tests := []struct {
input string
expectedCommand string
expectedArgs []string
expectedErrContent string
}{
// 0 - empty command
{
input: ``,
expectedCommand: ``,
expectedArgs: nil,
expectedErrContent: noCommandErrContent,
},
// 1 - command without arguments
{
input: `command`,
expectedCommand: `command`,
expectedArgs: nil,
expectedErrContent: ``,
},
// 2 - command with single argument
{
input: `command arg1`,
expectedCommand: `command`,
expectedArgs: []string{`arg1`},
expectedErrContent: ``,
},
// 3 - command with multiple arguments
{
input: `command arg1 arg2`,
expectedCommand: `command`,
expectedArgs: []string{`arg1`, `arg2`},
expectedErrContent: ``,
},
// 4 - command with unclosed quotes
{
input: `command "arg1 arg2`,
expectedCommand: "",
expectedArgs: nil,
expectedErrContent: parseErrorContent,
},
// 5 - command with unclosed quotes
{
input: `command 'arg1 arg2"`,
expectedCommand: "",
expectedArgs: nil,
expectedErrContent: parseErrorContent,
},
}
for i, test := range tests {
errorPrefix := fmt.Sprintf("Test [%d]: ", i)
errorSuffix := fmt.Sprintf(" Command to parse: [%s]", test.input)
actualCommand, actualArgs, actualErr := SplitCommandAndArgs(test.input)
// test if error matches expectation
if test.expectedErrContent != "" {
if actualErr == nil {
t.Errorf(errorPrefix+"Expected error with content [%s], found no error."+errorSuffix, test.expectedErrContent)
} else if !strings.Contains(actualErr.Error(), test.expectedErrContent) {
t.Errorf(errorPrefix+"Expected error with content [%s], found [%v]."+errorSuffix, test.expectedErrContent, actualErr)
}
} else if actualErr != nil {
t.Errorf(errorPrefix+"Expected no error, found [%v]."+errorSuffix, actualErr)
}
// test if command matches
if test.expectedCommand != actualCommand {
t.Errorf(errorPrefix+"Expected command: [%s], actual: [%s]."+errorSuffix, test.expectedCommand, actualCommand)
}
// test if arguments match
if len(test.expectedArgs) != len(actualArgs) {
t.Errorf(errorPrefix+"Wrong number of arguments! Expected [%v], actual [%v]."+errorSuffix, test.expectedArgs, actualArgs)
} else {
// test args only if the count matches.
for j, actualArg := range actualArgs {
expectedArg := test.expectedArgs[j]
if actualArg != expectedArg {
t.Errorf(errorPrefix+"Argument at position [%d] differ! Expected [%s], actual [%s]"+errorSuffix, j, expectedArg, actualArg)
}
}
}
}
}
func ExampleSplitCommandAndArgs() {
var commandLine string
var command string
var args []string
// just for the test - change GOOS and reset it at the end of the test
runtimeGoos = osWindows
defer func() {
runtimeGoos = runtime.GOOS
}()
commandLine = `mkdir /P "C:\Program Files"`
command, args, _ = SplitCommandAndArgs(commandLine)
fmt.Printf("Windows: %s: %s [%s]\n", commandLine, command, strings.Join(args, ","))
// set GOOS to linux
runtimeGoos = osLinux
commandLine = `mkdir -p /path/with\ space`
command, args, _ = SplitCommandAndArgs(commandLine)
fmt.Printf("Linux: %s: %s [%s]\n", commandLine, command, strings.Join(args, ","))
// Output:
// Windows: mkdir /P "C:\Program Files": mkdir [/P,C:\Program Files]
// Linux: mkdir -p /path/with\ space: mkdir [-p,/path/with space]
}
| 5 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package http
import (
"errors"
"net/http"
"net/url"
"path"
"path/filepath"
"strings"
"github.com/spf13/afero"
"golang.org/x/crypto/bcrypt"
"github.com/filebrowser/filebrowser/v2/files"
"github.com/filebrowser/filebrowser/v2/share"
)
var withHashFile = func(fn handleFunc) handleFunc {
return func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
id, ifPath := ifPathWithName(r)
link, err := d.store.Share.GetByHash(id)
if err != nil {
return errToStatus(err), err
}
status, err := authenticateShareRequest(r, link)
if status != 0 || err != nil {
return status, err
}
user, err := d.store.Users.Get(d.server.Root, link.UserID)
if err != nil {
return errToStatus(err), err
}
d.user = user
file, err := files.NewFileInfo(files.FileOptions{
Fs: d.user.Fs,
Path: link.Path,
Modify: d.user.Perm.Modify,
Expand: false,
ReadHeader: d.server.TypeDetectionByHeader,
Checker: d,
Token: link.Token,
})
if err != nil {
return errToStatus(err), err
}
// share base path
basePath := link.Path
// file relative path
filePath := ""
if file.IsDir {
basePath = filepath.Dir(basePath)
filePath = ifPath
}
// set fs root to the shared file/folder
d.user.Fs = afero.NewBasePathFs(d.user.Fs, basePath)
file, err = files.NewFileInfo(files.FileOptions{
Fs: d.user.Fs,
Path: filePath,
Modify: d.user.Perm.Modify,
Expand: true,
Checker: d,
Token: link.Token,
})
if err != nil {
return errToStatus(err), err
}
d.raw = file
return fn(w, r, d)
}
}
// ref to https://github.com/filebrowser/filebrowser/pull/727
// `/api/public/dl/MEEuZK-v/file-name.txt` for old browsers to save file with correct name
func ifPathWithName(r *http.Request) (id, filePath string) {
pathElements := strings.Split(r.URL.Path, "/")
// prevent maliciously constructed parameters like `/api/public/dl/XZzCDnK2_not_exists_hash_name`
// len(pathElements) will be 1, and golang will panic `runtime error: index out of range`
switch len(pathElements) {
case 1:
return r.URL.Path, "/"
default:
return pathElements[0], path.Join("/", path.Join(pathElements[1:]...))
}
}
var publicShareHandler = withHashFile(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
file := d.raw.(*files.FileInfo)
if file.IsDir {
file.Listing.Sorting = files.Sorting{By: "name", Asc: false}
file.Listing.ApplySort()
return renderJSON(w, r, file)
}
return renderJSON(w, r, file)
})
var publicDlHandler = withHashFile(func(w http.ResponseWriter, r *http.Request, d *data) (int, error) {
file := d.raw.(*files.FileInfo)
if !file.IsDir {
return rawFileHandler(w, r, file)
}
return rawDirHandler(w, r, d, file)
})
func authenticateShareRequest(r *http.Request, l *share.Link) (int, error) {
if l.PasswordHash == "" {
return 0, nil
}
if r.URL.Query().Get("token") == l.Token {
return 0, nil
}
password := r.Header.Get("X-SHARE-PASSWORD")
password, err := url.QueryUnescape(password)
if err != nil {
return 0, err
}
if password == "" {
return http.StatusUnauthorized, nil
}
if err := bcrypt.CompareHashAndPassword([]byte(l.PasswordHash), []byte(password)); err != nil {
if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
return http.StatusUnauthorized, nil
}
return 0, err
}
return 0, nil
}
func healthHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"OK"}`))
}
| package http
import (
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/asdine/storm/v3"
"github.com/spf13/afero"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/share"
"github.com/filebrowser/filebrowser/v2/storage/bolt"
"github.com/filebrowser/filebrowser/v2/users"
)
func TestPublicShareHandlerAuthentication(t *testing.T) {
t.Parallel()
const passwordBcrypt = "$2y$10$TFAmdCbyd/mEZDe5fUeZJu.MaJQXRTwdqb/IQV.eTn6dWrF58gCSe" //nolint:gosec
testCases := map[string]struct {
share *share.Link
req *http.Request
expectedStatusCode int
}{
"Public share, no auth required": {
share: &share.Link{Hash: "h", UserID: 1},
req: newHTTPRequest(t),
expectedStatusCode: 200,
},
"Private share, no auth provided, 401": {
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
req: newHTTPRequest(t),
expectedStatusCode: 401,
},
"Private share, authentication via token": {
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
req: newHTTPRequest(t, func(r *http.Request) { r.URL.RawQuery = "token=123" }),
expectedStatusCode: 200,
},
"Private share, authentication via invalid token, 401": {
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
req: newHTTPRequest(t, func(r *http.Request) { r.URL.RawQuery = "token=1234" }),
expectedStatusCode: 401,
},
"Private share, authentication via password": {
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
req: newHTTPRequest(t, func(r *http.Request) { r.Header.Set("X-SHARE-PASSWORD", "password") }),
expectedStatusCode: 200,
},
"Private share, authentication via invalid password, 401": {
share: &share.Link{Hash: "h", UserID: 1, PasswordHash: passwordBcrypt, Token: "123"},
req: newHTTPRequest(t, func(r *http.Request) { r.Header.Set("X-SHARE-PASSWORD", "wrong-password") }),
expectedStatusCode: 401,
},
}
for name, tc := range testCases {
for handlerName, handler := range map[string]handleFunc{"public share handler": publicShareHandler, "public dl handler": publicDlHandler} {
name, tc, handlerName, handler := name, tc, handlerName, handler
t.Run(fmt.Sprintf("%s: %s", handlerName, name), func(t *testing.T) {
t.Parallel()
dbPath := filepath.Join(t.TempDir(), "db")
db, err := storm.Open(dbPath)
if err != nil {
t.Fatalf("failed to open db: %v", err)
}
t.Cleanup(func() {
if err := db.Close(); err != nil { //nolint:govet
t.Errorf("failed to close db: %v", err)
}
})
storage, err := bolt.NewStorage(db)
if err != nil {
t.Fatalf("failed to get storage: %v", err)
}
if err := storage.Share.Save(tc.share); err != nil {
t.Fatalf("failed to save share: %v", err)
}
if err := storage.Users.Save(&users.User{Username: "username", Password: "pw"}); err != nil {
t.Fatalf("failed to save user: %v", err)
}
if err := storage.Settings.Save(&settings.Settings{Key: []byte("key")}); err != nil {
t.Fatalf("failed to save settings: %v", err)
}
storage.Users = &customFSUser{
Store: storage.Users,
fs: &afero.MemMapFs{},
}
recorder := httptest.NewRecorder()
handler := handle(handler, "", storage, &settings.Server{})
handler.ServeHTTP(recorder, tc.req)
result := recorder.Result()
defer result.Body.Close()
if result.StatusCode != tc.expectedStatusCode {
t.Errorf("expected status code %d, got status code %d", tc.expectedStatusCode, result.StatusCode)
}
})
}
}
}
func newHTTPRequest(t *testing.T, requestModifiers ...func(*http.Request)) *http.Request {
t.Helper()
r, err := http.NewRequest(http.MethodGet, "h", http.NoBody)
if err != nil {
t.Fatalf("failed to construct request: %v", err)
}
for _, modify := range requestModifiers {
modify(r)
}
return r
}
type customFSUser struct {
users.Store
fs afero.Fs
}
func (cu *customFSUser) Get(baseScope string, id interface{}) (*users.User, error) {
user, err := cu.Store.Get(baseScope, id)
if err != nil {
return nil, err
}
user.Fs = cu.fs
return user, nil
}
| 6 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package files
import (
"crypto/md5" //nolint:gosec
"crypto/sha1" //nolint:gosec
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"hash"
"image"
"io"
"log"
"mime"
"net/http"
"os"
"path"
"path/filepath"
"strings"
"time"
"github.com/spf13/afero"
"github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/rules"
)
const PermFile = 0664
const PermDir = 0755
// FileInfo describes a file.
type FileInfo struct {
*Listing
Fs afero.Fs `json:"-"`
Path string `json:"path"`
Name string `json:"name"`
Size int64 `json:"size"`
Extension string `json:"extension"`
ModTime time.Time `json:"modified"`
Mode os.FileMode `json:"mode"`
IsDir bool `json:"isDir"`
IsSymlink bool `json:"isSymlink"`
Type string `json:"type"`
Subtitles []string `json:"subtitles,omitempty"`
Content string `json:"content,omitempty"`
Checksums map[string]string `json:"checksums,omitempty"`
Token string `json:"token,omitempty"`
currentDir []os.FileInfo `json:"-"`
Resolution *ImageResolution `json:"resolution,omitempty"`
}
// FileOptions are the options when getting a file info.
type FileOptions struct {
Fs afero.Fs
Path string
Modify bool
Expand bool
ReadHeader bool
Token string
Checker rules.Checker
Content bool
}
type ImageResolution struct {
Width int `json:"width"`
Height int `json:"height"`
}
// NewFileInfo creates a File object from a path and a given user. This File
// object will be automatically filled depending on if it is a directory
// or a file. If it's a video file, it will also detect any subtitles.
func NewFileInfo(opts FileOptions) (*FileInfo, error) {
if !opts.Checker.Check(opts.Path) {
return nil, os.ErrPermission
}
file, err := stat(opts)
if err != nil {
return nil, err
}
if opts.Expand {
if file.IsDir {
if err := file.readListing(opts.Checker, opts.ReadHeader); err != nil { //nolint:govet
return nil, err
}
return file, nil
}
err = file.detectType(opts.Modify, opts.Content, true)
if err != nil {
return nil, err
}
}
return file, err
}
func stat(opts FileOptions) (*FileInfo, error) {
var file *FileInfo
if lstaterFs, ok := opts.Fs.(afero.Lstater); ok {
info, _, err := lstaterFs.LstatIfPossible(opts.Path)
if err != nil {
return nil, err
}
file = &FileInfo{
Fs: opts.Fs,
Path: opts.Path,
Name: info.Name(),
ModTime: info.ModTime(),
Mode: info.Mode(),
IsDir: info.IsDir(),
IsSymlink: IsSymlink(info.Mode()),
Size: info.Size(),
Extension: filepath.Ext(info.Name()),
Token: opts.Token,
}
}
// regular file
if file != nil && !file.IsSymlink {
return file, nil
}
// fs doesn't support afero.Lstater interface or the file is a symlink
info, err := opts.Fs.Stat(opts.Path)
if err != nil {
// can't follow symlink
if file != nil && file.IsSymlink {
return file, nil
}
return nil, err
}
// set correct file size in case of symlink
if file != nil && file.IsSymlink {
file.Size = info.Size()
file.IsDir = info.IsDir()
return file, nil
}
file = &FileInfo{
Fs: opts.Fs,
Path: opts.Path,
Name: info.Name(),
ModTime: info.ModTime(),
Mode: info.Mode(),
IsDir: info.IsDir(),
Size: info.Size(),
Extension: filepath.Ext(info.Name()),
Token: opts.Token,
}
return file, nil
}
// Checksum checksums a given File for a given User, using a specific
// algorithm. The checksums data is saved on File object.
func (i *FileInfo) Checksum(algo string) error {
if i.IsDir {
return errors.ErrIsDirectory
}
if i.Checksums == nil {
i.Checksums = map[string]string{}
}
reader, err := i.Fs.Open(i.Path)
if err != nil {
return err
}
defer reader.Close()
var h hash.Hash
//nolint:gosec
switch algo {
case "md5":
h = md5.New()
case "sha1":
h = sha1.New()
case "sha256":
h = sha256.New()
case "sha512":
h = sha512.New()
default:
return errors.ErrInvalidOption
}
_, err = io.Copy(h, reader)
if err != nil {
return err
}
i.Checksums[algo] = hex.EncodeToString(h.Sum(nil))
return nil
}
func (i *FileInfo) RealPath() string {
if realPathFs, ok := i.Fs.(interface {
RealPath(name string) (fPath string, err error)
}); ok {
realPath, err := realPathFs.RealPath(i.Path)
if err == nil {
return realPath
}
}
return i.Path
}
// TODO: use constants
//
//nolint:goconst
func (i *FileInfo) detectType(modify, saveContent, readHeader bool) error {
if IsNamedPipe(i.Mode) {
i.Type = "blob"
return nil
}
// failing to detect the type should not return error.
// imagine the situation where a file in a dir with thousands
// of files couldn't be opened: we'd have immediately
// a 500 even though it doesn't matter. So we just log it.
mimetype := mime.TypeByExtension(i.Extension)
var buffer []byte
if readHeader {
buffer = i.readFirstBytes()
if mimetype == "" {
mimetype = http.DetectContentType(buffer)
}
}
switch {
case strings.HasPrefix(mimetype, "video"):
i.Type = "video"
i.detectSubtitles()
return nil
case strings.HasPrefix(mimetype, "audio"):
i.Type = "audio"
return nil
case strings.HasPrefix(mimetype, "image"):
i.Type = "image"
resolution, err := calculateImageResolution(i.Fs, i.Path)
if err != nil {
log.Printf("Error calculating image resolution: %v", err)
} else {
i.Resolution = resolution
}
return nil
case strings.HasSuffix(mimetype, "pdf"):
i.Type = "pdf"
return nil
case (strings.HasPrefix(mimetype, "text") || !isBinary(buffer)) && i.Size <= 10*1024*1024: // 10 MB
i.Type = "text"
if !modify {
i.Type = "textImmutable"
}
if saveContent {
afs := &afero.Afero{Fs: i.Fs}
content, err := afs.ReadFile(i.Path)
if err != nil {
return err
}
i.Content = string(content)
}
return nil
default:
i.Type = "blob"
}
return nil
}
func calculateImageResolution(fs afero.Fs, filePath string) (*ImageResolution, error) {
file, err := fs.Open(filePath)
if err != nil {
return nil, err
}
defer func() {
if cErr := file.Close(); cErr != nil {
log.Printf("Failed to close file: %v", cErr)
}
}()
config, _, err := image.DecodeConfig(file)
if err != nil {
return nil, err
}
return &ImageResolution{
Width: config.Width,
Height: config.Height,
}, nil
}
func (i *FileInfo) readFirstBytes() []byte {
reader, err := i.Fs.Open(i.Path)
if err != nil {
log.Print(err)
i.Type = "blob"
return nil
}
defer reader.Close()
buffer := make([]byte, 512) //nolint:gomnd
n, err := reader.Read(buffer)
if err != nil && err != io.EOF {
log.Print(err)
i.Type = "blob"
return nil
}
return buffer[:n]
}
func (i *FileInfo) detectSubtitles() {
if i.Type != "video" {
return
}
i.Subtitles = []string{}
ext := filepath.Ext(i.Path)
// detect multiple languages. Base*.vtt
// TODO: give subtitles descriptive names (lang) and track attributes
parentDir := strings.TrimRight(i.Path, i.Name)
var dir []os.FileInfo
if len(i.currentDir) > 0 {
dir = i.currentDir
} else {
var err error
dir, err = afero.ReadDir(i.Fs, parentDir)
if err != nil {
return
}
}
base := strings.TrimSuffix(i.Name, ext)
for _, f := range dir {
if !f.IsDir() && strings.HasPrefix(f.Name(), base) && strings.HasSuffix(f.Name(), ".vtt") {
i.Subtitles = append(i.Subtitles, path.Join(parentDir, f.Name()))
}
}
}
func (i *FileInfo) readListing(checker rules.Checker, readHeader bool) error {
afs := &afero.Afero{Fs: i.Fs}
dir, err := afs.ReadDir(i.Path)
if err != nil {
return err
}
listing := &Listing{
Items: []*FileInfo{},
NumDirs: 0,
NumFiles: 0,
}
for _, f := range dir {
name := f.Name()
fPath := path.Join(i.Path, name)
if !checker.Check(fPath) {
continue
}
isSymlink, isInvalidLink := false, false
if IsSymlink(f.Mode()) {
isSymlink = true
// It's a symbolic link. We try to follow it. If it doesn't work,
// we stay with the link information instead of the target's.
info, err := i.Fs.Stat(fPath)
if err == nil {
f = info
} else {
isInvalidLink = true
}
}
file := &FileInfo{
Fs: i.Fs,
Name: name,
Size: f.Size(),
ModTime: f.ModTime(),
Mode: f.Mode(),
IsDir: f.IsDir(),
IsSymlink: isSymlink,
Extension: filepath.Ext(name),
Path: fPath,
currentDir: dir,
}
if !file.IsDir && strings.HasPrefix(mime.TypeByExtension(file.Extension), "image/") {
resolution, err := calculateImageResolution(file.Fs, file.Path)
if err != nil {
log.Printf("Error calculating resolution for image %s: %v", file.Path, err)
} else {
file.Resolution = resolution
}
}
if file.IsDir {
listing.NumDirs++
} else {
listing.NumFiles++
if isInvalidLink {
file.Type = "invalid_link"
} else {
err := file.detectType(true, false, readHeader)
if err != nil {
return err
}
}
}
listing.Items = append(listing.Items, file)
}
i.Listing = listing
return nil
}
| package fileutils
import "testing"
func TestCommonPrefix(t *testing.T) {
testCases := map[string]struct {
paths []string
want string
}{
"same lvl": {
paths: []string{
"/home/user/file1",
"/home/user/file2",
},
want: "/home/user",
},
"sub folder": {
paths: []string{
"/home/user/folder",
"/home/user/folder/file",
},
want: "/home/user/folder",
},
"relative path": {
paths: []string{
"/home/user/folder",
"/home/user/folder/../folder2",
},
want: "/home/user",
},
"no common path": {
paths: []string{
"/home/user/folder",
"/etc/file",
},
want: "",
},
}
for name, tt := range testCases {
t.Run(name, func(t *testing.T) {
if got := CommonPrefix('/', tt.paths...); got != tt.want {
t.Errorf("CommonPrefix() = %v, want %v", got, tt.want)
}
})
}
}
| 7 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package fileutils
import (
"io"
"os"
"path"
"path/filepath"
"github.com/spf13/afero"
)
// MoveFile moves file from src to dst.
// By default the rename filesystem system call is used. If src and dst point to different volumes
// the file copy is used as a fallback
func MoveFile(fs afero.Fs, src, dst string) error {
if fs.Rename(src, dst) == nil {
return nil
}
// fallback
err := Copy(fs, src, dst)
if err != nil {
_ = fs.Remove(dst)
return err
}
if err := fs.RemoveAll(src); err != nil {
return err
}
return nil
}
// CopyFile copies a file from source to dest and returns
// an error if any.
func CopyFile(fs afero.Fs, source, dest string) error {
// Open the source file.
src, err := fs.Open(source)
if err != nil {
return err
}
defer src.Close()
// Makes the directory needed to create the dst
// file.
err = fs.MkdirAll(filepath.Dir(dest), 0666) //nolint:gomnd
if err != nil {
return err
}
// Create the destination file.
dst, err := fs.OpenFile(dest, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0775) //nolint:gomnd
if err != nil {
return err
}
defer dst.Close()
// Copy the contents of the file.
_, err = io.Copy(dst, src)
if err != nil {
return err
}
// Copy the mode
info, err := fs.Stat(source)
if err != nil {
return err
}
err = fs.Chmod(dest, info.Mode())
if err != nil {
return err
}
return nil
}
// CommonPrefix returns common directory path of provided files
func CommonPrefix(sep byte, paths ...string) string {
// Handle special cases.
switch len(paths) {
case 0:
return ""
case 1:
return path.Clean(paths[0])
}
// Note, we treat string as []byte, not []rune as is often
// done in Go. (And sep as byte, not rune). This is because
// most/all supported OS' treat paths as string of non-zero
// bytes. A filename may be displayed as a sequence of Unicode
// runes (typically encoded as UTF-8) but paths are
// not required to be valid UTF-8 or in any normalized form
// (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different
// file names.
c := []byte(path.Clean(paths[0]))
// We add a trailing sep to handle the case where the
// common prefix directory is included in the path list
// (e.g. /home/user1, /home/user1/foo, /home/user1/bar).
// path.Clean will have cleaned off trailing / separators with
// the exception of the root directory, "/" (in which case we
// make it "//", but this will get fixed up to "/" bellow).
c = append(c, sep)
// Ignore the first path since it's already in c
for _, v := range paths[1:] {
// Clean up each path before testing it
v = path.Clean(v) + string(sep)
// Find the first non-common byte and truncate c
if len(v) < len(c) {
c = c[:len(v)]
}
for i := 0; i < len(c); i++ {
if v[i] != c[i] {
c = c[:i]
break
}
}
}
// Remove trailing non-separator characters and the final separator
for i := len(c) - 1; i >= 0; i-- {
if c[i] == sep {
c = c[:i]
break
}
}
return string(c)
}
| package fileutils
import "testing"
func TestCommonPrefix(t *testing.T) {
testCases := map[string]struct {
paths []string
want string
}{
"same lvl": {
paths: []string{
"/home/user/file1",
"/home/user/file2",
},
want: "/home/user",
},
"sub folder": {
paths: []string{
"/home/user/folder",
"/home/user/folder/file",
},
want: "/home/user/folder",
},
"relative path": {
paths: []string{
"/home/user/folder",
"/home/user/folder/../folder2",
},
want: "/home/user",
},
"no common path": {
paths: []string{
"/home/user/folder",
"/etc/file",
},
want: "",
},
}
for name, tt := range testCases {
t.Run(name, func(t *testing.T) {
if got := CommonPrefix('/', tt.paths...); got != tt.want {
t.Errorf("CommonPrefix() = %v, want %v", got, tt.want)
}
})
}
}
| 8 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package auth
import (
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/users"
)
// StorageBackend is a storage backend for auth storage.
type StorageBackend interface {
Get(settings.AuthMethod) (Auther, error)
Save(Auther) error
}
// Storage is a auth storage.
type Storage struct {
back StorageBackend
users *users.Storage
}
// NewStorage creates a auth storage from a backend.
func NewStorage(back StorageBackend, userStore *users.Storage) *Storage {
return &Storage{back: back, users: userStore}
}
// Get wraps a StorageBackend.Get.
func (s *Storage) Get(t settings.AuthMethod) (Auther, error) {
return s.back.Get(t)
}
// Save wraps a StorageBackend.Save.
func (s *Storage) Save(a Auther) error {
return s.back.Save(a)
}
| package users
// Interface is implemented by storage
var _ Store = &Storage{}
| 9 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package settings
import (
"github.com/filebrowser/filebrowser/v2/errors"
"github.com/filebrowser/filebrowser/v2/rules"
"github.com/filebrowser/filebrowser/v2/users"
)
// StorageBackend is a settings storage backend.
type StorageBackend interface {
Get() (*Settings, error)
Save(*Settings) error
GetServer() (*Server, error)
SaveServer(*Server) error
}
// Storage is a settings storage.
type Storage struct {
back StorageBackend
}
// NewStorage creates a settings storage from a backend.
func NewStorage(back StorageBackend) *Storage {
return &Storage{back: back}
}
// Get returns the settings for the current instance.
func (s *Storage) Get() (*Settings, error) {
set, err := s.back.Get()
if err != nil {
return nil, err
}
if set.UserHomeBasePath == "" {
set.UserHomeBasePath = DefaultUsersHomeBasePath
}
if set.Tus == (Tus{}) {
set.Tus = Tus{
ChunkSize: DefaultTusChunkSize,
RetryCount: DefaultTusRetryCount,
}
}
return set, nil
}
var defaultEvents = []string{
"save",
"copy",
"rename",
"upload",
"delete",
}
// Save saves the settings for the current instance.
func (s *Storage) Save(set *Settings) error {
if len(set.Key) == 0 {
return errors.ErrEmptyKey
}
if set.Defaults.Locale == "" {
set.Defaults.Locale = "en"
}
if set.Defaults.Commands == nil {
set.Defaults.Commands = []string{}
}
if set.Defaults.ViewMode == "" {
set.Defaults.ViewMode = users.MosaicViewMode
}
if set.Rules == nil {
set.Rules = []rules.Rule{}
}
if set.Shell == nil {
set.Shell = []string{}
}
if set.Commands == nil {
set.Commands = map[string][]string{}
}
for _, event := range defaultEvents {
if _, ok := set.Commands["before_"+event]; !ok {
set.Commands["before_"+event] = []string{}
}
if _, ok := set.Commands["after_"+event]; !ok {
set.Commands["after_"+event] = []string{}
}
}
err := s.back.Save(set)
if err != nil {
return err
}
return nil
}
// GetServer wraps StorageBackend.GetServer.
func (s *Storage) GetServer() (*Server, error) {
return s.back.GetServer()
}
// SaveServer wraps StorageBackend.SaveServer and adds some verification.
func (s *Storage) SaveServer(ser *Server) error {
ser.Clean()
return s.back.SaveServer(ser)
}
| package users
// Interface is implemented by storage
var _ Store = &Storage{}
| 10 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package share
import (
"time"
"github.com/filebrowser/filebrowser/v2/errors"
)
// StorageBackend is the interface to implement for a share storage.
type StorageBackend interface {
All() ([]*Link, error)
FindByUserID(id uint) ([]*Link, error)
GetByHash(hash string) (*Link, error)
GetPermanent(path string, id uint) (*Link, error)
Gets(path string, id uint) ([]*Link, error)
Save(s *Link) error
Delete(hash string) error
}
// Storage is a storage.
type Storage struct {
back StorageBackend
}
// NewStorage creates a share links storage from a backend.
func NewStorage(back StorageBackend) *Storage {
return &Storage{back: back}
}
// All wraps a StorageBackend.All.
func (s *Storage) All() ([]*Link, error) {
links, err := s.back.All()
if err != nil {
return nil, err
}
for i, link := range links {
if link.Expire != 0 && link.Expire <= time.Now().Unix() {
if err := s.Delete(link.Hash); err != nil {
return nil, err
}
links = append(links[:i], links[i+1:]...)
}
}
return links, nil
}
// FindByUserID wraps a StorageBackend.FindByUserID.
func (s *Storage) FindByUserID(id uint) ([]*Link, error) {
links, err := s.back.FindByUserID(id)
if err != nil {
return nil, err
}
for i, link := range links {
if link.Expire != 0 && link.Expire <= time.Now().Unix() {
if err := s.Delete(link.Hash); err != nil {
return nil, err
}
links = append(links[:i], links[i+1:]...)
}
}
return links, nil
}
// GetByHash wraps a StorageBackend.GetByHash.
func (s *Storage) GetByHash(hash string) (*Link, error) {
link, err := s.back.GetByHash(hash)
if err != nil {
return nil, err
}
if link.Expire != 0 && link.Expire <= time.Now().Unix() {
if err := s.Delete(link.Hash); err != nil {
return nil, err
}
return nil, errors.ErrNotExist
}
return link, nil
}
// GetPermanent wraps a StorageBackend.GetPermanent
func (s *Storage) GetPermanent(path string, id uint) (*Link, error) {
return s.back.GetPermanent(path, id)
}
// Gets wraps a StorageBackend.Gets
func (s *Storage) Gets(path string, id uint) ([]*Link, error) {
links, err := s.back.Gets(path, id)
if err != nil {
return nil, err
}
for i, link := range links {
if link.Expire != 0 && link.Expire <= time.Now().Unix() {
if err := s.Delete(link.Hash); err != nil {
return nil, err
}
links = append(links[:i], links[i+1:]...)
}
}
return links, nil
}
// Save wraps a StorageBackend.Save
func (s *Storage) Save(l *Link) error {
return s.back.Save(l)
}
// Delete wraps a StorageBackend.Delete
func (s *Storage) Delete(hash string) error {
return s.back.Delete(hash)
}
| package users
// Interface is implemented by storage
var _ Store = &Storage{}
| 11 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package storage
import (
"github.com/filebrowser/filebrowser/v2/auth"
"github.com/filebrowser/filebrowser/v2/settings"
"github.com/filebrowser/filebrowser/v2/share"
"github.com/filebrowser/filebrowser/v2/users"
)
// Storage is a storage powered by a Backend which makes the necessary
// verifications when fetching and saving data to ensure consistency.
type Storage struct {
Users users.Store
Share *share.Storage
Auth *auth.Storage
Settings *settings.Storage
}
| package users
// Interface is implemented by storage
var _ Store = &Storage{}
| 12 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package users
import (
"sync"
"time"
"github.com/filebrowser/filebrowser/v2/errors"
)
// StorageBackend is the interface to implement for a users storage.
type StorageBackend interface {
GetBy(interface{}) (*User, error)
Gets() ([]*User, error)
Save(u *User) error
Update(u *User, fields ...string) error
DeleteByID(uint) error
DeleteByUsername(string) error
}
type Store interface {
Get(baseScope string, id interface{}) (user *User, err error)
Gets(baseScope string) ([]*User, error)
Update(user *User, fields ...string) error
Save(user *User) error
Delete(id interface{}) error
LastUpdate(id uint) int64
}
// Storage is a users storage.
type Storage struct {
back StorageBackend
updated map[uint]int64
mux sync.RWMutex
}
// NewStorage creates a users storage from a backend.
func NewStorage(back StorageBackend) *Storage {
return &Storage{
back: back,
updated: map[uint]int64{},
}
}
// Get allows you to get a user by its name or username. The provided
// id must be a string for username lookup or a uint for id lookup. If id
// is neither, a ErrInvalidDataType will be returned.
func (s *Storage) Get(baseScope string, id interface{}) (user *User, err error) {
user, err = s.back.GetBy(id)
if err != nil {
return
}
if err := user.Clean(baseScope); err != nil {
return nil, err
}
return
}
// Gets gets a list of all users.
func (s *Storage) Gets(baseScope string) ([]*User, error) {
users, err := s.back.Gets()
if err != nil {
return nil, err
}
for _, user := range users {
if err := user.Clean(baseScope); err != nil { //nolint:govet
return nil, err
}
}
return users, err
}
// Update updates a user in the database.
func (s *Storage) Update(user *User, fields ...string) error {
err := user.Clean("", fields...)
if err != nil {
return err
}
err = s.back.Update(user, fields...)
if err != nil {
return err
}
s.mux.Lock()
s.updated[user.ID] = time.Now().Unix()
s.mux.Unlock()
return nil
}
// Save saves the user in a storage.
func (s *Storage) Save(user *User) error {
if err := user.Clean(""); err != nil {
return err
}
return s.back.Save(user)
}
// Delete allows you to delete a user by its name or username. The provided
// id must be a string for username lookup or a uint for id lookup. If id
// is neither, a ErrInvalidDataType will be returned.
func (s *Storage) Delete(id interface{}) error {
switch id := id.(type) {
case string:
user, err := s.back.GetBy(id)
if err != nil {
return err
}
if user.ID == 1 {
return errors.ErrRootUserDeletion
}
return s.back.DeleteByUsername(id)
case uint:
if id == 1 {
return errors.ErrRootUserDeletion
}
return s.back.DeleteByID(id)
default:
return errors.ErrInvalidDataType
}
}
// LastUpdate gets the timestamp for the last update of an user.
func (s *Storage) LastUpdate(id uint) int64 {
s.mux.RLock()
defer s.mux.RUnlock()
if val, ok := s.updated[id]; ok {
return val
}
return 0
}
| package users
// Interface is implemented by storage
var _ Store = &Storage{}
| 13 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package main
import (
"encoding/json"
"flag"
"fmt"
"html"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"sort"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
)
const (
htmlTemplate = `<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>%s</table></body></html>`
fortuneTemplate = `<tr><td>%d</td><td>%s</td></tr>`
helloWorldString = "Hello, World!"
extraFortuneMessage = "Additional fortune added at request time."
)
var (
bindHost = ":8080"
debugFlag = false
preforkFlag = false
childFlag = false
helloWorldMessage = &Message{helloWorldString}
extraFortune = &Fortune{Message: extraFortuneMessage}
)
// Message is a JSON struct to render a message
type Message struct {
Message string `json:"message"`
}
// World is a JSON struct to render a random number
type World struct {
ID uint16 `json:"id"`
RandomNumber uint16 `json:"randomNumber"`
}
// Fortune renders a fortune in JSON
type Fortune struct {
ID uint16 `json:"id"`
Message string `json:"message"`
}
// Fortunes is a list of fortunes
type Fortunes []*Fortune
// Len returns the length of the fortunes list
func (s Fortunes) Len() int {
return len(s)
}
// Swap swaps fortunes at the given positions
func (s Fortunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Fortunes) Less(i, j int) bool { return s[i].Message < s[j].Message }
// Sets the content type of response. Also adds the Server header.
func setContentType(w http.ResponseWriter, contentType string) {
w.Header().Set("Server", "chi")
w.Header().Set("Content-Type", contentType)
}
// Test 1: JSON Serialization
func serializeJSON(w http.ResponseWriter, r *http.Request) {
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(helloWorldMessage)
}
// Test 2: Single Database Query
func singleQuery(w http.ResponseWriter, r *http.Request) {
var world World
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world.ID, &world.RandomNumber)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(&world)
}
// Caps queries parameter between 1 and 500.
// Non-int values like "foo" and "" become 1.
func sanitizeQueryParam(queries string) int {
n, err := strconv.Atoi(queries)
if err != nil {
n = 1
} else if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
return n
}
// Test 3: Multiple Database Queries
func multipleQueries(w http.ResponseWriter, r *http.Request) {
queries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, queries)
for i := 0; i < queries; i++ {
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&worlds[i].ID, &worlds[i].RandomNumber)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(worlds)
}
// Test 4: Fortunes
func fortunes(w http.ResponseWriter, r *http.Request) {
rows, err := fortuneStatement.Query()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fortunes := make(Fortunes, 0)
for rows.Next() { //Fetch rows
fortune := Fortune{}
if err := rows.Scan(&fortune.ID, &fortune.Message); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fortunes = append(fortunes, &fortune)
}
fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
sort.Sort(fortunes)
setContentType(w, "text/html; charset=utf-8")
var body strings.Builder
for _, fortune := range fortunes {
fmt.Fprintf(&body, fortuneTemplate, fortune.ID, html.EscapeString(fortune.Message))
}
fmt.Fprintf(w, htmlTemplate, body.String())
}
// Test 5: Database Updates
func dbupdate(w http.ResponseWriter, r *http.Request) {
numQueries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, numQueries)
for i := 0; i < numQueries; i++ {
if err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&worlds[i].ID, &worlds[i].RandomNumber); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
worlds[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := updateStatement.Exec(worlds[i].RandomNumber, worlds[i].ID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(worlds)
}
// Test 6: Plaintext
func plaintext(w http.ResponseWriter, r *http.Request) {
setContentType(w, "text/plain")
_, _ = io.WriteString(w, helloWorldString)
}
func init() {
flag.StringVar(&bindHost, "bind", bindHost, "Set bind host")
flag.BoolVar(&debugFlag, "debug", false, "Enable debug mode")
flag.BoolVar(&preforkFlag, "prefork", false, "Enable prefork mode")
flag.BoolVar(&childFlag, "child", false, "Enable child mode")
flag.Parse()
}
func initRouter() http.Handler {
r := chi.NewRouter()
r.Get("/json", serializeJSON)
r.Get("/db", singleQuery)
r.Get("/queries", multipleQueries)
r.Get("/fortunes", fortunes)
r.Get("/plaintext", plaintext)
r.Get("/updates", dbupdate)
return r
}
func startListening(listener net.Listener) error {
var err error
if !preforkFlag {
err = http.ListenAndServe(bindHost, initRouter())
} else {
err = http.Serve(listener, initRouter())
}
return err
}
func main() {
var listener net.Listener
if preforkFlag {
listener = doPrefork(childFlag, bindHost)
}
if !debugFlag {
log.SetOutput(ioutil.Discard)
}
if err := startListening(listener); err != nil {
log.Fatal(err)
}
}
| package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// go test -v -run=^$ -bench=Benchmark_Plaintext -benchmem -count=4
func Benchmark_Plaintext(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/plaintext", plaintextHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/plaintext", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, helloworldRaw, body)
}
// go test -v -run=^$ -bench=Benchmark_JSON -benchmem -count=4
func Benchmark_JSON(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/json", jsonHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/json", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMEApplicationJSON, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, `{"message":"Hello, World!"}`, string(body))
}
| 14 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package main
import (
"encoding/json"
"flag"
"fmt"
"html"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"sort"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
)
const (
htmlTemplate = `<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>%s</table></body></html>`
fortuneTemplate = `<tr><td>%d</td><td>%s</td></tr>`
helloWorldString = "Hello, World!"
extraFortuneMessage = "Additional fortune added at request time."
)
var (
bindHost = ":8080"
debugFlag = false
preforkFlag = false
childFlag = false
helloWorldMessage = &Message{helloWorldString}
extraFortune = &Fortune{Message: extraFortuneMessage}
)
// Message is a JSON struct to render a message
type Message struct {
Message string `json:"message"`
}
// World is a JSON struct to render a random number
type World struct {
ID uint16 `json:"id"`
RandomNumber uint16 `json:"randomNumber"`
}
// Fortune renders a fortune in JSON
type Fortune struct {
ID uint16 `json:"id"`
Message string `json:"message"`
}
// Fortunes is a list of fortunes
type Fortunes []*Fortune
// Len returns the length of the fortunes list
func (s Fortunes) Len() int {
return len(s)
}
// Swap swaps fortunes at the given positions
func (s Fortunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Fortunes) Less(i, j int) bool { return s[i].Message < s[j].Message }
// Sets the content type of response. Also adds the Server header.
func setContentType(w http.ResponseWriter, contentType string) {
w.Header().Set("Server", "chi")
w.Header().Set("Content-Type", contentType)
}
// Test 1: JSON Serialization
func serializeJSON(w http.ResponseWriter, r *http.Request) {
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(helloWorldMessage)
}
// Test 2: Single Database Query
func singleQuery(w http.ResponseWriter, r *http.Request) {
var world World
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world.ID, &world.RandomNumber)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(&world)
}
// Caps queries parameter between 1 and 500.
// Non-int values like "foo" and "" become 1.
func sanitizeQueryParam(queries string) int {
n, err := strconv.Atoi(queries)
if err != nil {
n = 1
} else if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
return n
}
// Test 3: Multiple Database Queries
func multipleQueries(w http.ResponseWriter, r *http.Request) {
queries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, queries)
for i := 0; i < queries; i++ {
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&worlds[i].ID, &worlds[i].RandomNumber)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(worlds)
}
// Test 4: Fortunes
func fortunes(w http.ResponseWriter, r *http.Request) {
rows, err := fortuneStatement.Query()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fortunes := make(Fortunes, 0)
for rows.Next() { //Fetch rows
fortune := Fortune{}
if err := rows.Scan(&fortune.ID, &fortune.Message); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fortunes = append(fortunes, &fortune)
}
fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
sort.Sort(fortunes)
setContentType(w, "text/html; charset=utf-8")
var body strings.Builder
for _, fortune := range fortunes {
fmt.Fprintf(&body, fortuneTemplate, fortune.ID, html.EscapeString(fortune.Message))
}
fmt.Fprintf(w, htmlTemplate, body.String())
}
// Test 5: Database Updates
func dbupdate(w http.ResponseWriter, r *http.Request) {
numQueries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, numQueries)
for i := 0; i < numQueries; i++ {
if err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&worlds[i].ID, &worlds[i].RandomNumber); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
worlds[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := updateStatement.Exec(worlds[i].RandomNumber, worlds[i].ID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(worlds)
}
// Test 6: Plaintext
func plaintext(w http.ResponseWriter, r *http.Request) {
setContentType(w, "text/plain")
_, _ = io.WriteString(w, helloWorldString)
}
func init() {
flag.StringVar(&bindHost, "bind", bindHost, "Set bind host")
flag.BoolVar(&debugFlag, "debug", false, "Enable debug mode")
flag.BoolVar(&preforkFlag, "prefork", false, "Enable prefork mode")
flag.BoolVar(&childFlag, "child", false, "Enable child mode")
flag.Parse()
}
func initRouter() http.Handler {
r := chi.NewRouter()
r.Get("/json", serializeJSON)
r.Get("/db", singleQuery)
r.Get("/queries", multipleQueries)
r.Get("/fortunes", fortunes)
r.Get("/plaintext", plaintext)
r.Get("/updates", dbupdate)
return r
}
func startListening(listener net.Listener) error {
var err error
if !preforkFlag {
err = http.ListenAndServe(bindHost, initRouter())
} else {
err = http.Serve(listener, initRouter())
}
return err
}
func main() {
var listener net.Listener
if preforkFlag {
listener = doPrefork(childFlag, bindHost)
}
if !debugFlag {
log.SetOutput(ioutil.Discard)
}
if err := startListening(listener); err != nil {
log.Fatal(err)
}
}
| package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// go test -v -run=^$ -bench=Benchmark_Plaintext -benchmem -count=4
func Benchmark_Plaintext(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/plaintext", plaintextHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/plaintext", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, helloworldRaw, body)
}
// go test -v -run=^$ -bench=Benchmark_JSON -benchmem -count=4
func Benchmark_JSON(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/json", jsonHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/json", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMEApplicationJSON, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, `{"message":"Hello, World!"}`, string(body))
}
| 15 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package main
import (
"encoding/json"
"flag"
"fmt"
"html"
"io"
"io/ioutil"
"log"
"math/rand"
"net"
"net/http"
"sort"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
)
const (
htmlTemplate = `<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>%s</table></body></html>`
fortuneTemplate = `<tr><td>%d</td><td>%s</td></tr>`
helloWorldString = "Hello, World!"
extraFortuneMessage = "Additional fortune added at request time."
)
var (
bindHost = ":8080"
debugFlag = false
preforkFlag = false
childFlag = false
helloWorldMessage = &Message{helloWorldString}
extraFortune = &Fortune{Message: extraFortuneMessage}
)
// Message is a JSON struct to render a message
type Message struct {
Message string `json:"message"`
}
// World is a JSON struct to render a random number
type World struct {
ID uint16 `json:"id"`
RandomNumber uint16 `json:"randomNumber"`
}
// Fortune renders a fortune in JSON
type Fortune struct {
ID uint16 `json:"id"`
Message string `json:"message"`
}
// Fortunes is a list of fortunes
type Fortunes []*Fortune
// Len returns the length of the fortunes list
func (s Fortunes) Len() int {
return len(s)
}
// Swap swaps fortunes at the given positions
func (s Fortunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s Fortunes) Less(i, j int) bool { return s[i].Message < s[j].Message }
// Sets the content type of response. Also adds the Server header.
func setContentType(w http.ResponseWriter, contentType string) {
w.Header().Set("Server", "chi")
w.Header().Set("Content-Type", contentType)
}
// Test 1: JSON Serialization
func serializeJSON(w http.ResponseWriter, r *http.Request) {
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(helloWorldMessage)
}
// Test 2: Single Database Query
func singleQuery(w http.ResponseWriter, r *http.Request) {
var world World
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&world.ID, &world.RandomNumber)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(&world)
}
// Caps queries parameter between 1 and 500.
// Non-int values like "foo" and "" become 1.
func sanitizeQueryParam(queries string) int {
n, err := strconv.Atoi(queries)
if err != nil {
n = 1
} else if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
return n
}
// Test 3: Multiple Database Queries
func multipleQueries(w http.ResponseWriter, r *http.Request) {
queries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, queries)
for i := 0; i < queries; i++ {
err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&worlds[i].ID, &worlds[i].RandomNumber)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(worlds)
}
// Test 4: Fortunes
func fortunes(w http.ResponseWriter, r *http.Request) {
rows, err := fortuneStatement.Query()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fortunes := make(Fortunes, 0)
for rows.Next() { //Fetch rows
fortune := Fortune{}
if err := rows.Scan(&fortune.ID, &fortune.Message); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fortunes = append(fortunes, &fortune)
}
fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
sort.Sort(fortunes)
setContentType(w, "text/html; charset=utf-8")
var body strings.Builder
for _, fortune := range fortunes {
fmt.Fprintf(&body, fortuneTemplate, fortune.ID, html.EscapeString(fortune.Message))
}
fmt.Fprintf(w, htmlTemplate, body.String())
}
// Test 5: Database Updates
func dbupdate(w http.ResponseWriter, r *http.Request) {
numQueries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, numQueries)
for i := 0; i < numQueries; i++ {
if err := worldStatement.QueryRow(rand.Intn(worldRowCount)+1).Scan(&worlds[i].ID, &worlds[i].RandomNumber); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
worlds[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := updateStatement.Exec(worlds[i].RandomNumber, worlds[i].ID); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
setContentType(w, "application/json")
_ = json.NewEncoder(w).Encode(worlds)
}
// Test 6: Plaintext
func plaintext(w http.ResponseWriter, r *http.Request) {
setContentType(w, "text/plain")
_, _ = io.WriteString(w, helloWorldString)
}
func init() {
flag.StringVar(&bindHost, "bind", bindHost, "Set bind host")
flag.BoolVar(&debugFlag, "debug", false, "Enable debug mode")
flag.BoolVar(&preforkFlag, "prefork", false, "Enable prefork mode")
flag.BoolVar(&childFlag, "child", false, "Enable child mode")
flag.Parse()
}
func initRouter() http.Handler {
r := chi.NewRouter()
r.Get("/json", serializeJSON)
r.Get("/db", singleQuery)
r.Get("/queries", multipleQueries)
r.Get("/fortunes", fortunes)
r.Get("/plaintext", plaintext)
r.Get("/updates", dbupdate)
return r
}
func startListening(listener net.Listener) error {
var err error
if !preforkFlag {
err = http.ListenAndServe(bindHost, initRouter())
} else {
err = http.Serve(listener, initRouter())
}
return err
}
func main() {
var listener net.Listener
if preforkFlag {
listener = doPrefork(childFlag, bindHost)
}
if !debugFlag {
log.SetOutput(ioutil.Discard)
}
if err := startListening(listener); err != nil {
log.Fatal(err)
}
}
| package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// go test -v -run=^$ -bench=Benchmark_Plaintext -benchmem -count=4
func Benchmark_Plaintext(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/plaintext", plaintextHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/plaintext", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, helloworldRaw, body)
}
// go test -v -run=^$ -bench=Benchmark_JSON -benchmem -count=4
func Benchmark_JSON(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/json", jsonHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/json", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMEApplicationJSON, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, `{"message":"Hello, World!"}`, string(body))
}
| 16 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package main
import (
"database/sql"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"math/rand"
"net/http"
"runtime"
"sort"
"strconv"
_ "github.com/go-sql-driver/mysql"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
)
const (
// Database
connectionString = "benchmarkdbuser:benchmarkdbpass@tcp(tfb-database:3306)/hello_world"
worldSelect = "SELECT id, randomNumber FROM World WHERE id = ?"
worldUpdate = "UPDATE World SET randomNumber = ? WHERE id = ?"
fortuneSelect = "SELECT id, message FROM Fortune;"
worldRowCount = 10000
maxConnectionCount = 256
helloWorldString = "Hello, World!"
extraFortuneMessage = "Additional fortune added at request time."
)
var (
// Templates
tmpl = template.Must(template.
ParseFiles("templates/layout.html",
"templates/fortune.html"))
// Database
worldStatement *sql.Stmt
fortuneStatement *sql.Stmt
updateStatement *sql.Stmt
)
type Message struct {
Message string `json:"message"`
}
type World struct {
Id uint16 `json:"id"`
RandomNumber uint16 `json:"randomNumber"`
}
func randomRow() *sql.Row {
return worldStatement.QueryRow(rand.Intn(worldRowCount) + 1)
}
type Fortune struct {
Id uint16 `json:"id"`
Message string `json:"message"`
}
type Fortunes []*Fortune
func (s Fortunes) Len() int {
return len(s)
}
func (s Fortunes) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
type ByMessage struct {
Fortunes
}
func (s ByMessage) Less(i, j int) bool {
return s.Fortunes[i].Message < s.Fortunes[j].Message
}
// Sets the content type of response. Also adds the Server header.
func setContentType(w http.ResponseWriter, contentType string) {
w.Header().Set("Server", "Goji")
w.Header().Set("Content-Type", contentType)
}
// Test 1: Json Serialization
func serializeJson(c web.C, w http.ResponseWriter, r *http.Request) {
setContentType(w, "application/json")
json.NewEncoder(w).Encode(&Message{helloWorldString})
}
// Test 2: Single Database Query
func singleQuery(c web.C, w http.ResponseWriter, r *http.Request) {
world := World{}
if err := randomRow().Scan(&world.Id, &world.RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
setContentType(w, "application/json")
json.NewEncoder(w).Encode(&world)
}
// Caps queries parameter between 1 and 500.
// Non-int values like "foo" and "" become 1.
func sanitizeQueryParam(queries string) int {
n := 1
if len(queries) > 0 {
if conv, err := strconv.Atoi(queries); err != nil {
n = 1
} else {
n = conv
}
}
if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
return n
}
// Test 3: Multiple Database Queries
func multipleQueries(c web.C, w http.ResponseWriter, r *http.Request) {
queries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, queries)
for i := 0; i < queries; i++ {
if err := randomRow().Scan(&worlds[i].Id, &worlds[i].RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
}
setContentType(w, "application/json")
json.NewEncoder(w).Encode(worlds)
}
// Test 4: Fortunes
func fortunes(c web.C, w http.ResponseWriter, r *http.Request) {
rows, err := fortuneStatement.Query()
if err != nil {
log.Fatalf("Error preparing statement: %v", err)
}
fortunes := make(Fortunes, 0)
for rows.Next() {
fortune := Fortune{}
if err := rows.Scan(&fortune.Id, &fortune.Message); err != nil {
log.Fatalf("Error scanning fortune row: %s", err.Error())
}
fortunes = append(fortunes, &fortune)
}
fortunes = append(fortunes, &Fortune{Message: extraFortuneMessage})
sort.Sort(ByMessage{fortunes})
setContentType(w, "text/html;charset=utf-8")
if err := tmpl.Execute(w, fortunes); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Test 5: Database Updates
func dbupdate(c web.C, w http.ResponseWriter, r *http.Request) {
queries := sanitizeQueryParam(r.URL.Query().Get("queries"))
worlds := make([]World, queries)
for i := 0; i < queries; i++ {
if err := randomRow().Scan(&worlds[i].Id, &worlds[i].RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
worlds[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := updateStatement.Exec(worlds[i].RandomNumber, worlds[i].Id); err != nil {
log.Fatalf("Error updating world row: %s", err.Error())
}
}
setContentType(w, "application/json")
json.NewEncoder(w).Encode(worlds)
}
// Test 6: Plaintext
func plaintext(c web.C, w http.ResponseWriter, r *http.Request) {
setContentType(w, "text/plain")
fmt.Fprintf(w, helloWorldString)
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
log.SetOutput(ioutil.Discard) // add line 3
db, err := sql.Open("mysql", connectionString)
if err != nil {
log.Fatalf("Error opening database: %v", err)
}
db.SetMaxIdleConns(maxConnectionCount)
worldStatement, err = db.Prepare(worldSelect)
if err != nil {
log.Fatal(err)
}
fortuneStatement, err = db.Prepare(fortuneSelect)
if err != nil {
log.Fatal(err)
}
updateStatement, err = db.Prepare(worldUpdate)
if err != nil {
log.Fatal(err)
}
flag.Set("bind", ":8080")
goji.Get("/json", serializeJson)
goji.Get("/db", singleQuery)
goji.Get("/queries", multipleQueries)
goji.Get("/fortunes", fortunes)
goji.Get("/plaintext", plaintext)
goji.Get("/updates", dbupdate)
goji.Serve()
}
| package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// go test -v -run=^$ -bench=Benchmark_Plaintext -benchmem -count=4
func Benchmark_Plaintext(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/plaintext", plaintextHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/plaintext", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, helloworldRaw, body)
}
// go test -v -run=^$ -bench=Benchmark_JSON -benchmem -count=4
func Benchmark_JSON(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/json", jsonHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/json", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMEApplicationJSON, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, `{"message":"Hello, World!"}`, string(body))
}
| 17 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package main
import (
"context"
"fmt"
"log"
"math/rand"
"os"
"runtime"
"sort"
"sync"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"fiber/app/templates"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
var (
db *pgxpool.Pool
cachedWorlds Worlds
)
const (
queryparam = "q"
helloworld = "Hello, World!"
worldcount = 10000
worldselectsql = "SELECT id, randomNumber FROM World WHERE id = $1"
worldupdatesql = "UPDATE World SET randomNumber = $1 WHERE id = $2"
worldcachesql = "SELECT * FROM World LIMIT $1"
fortuneselectsql = "SELECT id, message FROM Fortune"
pathJSON = "/json"
pathDB = "/db"
pathQueries = "/queries"
pathCache = "/cached-worlds"
pathFortunes = "/fortunes"
pathUpdate = "/update"
pathText = "/plaintext"
)
func main() {
initDatabase()
config := fiber.Config{
CaseSensitive: true,
StrictRouting: true,
DisableHeaderNormalizing: true,
ServerHeader: "go",
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
}
for i := range os.Args[1:] {
if os.Args[1:][i] == "-prefork" {
config.Prefork = true
}
}
app := fiber.New(config)
app.Use(func(c *fiber.Ctx) error {
switch c.Path() {
case pathJSON:
jsonHandler(c)
case pathDB:
dbHandler(c)
case pathQueries:
queriesHandler(c)
case pathCache:
cachedHandler(c)
case pathFortunes:
templateHandler(c)
case pathUpdate:
updateHandler(c)
case pathText:
plaintextHandler(c)
}
return nil
})
log.Fatal(app.Listen(":8080"))
}
// Message ...
type Message struct {
Message string `json:"message"`
}
// Worlds ...
type Worlds []World
// World ...
type World struct {
ID int32 `json:"id"`
RandomNumber int32 `json:"randomNumber"`
}
// JSONpool ...
var JSONpool = sync.Pool{
New: func() interface{} {
return new(Message)
},
}
// AcquireJSON ...
func AcquireJSON() *Message {
return JSONpool.Get().(*Message)
}
// ReleaseJSON ...
func ReleaseJSON(json *Message) {
json.Message = ""
JSONpool.Put(json)
}
// WorldPool ...
var WorldPool = sync.Pool{
New: func() interface{} {
return new(World)
},
}
// AcquireWorld ...
func AcquireWorld() *World {
return WorldPool.Get().(*World)
}
// ReleaseWorld ...
func ReleaseWorld(w *World) {
w.ID = 0
w.RandomNumber = 0
WorldPool.Put(w)
}
// WorldsPool ...
var WorldsPool = sync.Pool{
New: func() interface{} {
return make(Worlds, 0, 500)
},
}
// AcquireWorlds ...
func AcquireWorlds() Worlds {
return WorldsPool.Get().(Worlds)
}
// ReleaseWorlds ...ReleaseWorlds
func ReleaseWorlds(w Worlds) {
w = w[:0]
WorldsPool.Put(w)
}
// initDatabase :
func initDatabase() {
maxConn := runtime.NumCPU() * 4
if fiber.IsChild() {
maxConn = 5
}
var err error
db, err = pgxpool.New(context.Background(),
fmt.Sprintf(
"host=%s port=%d user=%s password=%s dbname=%s pool_max_conns=%d",
"tfb-database", 5432,
"benchmarkdbuser",
"benchmarkdbpass",
"hello_world",
maxConn,
))
if err != nil {
panic(err)
}
populateCache()
}
// this will populate the cached worlds for the cache test
func populateCache() {
worlds := make(Worlds, worldcount)
rows, err := db.Query(context.Background(), worldcachesql, worldcount)
if err != nil {
panic(err)
}
for i := 0; i < worldcount; i++ {
w := &worlds[i]
if !rows.Next() {
break
}
if err := rows.Scan(&w.ID, &w.RandomNumber); err != nil {
panic(err)
}
//db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)
}
cachedWorlds = worlds
}
// jsonHandler :
func jsonHandler(c *fiber.Ctx) error {
m := AcquireJSON()
m.Message = helloworld
c.JSON(&m)
ReleaseJSON(m)
return nil
}
// dbHandler :
func dbHandler(c *fiber.Ctx) error {
w := AcquireWorld()
db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)
c.JSON(&w)
ReleaseWorld(w)
return nil
}
// Frameworks/Go/fasthttp/src/server-postgresql/server.go#104
func templateHandler(c *fiber.Ctx) error {
rows, _ := db.Query(context.Background(), fortuneselectsql)
var f templates.Fortune
fortunes := make([]templates.Fortune, 0)
for rows.Next() {
_ = rows.Scan(&f.ID, &f.Message)
fortunes = append(fortunes, f)
}
rows.Close()
fortunes = append(fortunes, templates.Fortune{
Message: "Additional fortune added at request time.",
})
sort.Slice(fortunes, func(i, j int) bool {
return fortunes[i].Message < fortunes[j].Message
})
c.Response().Header.SetContentType(fiber.MIMETextHTMLCharsetUTF8)
templates.WriteFortunePage(c.Context(), fortunes)
return nil
}
// queriesHandler :
func queriesHandler(c *fiber.Ctx) error {
n := QueriesCount(c)
worlds := AcquireWorlds()[:n]
for i := 0; i < n; i++ {
w := &worlds[i]
db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)
}
c.JSON(&worlds)
ReleaseWorlds(worlds)
return nil
}
// updateHandler :
func updateHandler(c *fiber.Ctx) error {
n := QueriesCount(c)
worlds := AcquireWorlds()[:n]
for i := 0; i < n; i++ {
w := &worlds[i]
db.QueryRow(context.Background(), worldselectsql, RandomWorld()).Scan(&w.ID, &w.RandomNumber)
w.RandomNumber = int32(RandomWorld())
}
// sorting is required for insert deadlock prevention.
sort.Slice(worlds, func(i, j int) bool {
return worlds[i].ID < worlds[j].ID
})
batch := pgx.Batch{}
for _, w := range worlds {
batch.Queue(worldupdatesql, w.RandomNumber, w.ID)
}
db.SendBatch(context.Background(), &batch).Close()
c.JSON(&worlds)
ReleaseWorlds(worlds)
return nil
}
var helloworldRaw = []byte("Hello, World!")
// plaintextHandler :
func plaintextHandler(c *fiber.Ctx) error {
return c.Send(helloworldRaw)
}
// cachedHandler :
func cachedHandler(c *fiber.Ctx) error {
n := QueriesCount(c)
worlds := AcquireWorlds()[:n]
for i := 0; i < n; i++ {
worlds[i] = cachedWorlds[RandomWorld()-1]
}
c.JSON(&worlds)
ReleaseWorlds(worlds)
return nil
}
// RandomWorld :
func RandomWorld() int {
return rand.Intn(worldcount) + 1
}
// QueriesCount :
func QueriesCount(c *fiber.Ctx) int {
n := c.Request().URI().QueryArgs().GetUintOrZero(queryparam)
if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
return n
}
| package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// go test -v -run=^$ -bench=Benchmark_Plaintext -benchmem -count=4
func Benchmark_Plaintext(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/plaintext", plaintextHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/plaintext", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, helloworldRaw, body)
}
// go test -v -run=^$ -bench=Benchmark_JSON -benchmem -count=4
func Benchmark_JSON(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/json", jsonHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/json", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMEApplicationJSON, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, `{"message":"Hello, World!"}`, string(body))
}
| 18 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
package main
import (
"database/sql"
"encoding/json"
"flag"
"html/template"
"log"
"math/rand"
"net/http"
"sort"
"strconv"
"golang.org/x/net/context"
_ "github.com/go-sql-driver/mysql"
"github.com/guregu/kami"
)
type Message struct {
Message string `json:"message"`
}
type World struct {
Id uint16 `json:"id"`
RandomNumber uint16 `json:"randomNumber"`
}
type Fortune struct {
Id uint16 `json:"id"`
Message string `json:"message"`
}
// Databases
const (
connectionString = "benchmarkdbuser:benchmarkdbpass@tcp(tfb-database:3306)/hello_world?interpolateParams=true"
worldSelect = "SELECT id, randomNumber FROM World WHERE id = ?"
worldUpdate = "UPDATE World SET randomNumber = ? WHERE id = ?"
fortuneSelect = "SELECT id, message FROM Fortune;"
worldRowCount = 10000
maxConnectionCount = 256
)
const helloWorldString = "Hello, World!"
var (
// Templates
tmpl = template.Must(template.ParseFiles("templates/layout.html", "templates/fortune.html"))
// Database
db *sql.DB
helloWorldBytes = []byte(helloWorldString)
)
func main() {
var err error
db, err = sql.Open("mysql", connectionString)
if err != nil {
log.Fatalf("Error opening database: %v", err)
}
db.SetMaxIdleConns(maxConnectionCount)
flag.Set("bind", ":8080")
kami.Use("/", serverMiddleware)
kami.Get("/json", jsonHandler)
kami.Get("/db", dbHandler)
kami.Get("/queries", queriesHandler)
kami.Get("/fortunes", fortuneHandler)
kami.Get("/updates", updateHandler)
kami.Get("/plaintext", plaintextHandler)
kami.Serve()
}
// serverMiddleware will set the Server header on all outgoing requests
func serverMiddleware(ctx context.Context, w http.ResponseWriter, _ *http.Request) context.Context {
w.Header().Set("Server", "kami")
return ctx
}
// jsonHandler implements Test 1: JSON Serializer
func jsonHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&Message{helloWorldString})
}
// Test 2: Single database query
func dbHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
var world World
err := db.QueryRow(worldSelect, rand.Intn(worldRowCount)+1).Scan(&world.Id, &world.RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&world)
}
// Test 3: Multiple database queries
func queriesHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
n := 1
if nStr := r.URL.Query().Get("queries"); len(nStr) > 0 {
n, _ = strconv.Atoi(nStr)
}
if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
world := make([]World, n)
for i := 0; i < n; i++ {
err := db.QueryRow(worldSelect, rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber)
if err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(world)
}
// Test 4: Fortunes
func fortuneHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
rows, err := db.Query(fortuneSelect)
if err != nil {
log.Fatalf("Error preparing statement: %v", err)
}
fortunes := make(Fortunes, 0)
for rows.Next() { //Fetch rows
fortune := Fortune{}
if err := rows.Scan(&fortune.Id, &fortune.Message); err != nil {
log.Fatalf("Error scanning fortune row: %s", err.Error())
}
fortunes = append(fortunes, &fortune)
}
rows.Close()
fortunes = append(fortunes, &Fortune{Message: "Additional fortune added at request time."})
sort.Sort(ByMessage{fortunes})
w.Header().Set("Content-Type", "text/html;charset=utf-8")
if err := tmpl.Execute(w, fortunes); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
// Test 5: Database updates
func updateHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
n := 1
if nStr := r.URL.Query().Get("queries"); len(nStr) > 0 {
n, _ = strconv.Atoi(nStr)
}
w.Header().Set("Content-Type", "application/json")
encoder := json.NewEncoder(w)
if n < 1 {
n = 1
} else if n > 500 {
n = 500
}
world := make([]World, n)
for i := 0; i < n; i++ {
if err := db.QueryRow(worldSelect, rand.Intn(worldRowCount)+1).Scan(&world[i].Id, &world[i].RandomNumber); err != nil {
log.Fatalf("Error scanning world row: %s", err.Error())
}
world[i].RandomNumber = uint16(rand.Intn(worldRowCount) + 1)
if _, err := db.Exec(worldUpdate, world[i].RandomNumber, world[i].Id); err != nil {
log.Fatalf("Error updating world row: %s", err.Error())
}
}
encoder.Encode(world)
}
// Test 6: Plaintext
func plaintextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write(helloWorldBytes)
}
type Fortunes []*Fortune
func (s Fortunes) Len() int { return len(s) }
func (s Fortunes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByMessage struct{ Fortunes }
func (s ByMessage) Less(i, j int) bool { return s.Fortunes[i].Message < s.Fortunes[j].Message }
| package main
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/goccy/go-json"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)
// go test -v -run=^$ -bench=Benchmark_Plaintext -benchmem -count=4
func Benchmark_Plaintext(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/plaintext", plaintextHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/plaintext", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMETextPlainCharsetUTF8, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, helloworldRaw, body)
}
// go test -v -run=^$ -bench=Benchmark_JSON -benchmem -count=4
func Benchmark_JSON(b *testing.B) {
app := fiber.New(fiber.Config{
DisableStartupMessage: true,
JSONEncoder: json.Marshal,
JSONDecoder: json.Unmarshal,
})
app.Get("/json", jsonHandler)
var (
resp *http.Response
err error
)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
resp, err = app.Test(httptest.NewRequest("GET", "/json", nil))
}
utils.AssertEqual(b, nil, err, "app.Test(req)")
utils.AssertEqual(b, 200, resp.StatusCode, "Status code")
utils.AssertEqual(b, fiber.MIMEApplicationJSON, resp.Header.Get("Content-Type"))
body, _ := ioutil.ReadAll(resp.Body)
utils.AssertEqual(b, `{"message":"Hello, World!"}`, string(body))
}
| 19 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"compress/flate"
"errors"
"io"
"strings"
"sync"
)
const (
minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6
maxCompressionLevel = flate.BestCompression
defaultCompressionLevel = 1
)
var (
flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
flateReaderPool = sync.Pool{New: func() interface{} {
return flate.NewReader(nil)
}}
)
func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
const tail =
// Add four bytes as specified in RFC
"\x00\x00\xff\xff" +
// Add final block to squelch unexpected EOF error from flate reader.
"\x01\x00\x00\xff\xff"
fr, _ := flateReaderPool.Get().(io.ReadCloser)
if err := fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil); err != nil {
panic(err)
}
return &flateReadWrapper{fr}
}
func isValidCompressionLevel(level int) bool {
return minCompressionLevel <= level && level <= maxCompressionLevel
}
func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
p := &flateWriterPools[level-minCompressionLevel]
tw := &truncWriter{w: w}
fw, _ := p.Get().(*flate.Writer)
if fw == nil {
fw, _ = flate.NewWriter(tw, level)
} else {
fw.Reset(tw)
}
return &flateWriteWrapper{fw: fw, tw: tw, p: p}
}
// truncWriter is an io.Writer that writes all but the last four bytes of the
// stream to another io.Writer.
type truncWriter struct {
w io.WriteCloser
n int
p [4]byte
}
func (w *truncWriter) Write(p []byte) (int, error) {
n := 0
// fill buffer first for simplicity.
if w.n < len(w.p) {
n = copy(w.p[w.n:], p)
p = p[n:]
w.n += n
if len(p) == 0 {
return n, nil
}
}
m := len(p)
if m > len(w.p) {
m = len(w.p)
}
if nn, err := w.w.Write(w.p[:m]); err != nil {
return n + nn, err
}
copy(w.p[:], w.p[m:])
copy(w.p[len(w.p)-m:], p[len(p)-m:])
nn, err := w.w.Write(p[:len(p)-m])
return n + nn, err
}
type flateWriteWrapper struct {
fw *flate.Writer
tw *truncWriter
p *sync.Pool
}
func (w *flateWriteWrapper) Write(p []byte) (int, error) {
if w.fw == nil {
return 0, errWriteClosed
}
return w.fw.Write(p)
}
func (w *flateWriteWrapper) Close() error {
if w.fw == nil {
return errWriteClosed
}
err1 := w.fw.Flush()
w.p.Put(w.fw)
w.fw = nil
if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
}
err2 := w.tw.w.Close()
if err1 != nil {
return err1
}
return err2
}
type flateReadWrapper struct {
fr io.ReadCloser
}
func (r *flateReadWrapper) Read(p []byte) (int, error) {
if r.fr == nil {
return 0, io.ErrClosedPipe
}
n, err := r.fr.Read(p)
if err == io.EOF {
// Preemptively place the reader back in the pool. This helps with
// scenarios where the application does not call NextReader() soon after
// this final read.
_ = r.Close()
}
return n, err
}
func (r *flateReadWrapper) Close() error {
if r.fr == nil {
return io.ErrClosedPipe
}
err := r.fr.Close()
flateReaderPool.Put(r.fr)
r.fr = nil
return err
}
| package websocket
import (
"bytes"
"fmt"
"io"
"testing"
)
type nopCloser struct{ io.Writer }
func (nopCloser) Close() error { return nil }
func TestTruncWriter(t *testing.T) {
const data = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijlkmnopqrstuvwxyz987654321"
for n := 1; n <= 10; n++ {
var b bytes.Buffer
w := &truncWriter{w: nopCloser{&b}}
p := []byte(data)
for len(p) > 0 {
m := len(p)
if m > n {
m = n
}
if _, err := w.Write(p[:m]); err != nil {
t.Fatal(err)
}
p = p[m:]
}
if b.String() != data[:len(data)-len(w.p)] {
t.Errorf("%d: %q", n, b.String())
}
}
}
func textMessages(num int) [][]byte {
messages := make([][]byte, num)
for i := 0; i < num; i++ {
msg := fmt.Sprintf("planet: %d, country: %d, city: %d, street: %d", i, i, i, i)
messages[i] = []byte(msg)
}
return messages
}
func BenchmarkWriteNoCompression(b *testing.B) {
w := io.Discard
c := newTestConn(nil, w, false)
messages := textMessages(100)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := c.WriteMessage(TextMessage, messages[i%len(messages)]); err != nil {
b.Fatal(err)
}
}
b.ReportAllocs()
}
func BenchmarkWriteWithCompression(b *testing.B) {
w := io.Discard
c := newTestConn(nil, w, false)
messages := textMessages(100)
c.enableWriteCompression = true
c.newCompressionWriter = compressNoContextTakeover
b.ResetTimer()
for i := 0; i < b.N; i++ {
if err := c.WriteMessage(TextMessage, messages[i%len(messages)]); err != nil {
b.Fatal(err)
}
}
b.ReportAllocs()
}
func TestValidCompressionLevel(t *testing.T) {
c := newTestConn(nil, nil, false)
for _, level := range []int{minCompressionLevel - 1, maxCompressionLevel + 1} {
if err := c.SetCompressionLevel(level); err == nil {
t.Errorf("no error for level %d", level)
}
}
for _, level := range []int{minCompressionLevel, maxCompressionLevel} {
if err := c.SetCompressionLevel(level); err != nil {
t.Errorf("error for level %d", level)
}
}
}
| 20 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"bytes"
"net"
"sync"
"time"
)
// PreparedMessage caches on the wire representations of a message payload.
// Use PreparedMessage to efficiently send a message payload to multiple
// connections. PreparedMessage is especially useful when compression is used
// because the CPU and memory expensive compression operation can be executed
// once for a given set of compression options.
type PreparedMessage struct {
messageType int
data []byte
mu sync.Mutex
frames map[prepareKey]*preparedFrame
}
// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage.
type prepareKey struct {
isServer bool
compress bool
compressionLevel int
}
// preparedFrame contains data in wire representation.
type preparedFrame struct {
once sync.Once
data []byte
}
// NewPreparedMessage returns an initialized PreparedMessage. You can then send
// it to connection using WritePreparedMessage method. Valid wire
// representation will be calculated lazily only once for a set of current
// connection options.
func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) {
pm := &PreparedMessage{
messageType: messageType,
frames: make(map[prepareKey]*preparedFrame),
data: data,
}
// Prepare a plain server frame.
_, frameData, err := pm.frame(prepareKey{isServer: true, compress: false})
if err != nil {
return nil, err
}
// To protect against caller modifying the data argument, remember the data
// copied to the plain server frame.
pm.data = frameData[len(frameData)-len(data):]
return pm, nil
}
func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) {
pm.mu.Lock()
frame, ok := pm.frames[key]
if !ok {
frame = &preparedFrame{}
pm.frames[key] = frame
}
pm.mu.Unlock()
var err error
frame.once.Do(func() {
// Prepare a frame using a 'fake' connection.
// TODO: Refactor code in conn.go to allow more direct construction of
// the frame.
mu := make(chan struct{}, 1)
mu <- struct{}{}
var nc prepareConn
c := &Conn{
conn: &nc,
mu: mu,
isServer: key.isServer,
compressionLevel: key.compressionLevel,
enableWriteCompression: true,
writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize),
}
if key.compress {
c.newCompressionWriter = compressNoContextTakeover
}
err = c.WriteMessage(pm.messageType, pm.data)
frame.data = nc.buf.Bytes()
})
return pm.messageType, frame.data, err
}
type prepareConn struct {
buf bytes.Buffer
net.Conn
}
func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) }
func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil }
| // Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"bytes"
"compress/flate"
"math/rand"
"testing"
)
var preparedMessageTests = []struct {
messageType int
isServer bool
enableWriteCompression bool
compressionLevel int
}{
// Server
{TextMessage, true, false, flate.BestSpeed},
{TextMessage, true, true, flate.BestSpeed},
{TextMessage, true, true, flate.BestCompression},
{PingMessage, true, false, flate.BestSpeed},
{PingMessage, true, true, flate.BestSpeed},
// Client
{TextMessage, false, false, flate.BestSpeed},
{TextMessage, false, true, flate.BestSpeed},
{TextMessage, false, true, flate.BestCompression},
{PingMessage, false, false, flate.BestSpeed},
{PingMessage, false, true, flate.BestSpeed},
}
func TestPreparedMessage(t *testing.T) {
testRand := rand.New(rand.NewSource(99))
prevMaskRand := maskRand
maskRand = testRand
defer func() { maskRand = prevMaskRand }()
for _, tt := range preparedMessageTests {
var data = []byte("this is a test")
var buf bytes.Buffer
c := newTestConn(nil, &buf, tt.isServer)
if tt.enableWriteCompression {
c.newCompressionWriter = compressNoContextTakeover
}
if err := c.SetCompressionLevel(tt.compressionLevel); err != nil {
t.Fatal(err)
}
// Seed random number generator for consistent frame mask.
testRand.Seed(1234)
if err := c.WriteMessage(tt.messageType, data); err != nil {
t.Fatal(err)
}
want := buf.String()
pm, err := NewPreparedMessage(tt.messageType, data)
if err != nil {
t.Fatal(err)
}
// Scribble on data to ensure that NewPreparedMessage takes a snapshot.
copy(data, "hello world")
// Seed random number generator for consistent frame mask.
testRand.Seed(1234)
buf.Reset()
if err := c.WritePreparedMessage(pm); err != nil {
t.Fatal(err)
}
got := buf.String()
if got != want {
t.Errorf("write message != prepared message, got %#v, want %#v", got, want)
}
}
}
| 21 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2019 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"io"
"strings"
)
// JoinMessages concatenates received messages to create a single io.Reader.
// The string term is appended to each message. The returned reader does not
// support concurrent calls to the Read method.
func JoinMessages(c *Conn, term string) io.Reader {
return &joinReader{c: c, term: term}
}
type joinReader struct {
c *Conn
term string
r io.Reader
}
func (r *joinReader) Read(p []byte) (int, error) {
if r.r == nil {
var err error
_, r.r, err = r.c.NextReader()
if err != nil {
return 0, err
}
if r.term != "" {
r.r = io.MultiReader(r.r, strings.NewReader(r.term))
}
}
n, err := r.r.Read(p)
if err == io.EOF {
err = nil
r.r = nil
}
return n, err
}
| // Copyright 2019 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"bytes"
"io"
"strings"
"testing"
)
func TestJoinMessages(t *testing.T) {
messages := []string{"a", "bc", "def", "ghij", "klmno", "0", "12", "345", "6789"}
for _, readChunk := range []int{1, 2, 3, 4, 5, 6, 7} {
for _, term := range []string{"", ","} {
var connBuf bytes.Buffer
wc := newTestConn(nil, &connBuf, true)
rc := newTestConn(&connBuf, nil, false)
for _, m := range messages {
if err := wc.WriteMessage(BinaryMessage, []byte(m)); err != nil {
t.Fatalf("write %q: %v", m, err)
}
}
var result bytes.Buffer
_, err := io.CopyBuffer(&result, JoinMessages(rc, term), make([]byte, readChunk))
if IsUnexpectedCloseError(err, CloseAbnormalClosure) {
t.Errorf("readChunk=%d, term=%q: unexpected error %v", readChunk, term, err)
}
want := strings.Join(messages, term) + term
if result.String() != want {
t.Errorf("readChunk=%d, term=%q, got %q, want %q", readChunk, term, result.String(), want)
}
}
}
}
| 22 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"crypto/rand"
"crypto/sha1" //#nosec G505 -- (CWE-327) https://datatracker.ietf.org/doc/html/rfc6455#page-54
"encoding/base64"
"io"
"net/http"
"strings"
"unicode/utf8"
)
var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
func computeAcceptKey(challengeKey string) string {
h := sha1.New() //#nosec G401 -- (CWE-326) https://datatracker.ietf.org/doc/html/rfc6455#page-54
h.Write([]byte(challengeKey))
h.Write(keyGUID)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
func generateChallengeKey() (string, error) {
p := make([]byte, 16)
if _, err := io.ReadFull(rand.Reader, p); err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(p), nil
}
// Token octets per RFC 2616.
var isTokenOctet = [256]bool{
'!': true,
'#': true,
'$': true,
'%': true,
'&': true,
'\'': true,
'*': true,
'+': true,
'-': true,
'.': true,
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
'A': true,
'B': true,
'C': true,
'D': true,
'E': true,
'F': true,
'G': true,
'H': true,
'I': true,
'J': true,
'K': true,
'L': true,
'M': true,
'N': true,
'O': true,
'P': true,
'Q': true,
'R': true,
'S': true,
'T': true,
'U': true,
'W': true,
'V': true,
'X': true,
'Y': true,
'Z': true,
'^': true,
'_': true,
'`': true,
'a': true,
'b': true,
'c': true,
'd': true,
'e': true,
'f': true,
'g': true,
'h': true,
'i': true,
'j': true,
'k': true,
'l': true,
'm': true,
'n': true,
'o': true,
'p': true,
'q': true,
'r': true,
's': true,
't': true,
'u': true,
'v': true,
'w': true,
'x': true,
'y': true,
'z': true,
'|': true,
'~': true,
}
// skipSpace returns a slice of the string s with all leading RFC 2616 linear
// whitespace removed.
func skipSpace(s string) (rest string) {
i := 0
for ; i < len(s); i++ {
if b := s[i]; b != ' ' && b != '\t' {
break
}
}
return s[i:]
}
// nextToken returns the leading RFC 2616 token of s and the string following
// the token.
func nextToken(s string) (token, rest string) {
i := 0
for ; i < len(s); i++ {
if !isTokenOctet[s[i]] {
break
}
}
return s[:i], s[i:]
}
// nextTokenOrQuoted returns the leading token or quoted string per RFC 2616
// and the string following the token or quoted string.
func nextTokenOrQuoted(s string) (value string, rest string) {
if !strings.HasPrefix(s, "\"") {
return nextToken(s)
}
s = s[1:]
for i := 0; i < len(s); i++ {
switch s[i] {
case '"':
return s[:i], s[i+1:]
case '\\':
p := make([]byte, len(s)-1)
j := copy(p, s[:i])
escape := true
for i = i + 1; i < len(s); i++ {
b := s[i]
switch {
case escape:
escape = false
p[j] = b
j++
case b == '\\':
escape = true
case b == '"':
return string(p[:j]), s[i+1:]
default:
p[j] = b
j++
}
}
return "", ""
}
}
return "", ""
}
// equalASCIIFold returns true if s is equal to t with ASCII case folding as
// defined in RFC 4790.
func equalASCIIFold(s, t string) bool {
for s != "" && t != "" {
sr, size := utf8.DecodeRuneInString(s)
s = s[size:]
tr, size := utf8.DecodeRuneInString(t)
t = t[size:]
if sr == tr {
continue
}
if 'A' <= sr && sr <= 'Z' {
sr = sr + 'a' - 'A'
}
if 'A' <= tr && tr <= 'Z' {
tr = tr + 'a' - 'A'
}
if sr != tr {
return false
}
}
return s == t
}
// tokenListContainsValue returns true if the 1#token header with the given
// name contains a token equal to value with ASCII case folding.
func tokenListContainsValue(header http.Header, name string, value string) bool {
headers:
for _, s := range header[name] {
for {
var t string
t, s = nextToken(skipSpace(s))
if t == "" {
continue headers
}
s = skipSpace(s)
if s != "" && s[0] != ',' {
continue headers
}
if equalASCIIFold(t, value) {
return true
}
if s == "" {
continue headers
}
s = s[1:]
}
}
return false
}
// parseExtensions parses WebSocket extensions from a header.
func parseExtensions(header http.Header) []map[string]string {
// From RFC 6455:
//
// Sec-WebSocket-Extensions = extension-list
// extension-list = 1#extension
// extension = extension-token *( ";" extension-param )
// extension-token = registered-token
// registered-token = token
// extension-param = token [ "=" (token | quoted-string) ]
// ;When using the quoted-string syntax variant, the value
// ;after quoted-string unescaping MUST conform to the
// ;'token' ABNF.
var result []map[string]string
headers:
for _, s := range header["Sec-Websocket-Extensions"] {
for {
var t string
t, s = nextToken(skipSpace(s))
if t == "" {
continue headers
}
ext := map[string]string{"": t}
for {
s = skipSpace(s)
if !strings.HasPrefix(s, ";") {
break
}
var k string
k, s = nextToken(skipSpace(s[1:]))
if k == "" {
continue headers
}
s = skipSpace(s)
var v string
if strings.HasPrefix(s, "=") {
v, s = nextTokenOrQuoted(skipSpace(s[1:]))
s = skipSpace(s)
}
if s != "" && s[0] != ',' && s[0] != ';' {
continue headers
}
ext[k] = v
}
if s != "" && s[0] != ',' {
continue headers
}
result = append(result, ext)
if s == "" {
continue headers
}
s = s[1:]
}
}
return result
}
// isValidChallengeKey checks if the argument meets RFC6455 specification.
func isValidChallengeKey(s string) bool {
// From RFC6455:
//
// A |Sec-WebSocket-Key| header field with a base64-encoded (see
// Section 4 of [RFC4648]) value that, when decoded, is 16 bytes in
// length.
if s == "" {
return false
}
decoded, err := base64.StdEncoding.DecodeString(s)
return err == nil && len(decoded) == 16
}
| // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"net/http"
"reflect"
"testing"
)
var equalASCIIFoldTests = []struct {
t, s string
eq bool
}{
{"WebSocket", "websocket", true},
{"websocket", "WebSocket", true},
{"Öyster", "öyster", false},
{"WebSocket", "WetSocket", false},
}
func TestEqualASCIIFold(t *testing.T) {
for _, tt := range equalASCIIFoldTests {
eq := equalASCIIFold(tt.s, tt.t)
if eq != tt.eq {
t.Errorf("equalASCIIFold(%q, %q) = %v, want %v", tt.s, tt.t, eq, tt.eq)
}
}
}
var tokenListContainsValueTests = []struct {
value string
ok bool
}{
{"WebSocket", true},
{"WEBSOCKET", true},
{"websocket", true},
{"websockets", false},
{"x websocket", false},
{"websocket x", false},
{"other,websocket,more", true},
{"other, websocket, more", true},
}
func TestTokenListContainsValue(t *testing.T) {
for _, tt := range tokenListContainsValueTests {
h := http.Header{"Upgrade": {tt.value}}
ok := tokenListContainsValue(h, "Upgrade", "websocket")
if ok != tt.ok {
t.Errorf("tokenListContainsValue(h, n, %q) = %v, want %v", tt.value, ok, tt.ok)
}
}
}
var isValidChallengeKeyTests = []struct {
key string
ok bool
}{
{"dGhlIHNhbXBsZSBub25jZQ==", true},
{"", false},
{"InvalidKey", false},
{"WHQ4eXhscUtKYjBvOGN3WEdtOEQ=", false},
}
func TestIsValidChallengeKey(t *testing.T) {
for _, tt := range isValidChallengeKeyTests {
ok := isValidChallengeKey(tt.key)
if ok != tt.ok {
t.Errorf("isValidChallengeKey returns %v, want %v", ok, tt.ok)
}
}
}
var parseExtensionTests = []struct {
value string
extensions []map[string]string
}{
{`foo`, []map[string]string{{"": "foo"}}},
{`foo, bar; baz=2`, []map[string]string{
{"": "foo"},
{"": "bar", "baz": "2"}}},
{`foo; bar="b,a;z"`, []map[string]string{
{"": "foo", "bar": "b,a;z"}}},
{`foo , bar; baz = 2`, []map[string]string{
{"": "foo"},
{"": "bar", "baz": "2"}}},
{`foo, bar; baz=2 junk`, []map[string]string{
{"": "foo"}}},
{`foo junk, bar; baz=2 junk`, nil},
{`mux; max-channels=4; flow-control, deflate-stream`, []map[string]string{
{"": "mux", "max-channels": "4", "flow-control": ""},
{"": "deflate-stream"}}},
{`permessage-foo; x="10"`, []map[string]string{
{"": "permessage-foo", "x": "10"}}},
{`permessage-foo; use_y, permessage-foo`, []map[string]string{
{"": "permessage-foo", "use_y": ""},
{"": "permessage-foo"}}},
{`permessage-deflate; client_max_window_bits; server_max_window_bits=10 , permessage-deflate; client_max_window_bits`, []map[string]string{
{"": "permessage-deflate", "client_max_window_bits": "", "server_max_window_bits": "10"},
{"": "permessage-deflate", "client_max_window_bits": ""}}},
{"permessage-deflate; server_no_context_takeover; client_max_window_bits=15", []map[string]string{
{"": "permessage-deflate", "server_no_context_takeover": "", "client_max_window_bits": "15"},
}},
}
func TestParseExtensions(t *testing.T) {
for _, tt := range parseExtensionTests {
h := http.Header{http.CanonicalHeaderKey("Sec-WebSocket-Extensions"): {tt.value}}
extensions := parseExtensions(h)
if !reflect.DeepEqual(extensions, tt.extensions) {
t.Errorf("parseExtensions(%q)\n = %v,\nwant %v", tt.value, extensions, tt.extensions)
}
}
}
| 23 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
//go:build !appengine
// +build !appengine
package websocket
import "unsafe"
// #nosec G103 -- (CWE-242) Has been audited
const wordSize = int(unsafe.Sizeof(uintptr(0)))
func maskBytes(key [4]byte, pos int, b []byte) int {
// Mask one byte at a time for small buffers.
if len(b) < 2*wordSize {
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
// Mask one byte at a time to word boundary.
//#nosec G103 -- (CWE-242) Has been audited
if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
n = wordSize - n
for i := range b[:n] {
b[i] ^= key[pos&3]
pos++
}
b = b[n:]
}
// Create aligned word size key.
var k [wordSize]byte
for i := range k {
k[i] = key[(pos+i)&3]
}
//#nosec G103 -- (CWE-242) Has been audited
kw := *(*uintptr)(unsafe.Pointer(&k))
// Mask one word at a time.
n := (len(b) / wordSize) * wordSize
for i := 0; i < n; i += wordSize {
//#nosec G103 -- (CWE-242) Has been audited
*(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw
}
// Mask one byte at a time for remaining bytes.
b = b[n:]
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
| // Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
// !appengine
package websocket
import (
"fmt"
"testing"
)
func maskBytesByByte(key [4]byte, pos int, b []byte) int {
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
func notzero(b []byte) int {
for i := range b {
if b[i] != 0 {
return i
}
}
return -1
}
func TestMaskBytes(t *testing.T) {
key := [4]byte{1, 2, 3, 4}
for size := 1; size <= 1024; size++ {
for align := 0; align < wordSize; align++ {
for pos := 0; pos < 4; pos++ {
b := make([]byte, size+align)[align:]
maskBytes(key, pos, b)
maskBytesByByte(key, pos, b)
if i := notzero(b); i >= 0 {
t.Errorf("size:%d, align:%d, pos:%d, offset:%d", size, align, pos, i)
}
}
}
}
}
func BenchmarkMaskBytes(b *testing.B) {
for _, size := range []int{2, 4, 8, 16, 32, 512, 1024} {
b.Run(fmt.Sprintf("size-%d", size), func(b *testing.B) {
for _, align := range []int{wordSize / 2} {
b.Run(fmt.Sprintf("align-%d", align), func(b *testing.B) {
for _, fn := range []struct {
name string
fn func(key [4]byte, pos int, b []byte) int
}{
{"byte", maskBytesByByte},
{"word", maskBytes},
} {
b.Run(fn.name, func(b *testing.B) {
key := newMaskKey()
data := make([]byte, size+align)[align:]
for i := 0; i < b.N; i++ {
fn.fn(key, 0, data)
}
b.SetBytes(int64(len(data)))
})
}
})
}
})
}
}
| 24 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"bytes"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/httptrace"
"net/url"
"strings"
"time"
"golang.org/x/net/proxy"
)
// ErrBadHandshake is returned when the server response to opening handshake is
// invalid.
var ErrBadHandshake = errors.New("websocket: bad handshake")
var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
// NewClient creates a new client connection using the given net connection.
// The URL u specifies the host and request URI. Use requestHeader to specify
// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
// (Cookie). Use the response.Header to get the selected subprotocol
// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
//
// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
// non-nil *http.Response so that callers can handle redirects, authentication,
// etc.
//
// Deprecated: Use Dialer instead.
func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
d := Dialer{
ReadBufferSize: readBufSize,
WriteBufferSize: writeBufSize,
NetDial: func(net, addr string) (net.Conn, error) {
return netConn, nil
},
}
return d.Dial(u.String(), requestHeader)
}
// A Dialer contains options for connecting to WebSocket server.
//
// It is safe to call Dialer's methods concurrently.
type Dialer struct {
// NetDial specifies the dial function for creating TCP connections. If
// NetDial is nil, net.Dial is used.
NetDial func(network, addr string) (net.Conn, error)
// NetDialContext specifies the dial function for creating TCP connections. If
// NetDialContext is nil, NetDial is used.
NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
// NetDialTLSContext specifies the dial function for creating TLS/TCP connections. If
// NetDialTLSContext is nil, NetDialContext is used.
// If NetDialTLSContext is set, Dial assumes the TLS handshake is done there and
// TLSClientConfig is ignored.
NetDialTLSContext func(ctx context.Context, network, addr string) (net.Conn, error)
// Proxy specifies a function to return a proxy for a given
// Request. If the function returns a non-nil error, the
// request is aborted with the provided error.
// If Proxy is nil or returns a nil *URL, no proxy is used.
Proxy func(*http.Request) (*url.URL, error)
// TLSClientConfig specifies the TLS configuration to use with tls.Client.
// If nil, the default configuration is used.
// If either NetDialTLS or NetDialTLSContext are set, Dial assumes the TLS handshake
// is done there and TLSClientConfig is ignored.
TLSClientConfig *tls.Config
// HandshakeTimeout specifies the duration for the handshake to complete.
HandshakeTimeout time.Duration
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
// size is zero, then a useful default size is used. The I/O buffer sizes
// do not limit the size of the messages that can be sent or received.
ReadBufferSize, WriteBufferSize int
// WriteBufferPool is a pool of buffers for write operations. If the value
// is not set, then write buffers are allocated to the connection for the
// lifetime of the connection.
//
// A pool is most useful when the application has a modest volume of writes
// across a large number of connections.
//
// Applications should use a single pool for each unique value of
// WriteBufferSize.
WriteBufferPool BufferPool
// Subprotocols specifies the client's requested subprotocols.
Subprotocols []string
// EnableCompression specifies if the client should attempt to negotiate
// per message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
// Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
Jar http.CookieJar
}
// Dial creates a new client connection by calling DialContext with a background context.
func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
return d.DialContext(context.Background(), urlStr, requestHeader)
}
var errMalformedURL = errors.New("malformed ws or wss URL")
func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
hostPort = u.Host
hostNoPort = u.Host
if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
hostNoPort = hostNoPort[:i]
} else {
switch u.Scheme {
case "wss":
hostPort += ":443"
case "https":
hostPort += ":443"
default:
hostPort += ":80"
}
}
return hostPort, hostNoPort
}
// DefaultDialer is a dialer with all fields set to the default values.
var DefaultDialer = &Dialer{
Proxy: http.ProxyFromEnvironment,
HandshakeTimeout: 45 * time.Second,
}
// nilDialer is dialer to use when receiver is nil.
var nilDialer = *DefaultDialer
// DialContext creates a new client connection. Use requestHeader to specify the
// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
// Use the response.Header to get the selected subprotocol
// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
//
// The context will be used in the request and in the Dialer.
//
// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
// non-nil *http.Response so that callers can handle redirects, authentication,
// etcetera. The response body may not contain the entire response and does not
// need to be closed by the application.
func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
if d == nil {
d = &nilDialer
}
challengeKey, err := generateChallengeKey()
if err != nil {
return nil, nil, err
}
u, err := url.Parse(urlStr)
if err != nil {
return nil, nil, err
}
switch u.Scheme {
case "ws":
u.Scheme = "http"
case "wss":
u.Scheme = "https"
default:
return nil, nil, errMalformedURL
}
if u.User != nil {
// User name and password are not allowed in websocket URIs.
return nil, nil, errMalformedURL
}
req := &http.Request{
Method: http.MethodGet,
URL: u,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: make(http.Header),
Host: u.Host,
}
req = req.WithContext(ctx)
// Set the cookies present in the cookie jar of the dialer
if d.Jar != nil {
for _, cookie := range d.Jar.Cookies(u) {
req.AddCookie(cookie)
}
}
// Set the request headers using the capitalization for names and values in
// RFC examples. Although the capitalization shouldn't matter, there are
// servers that depend on it. The Header.Set method is not used because the
// method canonicalizes the header names.
req.Header["Upgrade"] = []string{"websocket"}
req.Header["Connection"] = []string{"Upgrade"}
req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
req.Header["Sec-WebSocket-Version"] = []string{"13"}
if len(d.Subprotocols) > 0 {
req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
}
for k, vs := range requestHeader {
switch {
case k == "Host":
if len(vs) > 0 {
req.Host = vs[0]
}
case k == "Upgrade" ||
k == "Connection" ||
k == "Sec-Websocket-Key" ||
k == "Sec-Websocket-Version" ||
//#nosec G101 (CWE-798): Potential HTTP request smuggling via parameter pollution
k == "Sec-Websocket-Extensions" ||
(k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
case k == "Sec-Websocket-Protocol":
req.Header["Sec-WebSocket-Protocol"] = vs
default:
req.Header[k] = vs
}
}
if d.EnableCompression {
req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"}
}
if d.HandshakeTimeout != 0 {
var cancel func()
ctx, cancel = context.WithTimeout(ctx, d.HandshakeTimeout)
defer cancel()
}
// Get network dial function.
var netDial func(network, add string) (net.Conn, error)
switch u.Scheme {
case "http":
if d.NetDialContext != nil {
netDial = func(network, addr string) (net.Conn, error) {
return d.NetDialContext(ctx, network, addr)
}
} else if d.NetDial != nil {
netDial = d.NetDial
}
case "https":
if d.NetDialTLSContext != nil {
netDial = func(network, addr string) (net.Conn, error) {
return d.NetDialTLSContext(ctx, network, addr)
}
} else if d.NetDialContext != nil {
netDial = func(network, addr string) (net.Conn, error) {
return d.NetDialContext(ctx, network, addr)
}
} else if d.NetDial != nil {
netDial = d.NetDial
}
default:
return nil, nil, errMalformedURL
}
if netDial == nil {
netDialer := &net.Dialer{}
netDial = func(network, addr string) (net.Conn, error) {
return netDialer.DialContext(ctx, network, addr)
}
}
// If needed, wrap the dial function to set the connection deadline.
if deadline, ok := ctx.Deadline(); ok {
forwardDial := netDial
netDial = func(network, addr string) (net.Conn, error) {
c, err := forwardDial(network, addr)
if err != nil {
return nil, err
}
err = c.SetDeadline(deadline)
if err != nil {
if err := c.Close(); err != nil {
log.Printf("websocket: failed to close network connection: %v", err)
}
return nil, err
}
return c, nil
}
}
// If needed, wrap the dial function to connect through a proxy.
if d.Proxy != nil {
proxyURL, err := d.Proxy(req)
if err != nil {
return nil, nil, err
}
if proxyURL != nil {
dialer, err := proxy.FromURL(proxyURL, netDialerFunc(netDial))
if err != nil {
return nil, nil, err
}
netDial = dialer.Dial
}
}
hostPort, hostNoPort := hostPortNoPort(u)
trace := httptrace.ContextClientTrace(ctx)
if trace != nil && trace.GetConn != nil {
trace.GetConn(hostPort)
}
netConn, err := netDial("tcp", hostPort)
if err != nil {
return nil, nil, err
}
if trace != nil && trace.GotConn != nil {
trace.GotConn(httptrace.GotConnInfo{
Conn: netConn,
})
}
defer func() {
if netConn != nil {
if err := netConn.Close(); err != nil {
log.Printf("websocket: failed to close network connection: %v", err)
}
}
}()
if u.Scheme == "https" && d.NetDialTLSContext == nil {
// If NetDialTLSContext is set, assume that the TLS handshake has already been done
cfg := cloneTLSConfig(d.TLSClientConfig)
if cfg.ServerName == "" {
cfg.ServerName = hostNoPort
}
tlsConn := tls.Client(netConn, cfg)
netConn = tlsConn
if trace != nil && trace.TLSHandshakeStart != nil {
trace.TLSHandshakeStart()
}
err := doHandshake(ctx, tlsConn, cfg)
if trace != nil && trace.TLSHandshakeDone != nil {
trace.TLSHandshakeDone(tlsConn.ConnectionState(), err)
}
if err != nil {
return nil, nil, err
}
}
conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize, d.WriteBufferPool, nil, nil)
if err := req.Write(netConn); err != nil {
return nil, nil, err
}
if trace != nil && trace.GotFirstResponseByte != nil {
if peek, err := conn.br.Peek(1); err == nil && len(peek) == 1 {
trace.GotFirstResponseByte()
}
}
resp, err := http.ReadResponse(conn.br, req)
if err != nil {
if d.TLSClientConfig != nil {
for _, proto := range d.TLSClientConfig.NextProtos {
if proto != "http/1.1" {
return nil, nil, fmt.Errorf(
"websocket: protocol %q was given but is not supported;"+
"sharing tls.Config with net/http Transport can cause this error: %w",
proto, err,
)
}
}
}
return nil, nil, err
}
if d.Jar != nil {
if rc := resp.Cookies(); len(rc) > 0 {
d.Jar.SetCookies(u, rc)
}
}
if resp.StatusCode != http.StatusSwitchingProtocols ||
!tokenListContainsValue(resp.Header, "Upgrade", "websocket") ||
!tokenListContainsValue(resp.Header, "Connection", "upgrade") ||
resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
// Before closing the network connection on return from this
// function, slurp up some of the response to aid application
// debugging.
buf := make([]byte, 1024)
n, _ := io.ReadFull(resp.Body, buf)
resp.Body = io.NopCloser(bytes.NewReader(buf[:n]))
return nil, resp, ErrBadHandshake
}
for _, ext := range parseExtensions(resp.Header) {
if ext[""] != "permessage-deflate" {
continue
}
_, snct := ext["server_no_context_takeover"]
_, cnct := ext["client_no_context_takeover"]
if !snct || !cnct {
return nil, resp, errInvalidCompression
}
conn.newCompressionWriter = compressNoContextTakeover
conn.newDecompressionReader = decompressNoContextTakeover
break
}
resp.Body = io.NopCloser(bytes.NewReader([]byte{}))
conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
if err := netConn.SetDeadline(time.Time{}); err != nil {
return nil, nil, err
}
netConn = nil // to avoid close in defer.
return conn, resp, nil
}
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{MinVersion: tls.VersionTLS12}
}
return cfg.Clone()
}
| // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"net/url"
"testing"
)
var hostPortNoPortTests = []struct {
u *url.URL
hostPort, hostNoPort string
}{
{&url.URL{Scheme: "ws", Host: "example.com"}, "example.com:80", "example.com"},
{&url.URL{Scheme: "wss", Host: "example.com"}, "example.com:443", "example.com"},
{&url.URL{Scheme: "ws", Host: "example.com:7777"}, "example.com:7777", "example.com"},
{&url.URL{Scheme: "wss", Host: "example.com:7777"}, "example.com:7777", "example.com"},
}
func TestHostPortNoPort(t *testing.T) {
for _, tt := range hostPortNoPortTests {
hostPort, hostNoPort := hostPortNoPort(tt.u)
if hostPort != tt.hostPort {
t.Errorf("hostPortNoPort(%v) returned hostPort %q, want %q", tt.u, hostPort, tt.hostPort)
}
if hostNoPort != tt.hostNoPort {
t.Errorf("hostPortNoPort(%v) returned hostNoPort %q, want %q", tt.u, hostNoPort, tt.hostNoPort)
}
}
}
| 25 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
// Copyright 2018 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package socks
import (
"context"
"errors"
"io"
"net"
"strconv"
"time"
)
var (
noDeadline = time.Time{}
aLongTimeAgo = time.Unix(1, 0)
)
func (d *Dialer) connect(ctx context.Context, c net.Conn, address string) (_ net.Addr, ctxErr error) {
host, port, err := splitHostPort(address)
if err != nil {
return nil, err
}
if deadline, ok := ctx.Deadline(); ok && !deadline.IsZero() {
c.SetDeadline(deadline)
defer c.SetDeadline(noDeadline)
}
if ctx != context.Background() {
errCh := make(chan error, 1)
done := make(chan struct{})
defer func() {
close(done)
if ctxErr == nil {
ctxErr = <-errCh
}
}()
go func() {
select {
case <-ctx.Done():
c.SetDeadline(aLongTimeAgo)
errCh <- ctx.Err()
case <-done:
errCh <- nil
}
}()
}
b := make([]byte, 0, 6+len(host)) // the size here is just an estimate
b = append(b, Version5)
if len(d.AuthMethods) == 0 || d.Authenticate == nil {
b = append(b, 1, byte(AuthMethodNotRequired))
} else {
ams := d.AuthMethods
if len(ams) > 255 {
return nil, errors.New("too many authentication methods")
}
b = append(b, byte(len(ams)))
for _, am := range ams {
b = append(b, byte(am))
}
}
if _, ctxErr = c.Write(b); ctxErr != nil {
return
}
if _, ctxErr = io.ReadFull(c, b[:2]); ctxErr != nil {
return
}
if b[0] != Version5 {
return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0])))
}
am := AuthMethod(b[1])
if am == AuthMethodNoAcceptableMethods {
return nil, errors.New("no acceptable authentication methods")
}
if d.Authenticate != nil {
if ctxErr = d.Authenticate(ctx, c, am); ctxErr != nil {
return
}
}
b = b[:0]
b = append(b, Version5, byte(d.cmd), 0)
if ip := net.ParseIP(host); ip != nil {
if ip4 := ip.To4(); ip4 != nil {
b = append(b, AddrTypeIPv4)
b = append(b, ip4...)
} else if ip6 := ip.To16(); ip6 != nil {
b = append(b, AddrTypeIPv6)
b = append(b, ip6...)
} else {
return nil, errors.New("unknown address type")
}
} else {
if len(host) > 255 {
return nil, errors.New("FQDN too long")
}
b = append(b, AddrTypeFQDN)
b = append(b, byte(len(host)))
b = append(b, host...)
}
b = append(b, byte(port>>8), byte(port))
if _, ctxErr = c.Write(b); ctxErr != nil {
return
}
if _, ctxErr = io.ReadFull(c, b[:4]); ctxErr != nil {
return
}
if b[0] != Version5 {
return nil, errors.New("unexpected protocol version " + strconv.Itoa(int(b[0])))
}
if cmdErr := Reply(b[1]); cmdErr != StatusSucceeded {
return nil, errors.New("unknown error " + cmdErr.String())
}
if b[2] != 0 {
return nil, errors.New("non-zero reserved field")
}
l := 2
var a Addr
switch b[3] {
case AddrTypeIPv4:
l += net.IPv4len
a.IP = make(net.IP, net.IPv4len)
case AddrTypeIPv6:
l += net.IPv6len
a.IP = make(net.IP, net.IPv6len)
case AddrTypeFQDN:
if _, err := io.ReadFull(c, b[:1]); err != nil {
return nil, err
}
l += int(b[0])
default:
return nil, errors.New("unknown address type " + strconv.Itoa(int(b[3])))
}
if cap(b) < l {
b = make([]byte, l)
} else {
b = b[:l]
}
if _, ctxErr = io.ReadFull(c, b); ctxErr != nil {
return
}
if a.IP != nil {
copy(a.IP, b)
} else {
a.Name = string(b[:len(b)-2])
}
a.Port = int(b[len(b)-2])<<8 | int(b[len(b)-1])
return &a, nil
}
func splitHostPort(address string) (string, int, error) {
host, port, err := net.SplitHostPort(address)
if err != nil {
return "", 0, err
}
portnum, err := strconv.Atoi(port)
if err != nil {
return "", 0, err
}
if 1 > portnum || portnum > 0xffff {
return "", 0, errors.New("port number out of range " + port)
}
return host, portnum, nil
}
| // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"net/url"
"testing"
)
var hostPortNoPortTests = []struct {
u *url.URL
hostPort, hostNoPort string
}{
{&url.URL{Scheme: "ws", Host: "example.com"}, "example.com:80", "example.com"},
{&url.URL{Scheme: "wss", Host: "example.com"}, "example.com:443", "example.com"},
{&url.URL{Scheme: "ws", Host: "example.com:7777"}, "example.com:7777", "example.com"},
{&url.URL{Scheme: "wss", Host: "example.com:7777"}, "example.com:7777", "example.com"},
}
func TestHostPortNoPort(t *testing.T) {
for _, tt := range hostPortNoPortTests {
hostPort, hostNoPort := hostPortNoPort(tt.u)
if hostPort != tt.hostPort {
t.Errorf("hostPortNoPort(%v) returned hostPort %q, want %q", tt.u, hostPort, tt.hostPort)
}
if hostNoPort != tt.hostNoPort {
t.Errorf("hostPortNoPort(%v) returned hostNoPort %q, want %q", tt.u, hostNoPort, tt.hostNoPort)
}
}
}
| 26 |
Review the shared code context and generate a suite of multiple unit tests for the functions in shared code context using the detected test framework and libraries.
Code context:
//go:build ignore
// +build ignore
package main
import (
"flag"
"log"
"net/url"
"os"
"os/signal"
"sync"
"time"
"github.com/gorilla/websocket"
)
var addr = flag.String("addr", "localhost:8080", "http service address")
func runNewConn(wg *sync.WaitGroup) {
defer wg.Done()
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
u := url.URL{Scheme: "ws", Host: *addr, Path: "/ws"}
log.Printf("connecting to %s", u.String())
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatal("dial:", err)
}
defer c.Close()
done := make(chan struct{})
go func() {
defer close(done)
for {
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
return
}
log.Printf("recv: %s", message)
}
}()
ticker := time.NewTicker(time.Minute * 5)
defer ticker.Stop()
for {
select {
case <-done:
return
case t := <-ticker.C:
err := c.WriteMessage(websocket.TextMessage, []byte(t.String()))
if err != nil {
log.Println("write:", err)
return
}
case <-interrupt:
log.Println("interrupt")
// Cleanly close the connection by sending a close message and then
// waiting (with timeout) for the server to close the connection.
err := c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
if err != nil {
log.Println("write close:", err)
return
}
select {
case <-done:
case <-time.After(time.Second):
}
return
}
}
}
func main() {
flag.Parse()
log.SetFlags(0)
wg := &sync.WaitGroup{}
for i := 0; i < 1000; i++ {
wg.Add(1)
go runNewConn(wg)
}
wg.Wait()
}
| // Copyright 2014 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"net/url"
"testing"
)
var hostPortNoPortTests = []struct {
u *url.URL
hostPort, hostNoPort string
}{
{&url.URL{Scheme: "ws", Host: "example.com"}, "example.com:80", "example.com"},
{&url.URL{Scheme: "wss", Host: "example.com"}, "example.com:443", "example.com"},
{&url.URL{Scheme: "ws", Host: "example.com:7777"}, "example.com:7777", "example.com"},
{&url.URL{Scheme: "wss", Host: "example.com:7777"}, "example.com:7777", "example.com"},
}
func TestHostPortNoPort(t *testing.T) {
for _, tt := range hostPortNoPortTests {
hostPort, hostNoPort := hostPortNoPort(tt.u)
if hostPort != tt.hostPort {
t.Errorf("hostPortNoPort(%v) returned hostPort %q, want %q", tt.u, hostPort, tt.hostPort)
}
if hostNoPort != tt.hostNoPort {
t.Errorf("hostPortNoPort(%v) returned hostNoPort %q, want %q", tt.u, hostNoPort, tt.hostNoPort)
}
}
}
| 27 |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 46