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
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 main import ( "bytes" "log" "net/http" "time" "github.com/gorilla/websocket" ) const ( // Time allowed to write a message to the peer. writeWait = 10 * time.Second // Time allowed to read the next pong message from the peer. pongWait = 60 * time.Second // Send pings to peer with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Maximum message size allowed from peer. maxMessageSize = 512 ) var ( newline = []byte{'\n'} space = []byte{' '} ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, } // Client is a middleman between the websocket connection and the hub. type Client struct { hub *Hub // The websocket connection. conn *websocket.Conn // Buffered channel of outbound messages. send chan []byte } // readPump pumps messages from the websocket connection to the hub. // // The application runs readPump in a per-connection goroutine. The application // ensures that there is at most one reader on a connection by executing all // reads from this goroutine. func (c *Client) readPump() { defer func() { c.hub.unregister <- c c.conn.Close() }() c.conn.SetReadLimit(maxMessageSize) c.conn.SetReadDeadline(time.Now().Add(pongWait)) c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil }) for { _, message, err := c.conn.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) { log.Printf("error: %v", err) } break } message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1)) c.hub.broadcast <- message } } // writePump pumps messages from the hub to the websocket connection. // // A goroutine running writePump is started for each connection. The // application ensures that there is at most one writer to a connection by // executing all writes from this goroutine. func (c *Client) writePump() { ticker := time.NewTicker(pingPeriod) defer func() { ticker.Stop() c.conn.Close() }() for { select { case message, ok := <-c.send: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if !ok { // The hub closed the channel. c.conn.WriteMessage(websocket.CloseMessage, []byte{}) return } w, err := c.conn.NextWriter(websocket.TextMessage) if err != nil { return } w.Write(message) // Add queued chat messages to the current websocket message. n := len(c.send) for i := 0; i < n; i++ { w.Write(newline) w.Write(<-c.send) } if err := w.Close(); err != nil { return } case <-ticker.C: c.conn.SetWriteDeadline(time.Now().Add(writeWait)) if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil { return } } } } // serveWs handles websocket requests from the peer. func serveWs(hub *Hub, w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println(err) return } client := &Client{hub: hub, conn: conn, send: make(chan []byte, 256)} client.hub.register <- client // Allow collection of memory referenced by the caller by doing all work in // new goroutines. go client.writePump() go client.readPump() }
// 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) } } }
28
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 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 ignore // +build ignore package main import ( "flag" "log" "net/url" "os" "os/signal" "time" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:8080", "http service address") func main() { flag.Parse() log.SetFlags(0) interrupt := make(chan os.Signal, 1) signal.Notify(interrupt, os.Interrupt) u := url.URL{Scheme: "ws", Host: *addr, Path: "/echo"} 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.Second) 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 } } }
// 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) } } }
29
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 ( "bufio" "errors" "io" "log" "net/http" "net/url" "strings" "time" ) // HandshakeError describes an error with the handshake from the peer. type HandshakeError struct { message string } func (e HandshakeError) Error() string { return e.message } // Upgrader specifies parameters for upgrading an HTTP connection to a // WebSocket connection. // // It is safe to call Upgrader's methods concurrently. type Upgrader struct { // 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 buffers allocated by the HTTP server are used. The // I/O buffer sizes do not limit the size of the messages that can be sent // or received. // The default value is 4096 bytes, 4kb. 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 server's supported protocols in order of // preference. If this field is not nil, then the Upgrade method negotiates a // subprotocol by selecting the first match in this list with a protocol // requested by the client. If there's no match, then no protocol is // negotiated (the Sec-Websocket-Protocol header is not included in the // handshake response). Subprotocols []string // Error specifies the function for generating HTTP error responses. If Error // is nil, then http.Error is used to generate the HTTP response. Error func(w http.ResponseWriter, r *http.Request, status int, reason error) // CheckOrigin returns true if the request Origin header is acceptable. If // CheckOrigin is nil, then a safe default is used: return false if the // Origin request header is present and the origin host is not equal to // request Host header. // // A CheckOrigin function should carefully validate the request origin to // prevent cross-site request forgery. CheckOrigin func(r *http.Request) bool // EnableCompression specify if the server 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 } func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) { err := HandshakeError{reason} if u.Error != nil { u.Error(w, r, status, err) } else { w.Header().Set("Sec-Websocket-Version", "13") http.Error(w, http.StatusText(status), status) } return nil, err } // checkSameOrigin returns true if the origin is not set or is equal to the request host. func checkSameOrigin(r *http.Request) bool { origin := r.Header["Origin"] if len(origin) == 0 { return true } u, err := url.Parse(origin[0]) if err != nil { return false } return equalASCIIFold(u.Host, r.Host) } func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string { if u.Subprotocols != nil { clientProtocols := Subprotocols(r) for _, clientProtocol := range clientProtocols { for _, serverProtocol := range u.Subprotocols { if clientProtocol == serverProtocol { return clientProtocol } } } } else if responseHeader != nil { return responseHeader.Get("Sec-Websocket-Protocol") } return "" } // Upgrade upgrades the HTTP server connection to the WebSocket protocol. // // The responseHeader is included in the response to the client's upgrade // request. Use the responseHeader to specify cookies (Set-Cookie). To specify // subprotocols supported by the server, set Upgrader.Subprotocols directly. // // If the upgrade fails, then Upgrade replies to the client with an HTTP error // response. func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) { const badHandshake = "websocket: the client is not using the websocket protocol: " if !tokenListContainsValue(r.Header, "Connection", "upgrade") { return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header") } if !tokenListContainsValue(r.Header, "Upgrade", "websocket") { return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header") } if r.Method != http.MethodGet { return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET") } if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") { return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header") } if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok { return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported") } checkOrigin := u.CheckOrigin if checkOrigin == nil { checkOrigin = checkSameOrigin } if !checkOrigin(r) { return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin") } challengeKey := r.Header.Get("Sec-Websocket-Key") if !isValidChallengeKey(challengeKey) { return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'Sec-WebSocket-Key' header must be Base64 encoded value of 16-byte in length") } subprotocol := u.selectSubprotocol(r, responseHeader) // Negotiate PMCE var compress bool if u.EnableCompression { for _, ext := range parseExtensions(r.Header) { if ext[""] != "permessage-deflate" { continue } compress = true break } } h, ok := w.(http.Hijacker) if !ok { return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker") } var brw *bufio.ReadWriter netConn, brw, err := h.Hijack() if err != nil { return u.returnError(w, r, http.StatusInternalServerError, err.Error()) } if brw.Reader.Buffered() > 0 { if err := netConn.Close(); err != nil { log.Printf("websocket: failed to close network connection: %v", err) } return nil, errors.New("websocket: client sent data before handshake is complete") } var br *bufio.Reader if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 { // Reuse hijacked buffered reader as connection reader. br = brw.Reader } buf := bufioWriterBuffer(netConn, brw.Writer) var writeBuf []byte if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 { // Reuse hijacked write buffer as connection buffer. writeBuf = buf } c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf) c.subprotocol = subprotocol if compress { c.newCompressionWriter = compressNoContextTakeover c.newDecompressionReader = decompressNoContextTakeover } // Use larger of hijacked buffer and connection write buffer for header. p := buf if len(c.writeBuf) > len(p) { p = c.writeBuf } p = p[:0] p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...) p = append(p, computeAcceptKey(challengeKey)...) p = append(p, "\r\n"...) if c.subprotocol != "" { p = append(p, "Sec-WebSocket-Protocol: "...) p = append(p, c.subprotocol...) p = append(p, "\r\n"...) } if compress { p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...) } for k, vs := range responseHeader { if k == "Sec-Websocket-Protocol" { continue } for _, v := range vs { p = append(p, k...) p = append(p, ": "...) for i := 0; i < len(v); i++ { b := v[i] if b <= 31 { // prevent response splitting. b = ' ' } p = append(p, b) } p = append(p, "\r\n"...) } } p = append(p, "\r\n"...) // Clear deadlines set by HTTP server. if err := netConn.SetDeadline(time.Time{}); err != nil { if err := netConn.Close(); err != nil { log.Printf("websocket: failed to close network connection: %v", err) } return nil, err } if u.HandshakeTimeout > 0 { if err := netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout)); err != nil { if err := netConn.Close(); err != nil { log.Printf("websocket: failed to close network connection: %v", err) } return nil, err } } if _, err = netConn.Write(p); err != nil { if err := netConn.Close(); err != nil { log.Printf("websocket: failed to close network connection: %v", err) } return nil, err } if u.HandshakeTimeout > 0 { if err := netConn.SetWriteDeadline(time.Time{}); err != nil { if err := netConn.Close(); err != nil { log.Printf("websocket: failed to close network connection: %v", err) } return nil, err } } return c, nil } // Upgrade upgrades the HTTP server connection to the WebSocket protocol. // // Deprecated: Use websocket.Upgrader instead. // // Upgrade does not perform origin checking. The application is responsible for // checking the Origin header before calling Upgrade. An example implementation // of the same origin policy check is: // // if req.Header.Get("Origin") != "http://"+req.Host { // http.Error(w, "Origin not allowed", http.StatusForbidden) // return // } // // If the endpoint supports subprotocols, then the application is responsible // for negotiating the protocol used on the connection. Use the Subprotocols() // function to get the subprotocols requested by the client. Use the // Sec-Websocket-Protocol response header to specify the subprotocol selected // by the application. // // The responseHeader is included in the response to the client's upgrade // request. Use the responseHeader to specify cookies (Set-Cookie) and the // negotiated subprotocol (Sec-Websocket-Protocol). // // The connection buffers IO to the underlying network connection. The // readBufSize and writeBufSize parameters specify the size of the buffers to // use. Messages can be larger than the buffers. // // If the request is not a valid WebSocket handshake, then Upgrade returns an // error of type HandshakeError. Applications should handle this error by // replying to the client with an HTTP error response. func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) { u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize} u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) { // don't return errors to maintain backwards compatibility } u.CheckOrigin = func(r *http.Request) bool { // allow all connections by default return true } return u.Upgrade(w, r, responseHeader) } // Subprotocols returns the subprotocols requested by the client in the // Sec-Websocket-Protocol header. func Subprotocols(r *http.Request) []string { h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol")) if h == "" { return nil } protocols := strings.Split(h, ",") for i := range protocols { protocols[i] = strings.TrimSpace(protocols[i]) } return protocols } // IsWebSocketUpgrade returns true if the client requested upgrade to the // WebSocket protocol. func IsWebSocketUpgrade(r *http.Request) bool { return tokenListContainsValue(r.Header, "Connection", "upgrade") && tokenListContainsValue(r.Header, "Upgrade", "websocket") } // bufioReaderSize size returns the size of a bufio.Reader. func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int { // This code assumes that peek on a reset reader returns // bufio.Reader.buf[:0]. // TODO: Use bufio.Reader.Size() after Go 1.10 br.Reset(originalReader) if p, err := br.Peek(0); err == nil { return cap(p) } return 0 } // writeHook is an io.Writer that records the last slice passed to it vio // io.Writer.Write. type writeHook struct { p []byte } func (wh *writeHook) Write(p []byte) (int, error) { wh.p = p return len(p), nil } // bufioWriterBuffer grabs the buffer from a bufio.Writer. func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte { // This code assumes that bufio.Writer.buf[:1] is passed to the // bufio.Writer's underlying writer. var wh writeHook bw.Reset(&wh) if err := bw.WriteByte(0); err != nil { panic(err) } if err := bw.Flush(); err != nil { log.Printf("websocket: bufioWriterBuffer: Flush: %v", err) } bw.Reset(originalWriter) return wh.p[:cap(wh.p)] }
// 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 ( "bufio" "bytes" "net" "net/http" "reflect" "strings" "testing" ) var subprotocolTests = []struct { h string protocols []string }{ {"", nil}, {"foo", []string{"foo"}}, {"foo,bar", []string{"foo", "bar"}}, {"foo, bar", []string{"foo", "bar"}}, {" foo, bar", []string{"foo", "bar"}}, {" foo, bar ", []string{"foo", "bar"}}, } func TestSubprotocols(t *testing.T) { for _, st := range subprotocolTests { r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}} protocols := Subprotocols(&r) if !reflect.DeepEqual(st.protocols, protocols) { t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols) } } } var isWebSocketUpgradeTests = []struct { ok bool h http.Header }{ {false, http.Header{"Upgrade": {"websocket"}}}, {false, http.Header{"Connection": {"upgrade"}}}, {true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}}, } func TestIsWebSocketUpgrade(t *testing.T) { for _, tt := range isWebSocketUpgradeTests { ok := IsWebSocketUpgrade(&http.Request{Header: tt.h}) if tt.ok != ok { t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok) } } } func TestSubProtocolSelection(t *testing.T) { upgrader := Upgrader{ Subprotocols: []string{"foo", "bar", "baz"}, } r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"foo", "bar"}}} s := upgrader.selectSubprotocol(&r, nil) if s != "foo" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "foo") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"bar", "foo"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "bar" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "bar") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"baz"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "baz" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "baz") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"quux"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "empty string") } } var checkSameOriginTests = []struct { ok bool r *http.Request }{ {false, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://other.org"}}}}, {true, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, {true, &http.Request{Host: "Example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, } func TestCheckSameOrigin(t *testing.T) { for _, tt := range checkSameOriginTests { ok := checkSameOrigin(tt.r) if tt.ok != ok { t.Errorf("checkSameOrigin(%+v) returned %v, want %v", tt.r, ok, tt.ok) } } } type reuseTestResponseWriter struct { brw *bufio.ReadWriter http.ResponseWriter } func (resp *reuseTestResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return fakeNetConn{strings.NewReader(""), &bytes.Buffer{}}, resp.brw, nil } var bufioReuseTests = []struct { n int reuse bool }{ {4096, true}, {128, false}, } func TestBufioReuse(t *testing.T) { for i, tt := range bufioReuseTests { br := bufio.NewReaderSize(strings.NewReader(""), tt.n) bw := bufio.NewWriterSize(&bytes.Buffer{}, tt.n) resp := &reuseTestResponseWriter{ brw: bufio.NewReadWriter(br, bw), } upgrader := Upgrader{} c, err := upgrader.Upgrade(resp, &http.Request{ Method: http.MethodGet, Header: http.Header{ "Upgrade": []string{"websocket"}, "Connection": []string{"upgrade"}, "Sec-Websocket-Key": []string{"dGhlIHNhbXBsZSBub25jZQ=="}, "Sec-Websocket-Version": []string{"13"}, }}, nil) if err != nil { t.Fatal(err) } if reuse := c.br == br; reuse != tt.reuse { t.Errorf("%d: buffered reader reuse=%v, want %v", i, reuse, tt.reuse) } writeBuf := bufioWriterBuffer(c.NetConn(), bw) if reuse := &c.writeBuf[0] == &writeBuf[0]; reuse != tt.reuse { t.Errorf("%d: write buffer reuse=%v, want %v", i, reuse, tt.reuse) } } }
30
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. // Command server is a test server for the Autobahn WebSockets Test Suite. package main import ( "errors" "flag" "io" "log" "net/http" "time" "unicode/utf8" "github.com/gorilla/websocket" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 4096, WriteBufferSize: 4096, EnableCompression: true, CheckOrigin: func(r *http.Request) bool { return true }, } // echoCopy echoes messages from the client using io.Copy. func echoCopy(w http.ResponseWriter, r *http.Request, writerOnly bool) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } defer conn.Close() for { mt, r, err := conn.NextReader() if err != nil { if err != io.EOF { log.Println("NextReader:", err) } return } if mt == websocket.TextMessage { r = &validator{r: r} } w, err := conn.NextWriter(mt) if err != nil { log.Println("NextWriter:", err) return } if mt == websocket.TextMessage { r = &validator{r: r} } if writerOnly { _, err = io.Copy(struct{ io.Writer }{w}, r) } else { _, err = io.Copy(w, r) } if err != nil { if err == errInvalidUTF8 { conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""), time.Time{}) } log.Println("Copy:", err) return } err = w.Close() if err != nil { log.Println("Close:", err) return } } } func echoCopyWriterOnly(w http.ResponseWriter, r *http.Request) { echoCopy(w, r, true) } func echoCopyFull(w http.ResponseWriter, r *http.Request) { echoCopy(w, r, false) } // echoReadAll echoes messages from the client by reading the entire message // with ioutil.ReadAll. func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage, writePrepared bool) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Println("Upgrade:", err) return } defer conn.Close() for { mt, b, err := conn.ReadMessage() if err != nil { if err != io.EOF { log.Println("NextReader:", err) } return } if mt == websocket.TextMessage { if !utf8.Valid(b) { conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""), time.Time{}) log.Println("ReadAll: invalid utf8") } } if writeMessage { if !writePrepared { err = conn.WriteMessage(mt, b) if err != nil { log.Println("WriteMessage:", err) } } else { pm, err := websocket.NewPreparedMessage(mt, b) if err != nil { log.Println("NewPreparedMessage:", err) return } err = conn.WritePreparedMessage(pm) if err != nil { log.Println("WritePreparedMessage:", err) } } } else { w, err := conn.NextWriter(mt) if err != nil { log.Println("NextWriter:", err) return } if _, err := w.Write(b); err != nil { log.Println("Writer:", err) return } if err := w.Close(); err != nil { log.Println("Close:", err) return } } } } func echoReadAllWriter(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, false, false) } func echoReadAllWriteMessage(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, true, false) } func echoReadAllWritePreparedMessage(w http.ResponseWriter, r *http.Request) { echoReadAll(w, r, true, true) } func serveHome(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.Error(w, "Not found.", http.StatusNotFound) return } if r.Method != http.MethodGet { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") io.WriteString(w, "<html><body>Echo Server</body></html>") } var addr = flag.String("addr", ":9000", "http service address") func main() { flag.Parse() http.HandleFunc("/", serveHome) http.HandleFunc("/c", echoCopyWriterOnly) http.HandleFunc("/f", echoCopyFull) http.HandleFunc("/r", echoReadAllWriter) http.HandleFunc("/m", echoReadAllWriteMessage) http.HandleFunc("/p", echoReadAllWritePreparedMessage) server := &http.Server{ Addr: *addr, ReadHeaderTimeout: 3 * time.Second, } err := server.ListenAndServe() if err != nil { log.Fatal("ListenAndServe: ", err) } } type validator struct { state int x rune r io.Reader } var errInvalidUTF8 = errors.New("invalid utf8") func (r *validator) Read(p []byte) (int, error) { n, err := r.r.Read(p) state := r.state x := r.x for _, b := range p[:n] { state, x = decode(state, x, b) if state == utf8Reject { break } } r.state = state r.x = x if state == utf8Reject || (err == io.EOF && state != utf8Accept) { return n, errInvalidUTF8 } return n, err } // UTF-8 decoder from http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ // // Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. var utf8d = [...]byte{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5f 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7f 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9f 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // a0..bf 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // c0..df 0xa, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // e0..ef 0xb, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // f0..ff 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // s7..s8 } const ( utf8Accept = 0 utf8Reject = 1 ) func decode(state int, x rune, b byte) (int, rune) { t := utf8d[b] if state != utf8Accept { x = rune(b&0x3f) | (x << 6) } else { x = rune((0xff >> t) & b) } state = int(utf8d[256+state*16+int(t)]) return state, x }
// 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 ( "bufio" "bytes" "net" "net/http" "reflect" "strings" "testing" ) var subprotocolTests = []struct { h string protocols []string }{ {"", nil}, {"foo", []string{"foo"}}, {"foo,bar", []string{"foo", "bar"}}, {"foo, bar", []string{"foo", "bar"}}, {" foo, bar", []string{"foo", "bar"}}, {" foo, bar ", []string{"foo", "bar"}}, } func TestSubprotocols(t *testing.T) { for _, st := range subprotocolTests { r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}} protocols := Subprotocols(&r) if !reflect.DeepEqual(st.protocols, protocols) { t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols) } } } var isWebSocketUpgradeTests = []struct { ok bool h http.Header }{ {false, http.Header{"Upgrade": {"websocket"}}}, {false, http.Header{"Connection": {"upgrade"}}}, {true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}}, } func TestIsWebSocketUpgrade(t *testing.T) { for _, tt := range isWebSocketUpgradeTests { ok := IsWebSocketUpgrade(&http.Request{Header: tt.h}) if tt.ok != ok { t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok) } } } func TestSubProtocolSelection(t *testing.T) { upgrader := Upgrader{ Subprotocols: []string{"foo", "bar", "baz"}, } r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"foo", "bar"}}} s := upgrader.selectSubprotocol(&r, nil) if s != "foo" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "foo") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"bar", "foo"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "bar" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "bar") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"baz"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "baz" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "baz") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"quux"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "empty string") } } var checkSameOriginTests = []struct { ok bool r *http.Request }{ {false, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://other.org"}}}}, {true, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, {true, &http.Request{Host: "Example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, } func TestCheckSameOrigin(t *testing.T) { for _, tt := range checkSameOriginTests { ok := checkSameOrigin(tt.r) if tt.ok != ok { t.Errorf("checkSameOrigin(%+v) returned %v, want %v", tt.r, ok, tt.ok) } } } type reuseTestResponseWriter struct { brw *bufio.ReadWriter http.ResponseWriter } func (resp *reuseTestResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return fakeNetConn{strings.NewReader(""), &bytes.Buffer{}}, resp.brw, nil } var bufioReuseTests = []struct { n int reuse bool }{ {4096, true}, {128, false}, } func TestBufioReuse(t *testing.T) { for i, tt := range bufioReuseTests { br := bufio.NewReaderSize(strings.NewReader(""), tt.n) bw := bufio.NewWriterSize(&bytes.Buffer{}, tt.n) resp := &reuseTestResponseWriter{ brw: bufio.NewReadWriter(br, bw), } upgrader := Upgrader{} c, err := upgrader.Upgrade(resp, &http.Request{ Method: http.MethodGet, Header: http.Header{ "Upgrade": []string{"websocket"}, "Connection": []string{"upgrade"}, "Sec-Websocket-Key": []string{"dGhlIHNhbXBsZSBub25jZQ=="}, "Sec-Websocket-Version": []string{"13"}, }}, nil) if err != nil { t.Fatal(err) } if reuse := c.br == br; reuse != tt.reuse { t.Errorf("%d: buffered reader reuse=%v, want %v", i, reuse, tt.reuse) } writeBuf := bufioWriterBuffer(c.NetConn(), bw) if reuse := &c.writeBuf[0] == &writeBuf[0]; reuse != tt.reuse { t.Errorf("%d: write buffer reuse=%v, want %v", i, reuse, tt.reuse) } } }
31
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/http" "sync" _ "net/http/pprof" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:8080", "http service address") var upgrader = websocket.Upgrader{ ReadBufferSize: 256, WriteBufferSize: 256, WriteBufferPool: &sync.Pool{}, } func process(c *websocket.Conn) { defer c.Close() for { _, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", message) } } func handler(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } // Process connection in a new goroutine go process(c) // Let the http handler return, the 8k buffer created by it will be garbage collected } func main() { flag.Parse() log.SetFlags(0) http.HandleFunc("/ws", handler) log.Fatal(http.ListenAndServe(*addr, nil)) }
// 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 ( "bufio" "bytes" "net" "net/http" "reflect" "strings" "testing" ) var subprotocolTests = []struct { h string protocols []string }{ {"", nil}, {"foo", []string{"foo"}}, {"foo,bar", []string{"foo", "bar"}}, {"foo, bar", []string{"foo", "bar"}}, {" foo, bar", []string{"foo", "bar"}}, {" foo, bar ", []string{"foo", "bar"}}, } func TestSubprotocols(t *testing.T) { for _, st := range subprotocolTests { r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}} protocols := Subprotocols(&r) if !reflect.DeepEqual(st.protocols, protocols) { t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols) } } } var isWebSocketUpgradeTests = []struct { ok bool h http.Header }{ {false, http.Header{"Upgrade": {"websocket"}}}, {false, http.Header{"Connection": {"upgrade"}}}, {true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}}, } func TestIsWebSocketUpgrade(t *testing.T) { for _, tt := range isWebSocketUpgradeTests { ok := IsWebSocketUpgrade(&http.Request{Header: tt.h}) if tt.ok != ok { t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok) } } } func TestSubProtocolSelection(t *testing.T) { upgrader := Upgrader{ Subprotocols: []string{"foo", "bar", "baz"}, } r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"foo", "bar"}}} s := upgrader.selectSubprotocol(&r, nil) if s != "foo" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "foo") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"bar", "foo"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "bar" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "bar") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"baz"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "baz" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "baz") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"quux"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "empty string") } } var checkSameOriginTests = []struct { ok bool r *http.Request }{ {false, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://other.org"}}}}, {true, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, {true, &http.Request{Host: "Example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, } func TestCheckSameOrigin(t *testing.T) { for _, tt := range checkSameOriginTests { ok := checkSameOrigin(tt.r) if tt.ok != ok { t.Errorf("checkSameOrigin(%+v) returned %v, want %v", tt.r, ok, tt.ok) } } } type reuseTestResponseWriter struct { brw *bufio.ReadWriter http.ResponseWriter } func (resp *reuseTestResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return fakeNetConn{strings.NewReader(""), &bytes.Buffer{}}, resp.brw, nil } var bufioReuseTests = []struct { n int reuse bool }{ {4096, true}, {128, false}, } func TestBufioReuse(t *testing.T) { for i, tt := range bufioReuseTests { br := bufio.NewReaderSize(strings.NewReader(""), tt.n) bw := bufio.NewWriterSize(&bytes.Buffer{}, tt.n) resp := &reuseTestResponseWriter{ brw: bufio.NewReadWriter(br, bw), } upgrader := Upgrader{} c, err := upgrader.Upgrade(resp, &http.Request{ Method: http.MethodGet, Header: http.Header{ "Upgrade": []string{"websocket"}, "Connection": []string{"upgrade"}, "Sec-Websocket-Key": []string{"dGhlIHNhbXBsZSBub25jZQ=="}, "Sec-Websocket-Version": []string{"13"}, }}, nil) if err != nil { t.Fatal(err) } if reuse := c.br == br; reuse != tt.reuse { t.Errorf("%d: buffered reader reuse=%v, want %v", i, reuse, tt.reuse) } writeBuf := bufioWriterBuffer(c.NetConn(), bw) if reuse := &c.writeBuf[0] == &writeBuf[0]; reuse != tt.reuse { t.Errorf("%d: write buffer reuse=%v, want %v", i, reuse, tt.reuse) } } }
32
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 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 ignore // +build ignore package main import ( "flag" "html/template" "log" "net/http" "github.com/gorilla/websocket" ) var addr = flag.String("addr", "localhost:8080", "http service address") var upgrader = websocket.Upgrader{} // use default options func echo(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { log.Print("upgrade:", err) return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { log.Println("read:", err) break } log.Printf("recv: %s", message) err = c.WriteMessage(mt, message) if err != nil { log.Println("write:", err) break } } } func home(w http.ResponseWriter, r *http.Request) { homeTemplate.Execute(w, "ws://"+r.Host+"/echo") } func main() { flag.Parse() log.SetFlags(0) http.HandleFunc("/echo", echo) http.HandleFunc("/", home) log.Fatal(http.ListenAndServe(*addr, nil)) } var homeTemplate = template.Must(template.New("").Parse(` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script> window.addEventListener("load", function(evt) { var output = document.getElementById("output"); var input = document.getElementById("input"); var ws; var print = function(message) { var d = document.createElement("div"); d.textContent = message; output.appendChild(d); output.scroll(0, output.scrollHeight); }; document.getElementById("open").onclick = function(evt) { if (ws) { return false; } ws = new WebSocket("{{.}}"); ws.onopen = function(evt) { print("OPEN"); } ws.onclose = function(evt) { print("CLOSE"); ws = null; } ws.onmessage = function(evt) { print("RESPONSE: " + evt.data); } ws.onerror = function(evt) { print("ERROR: " + evt.data); } return false; }; document.getElementById("send").onclick = function(evt) { if (!ws) { return false; } print("SEND: " + input.value); ws.send(input.value); return false; }; document.getElementById("close").onclick = function(evt) { if (!ws) { return false; } ws.close(); return false; }; }); </script> </head> <body> <table> <tr><td valign="top" width="50%"> <p>Click "Open" to create a connection to the server, "Send" to send a message to the server and "Close" to close the connection. You can change the message and send multiple times. <p> <form> <button id="open">Open</button> <button id="close">Close</button> <p><input id="input" type="text" value="Hello world!"> <button id="send">Send</button> </form> </td><td valign="top" width="50%"> <div id="output" style="max-height: 70vh;overflow-y: scroll;"></div> </td></tr></table> </body> </html> `))
// 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 ( "bufio" "bytes" "net" "net/http" "reflect" "strings" "testing" ) var subprotocolTests = []struct { h string protocols []string }{ {"", nil}, {"foo", []string{"foo"}}, {"foo,bar", []string{"foo", "bar"}}, {"foo, bar", []string{"foo", "bar"}}, {" foo, bar", []string{"foo", "bar"}}, {" foo, bar ", []string{"foo", "bar"}}, } func TestSubprotocols(t *testing.T) { for _, st := range subprotocolTests { r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {st.h}}} protocols := Subprotocols(&r) if !reflect.DeepEqual(st.protocols, protocols) { t.Errorf("SubProtocols(%q) returned %#v, want %#v", st.h, protocols, st.protocols) } } } var isWebSocketUpgradeTests = []struct { ok bool h http.Header }{ {false, http.Header{"Upgrade": {"websocket"}}}, {false, http.Header{"Connection": {"upgrade"}}}, {true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}}, } func TestIsWebSocketUpgrade(t *testing.T) { for _, tt := range isWebSocketUpgradeTests { ok := IsWebSocketUpgrade(&http.Request{Header: tt.h}) if tt.ok != ok { t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok) } } } func TestSubProtocolSelection(t *testing.T) { upgrader := Upgrader{ Subprotocols: []string{"foo", "bar", "baz"}, } r := http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"foo", "bar"}}} s := upgrader.selectSubprotocol(&r, nil) if s != "foo" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "foo") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"bar", "foo"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "bar" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "bar") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"baz"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "baz" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "baz") } r = http.Request{Header: http.Header{"Sec-Websocket-Protocol": {"quux"}}} s = upgrader.selectSubprotocol(&r, nil) if s != "" { t.Errorf("Upgrader.selectSubprotocol returned %v, want %v", s, "empty string") } } var checkSameOriginTests = []struct { ok bool r *http.Request }{ {false, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://other.org"}}}}, {true, &http.Request{Host: "example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, {true, &http.Request{Host: "Example.org", Header: map[string][]string{"Origin": {"https://example.org"}}}}, } func TestCheckSameOrigin(t *testing.T) { for _, tt := range checkSameOriginTests { ok := checkSameOrigin(tt.r) if tt.ok != ok { t.Errorf("checkSameOrigin(%+v) returned %v, want %v", tt.r, ok, tt.ok) } } } type reuseTestResponseWriter struct { brw *bufio.ReadWriter http.ResponseWriter } func (resp *reuseTestResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { return fakeNetConn{strings.NewReader(""), &bytes.Buffer{}}, resp.brw, nil } var bufioReuseTests = []struct { n int reuse bool }{ {4096, true}, {128, false}, } func TestBufioReuse(t *testing.T) { for i, tt := range bufioReuseTests { br := bufio.NewReaderSize(strings.NewReader(""), tt.n) bw := bufio.NewWriterSize(&bytes.Buffer{}, tt.n) resp := &reuseTestResponseWriter{ brw: bufio.NewReadWriter(br, bw), } upgrader := Upgrader{} c, err := upgrader.Upgrade(resp, &http.Request{ Method: http.MethodGet, Header: http.Header{ "Upgrade": []string{"websocket"}, "Connection": []string{"upgrade"}, "Sec-Websocket-Key": []string{"dGhlIHNhbXBsZSBub25jZQ=="}, "Sec-Websocket-Version": []string{"13"}, }}, nil) if err != nil { t.Fatal(err) } if reuse := c.br == br; reuse != tt.reuse { t.Errorf("%d: buffered reader reuse=%v, want %v", i, reuse, tt.reuse) } writeBuf := bufioWriterBuffer(c.NetConn(), bw) if reuse := &c.writeBuf[0] == &writeBuf[0]; reuse != tt.reuse { t.Errorf("%d: write buffer reuse=%v, want %v", i, reuse, tt.reuse) } } }
33
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 ( "encoding/json" "io" ) // WriteJSON writes the JSON encoding of v as a message. // // Deprecated: Use c.WriteJSON instead. func WriteJSON(c *Conn, v interface{}) error { return c.WriteJSON(v) } // WriteJSON writes the JSON encoding of v as a message. // // See the documentation for encoding/json Marshal for details about the // conversion of Go values to JSON. func (c *Conn) WriteJSON(v interface{}) error { w, err := c.NextWriter(TextMessage) if err != nil { return err } err1 := json.NewEncoder(w).Encode(v) err2 := w.Close() if err1 != nil { return err1 } return err2 } // ReadJSON reads the next JSON-encoded message from the connection and stores // it in the value pointed to by v. // // Deprecated: Use c.ReadJSON instead. func ReadJSON(c *Conn, v interface{}) error { return c.ReadJSON(v) } // ReadJSON reads the next JSON-encoded message from the connection and stores // it in the value pointed to by v. // // See the documentation for the encoding/json Unmarshal function for details // about the conversion of JSON to a Go value. func (c *Conn) ReadJSON(v interface{}) error { _, r, err := c.NextReader() if err != nil { return err } err = json.NewDecoder(r).Decode(v) if err == io.EOF { // One value is expected in the message. err = io.ErrUnexpectedEOF } return err }
// 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" "encoding/json" "io" "reflect" "testing" ) func TestJSON(t *testing.T) { var buf bytes.Buffer wc := newTestConn(nil, &buf, true) rc := newTestConn(&buf, nil, false) var actual, expect struct { A int B string } expect.A = 1 expect.B = "hello" if err := wc.WriteJSON(&expect); err != nil { t.Fatal("write", err) } if err := rc.ReadJSON(&actual); err != nil { t.Fatal("read", err) } if !reflect.DeepEqual(&actual, &expect) { t.Fatal("equal", actual, expect) } } func TestPartialJSONRead(t *testing.T) { var buf0, buf1 bytes.Buffer wc := newTestConn(nil, &buf0, true) rc := newTestConn(&buf0, &buf1, false) var v struct { A int B string } v.A = 1 v.B = "hello" messageCount := 0 // Partial JSON values. data, err := json.Marshal(v) if err != nil { t.Fatal(err) } for i := len(data) - 1; i >= 0; i-- { if err := wc.WriteMessage(TextMessage, data[:i]); err != nil { t.Fatal(err) } messageCount++ } // Whitespace. if err := wc.WriteMessage(TextMessage, []byte(" ")); err != nil { t.Fatal(err) } messageCount++ // Close. if err := wc.WriteMessage(CloseMessage, FormatCloseMessage(CloseNormalClosure, "")); err != nil { t.Fatal(err) } for i := 0; i < messageCount; i++ { err := rc.ReadJSON(&v) if err != io.ErrUnexpectedEOF { t.Error("read", i, err) } } err = rc.ReadJSON(&v) if _, ok := err.(*CloseError); !ok { t.Error("final", err) } } func TestDeprecatedJSON(t *testing.T) { var buf bytes.Buffer wc := newTestConn(nil, &buf, true) rc := newTestConn(&buf, nil, false) var actual, expect struct { A int B string } expect.A = 1 expect.B = "hello" if err := WriteJSON(wc, &expect); err != nil { t.Fatal("write", err) } if err := ReadJSON(rc, &actual); err != nil { t.Fatal("read", err) } if !reflect.DeepEqual(&actual, &expect) { t.Fatal("equal", actual, expect) } }
34
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 ( "bufio" "crypto/rand" "encoding/binary" "errors" "io" "net" "strconv" "strings" "sync" "time" "unicode/utf8" ) const ( // Frame header byte 0 bits from Section 5.2 of RFC 6455 finalBit = 1 << 7 rsv1Bit = 1 << 6 rsv2Bit = 1 << 5 rsv3Bit = 1 << 4 // Frame header byte 1 bits from Section 5.2 of RFC 6455 maskBit = 1 << 7 maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask maxControlFramePayloadSize = 125 writeWait = time.Second defaultReadBufferSize = 4096 defaultWriteBufferSize = 4096 continuationFrame = 0 noFrame = -1 ) // Close codes defined in RFC 6455, section 11.7. const ( CloseNormalClosure = 1000 CloseGoingAway = 1001 CloseProtocolError = 1002 CloseUnsupportedData = 1003 CloseNoStatusReceived = 1005 CloseAbnormalClosure = 1006 CloseInvalidFramePayloadData = 1007 ClosePolicyViolation = 1008 CloseMessageTooBig = 1009 CloseMandatoryExtension = 1010 CloseInternalServerErr = 1011 CloseServiceRestart = 1012 CloseTryAgainLater = 1013 CloseTLSHandshake = 1015 ) // The message types are defined in RFC 6455, section 11.8. const ( // TextMessage denotes a text data message. The text message payload is // interpreted as UTF-8 encoded text data. TextMessage = 1 // BinaryMessage denotes a binary data message. BinaryMessage = 2 // CloseMessage denotes a close control message. The optional message // payload contains a numeric code and text. Use the FormatCloseMessage // function to format a close message payload. CloseMessage = 8 // PingMessage denotes a ping control message. The optional message payload // is UTF-8 encoded text. PingMessage = 9 // PongMessage denotes a pong control message. The optional message payload // is UTF-8 encoded text. PongMessage = 10 ) // ErrCloseSent is returned when the application writes a message to the // connection after sending a close message. var ErrCloseSent = errors.New("websocket: close sent") // ErrReadLimit is returned when reading a message that is larger than the // read limit set for the connection. var ErrReadLimit = errors.New("websocket: read limit exceeded") // netError satisfies the net Error interface. type netError struct { msg string temporary bool timeout bool } func (e *netError) Error() string { return e.msg } func (e *netError) Temporary() bool { return e.temporary } func (e *netError) Timeout() bool { return e.timeout } // CloseError represents a close message. type CloseError struct { // Code is defined in RFC 6455, section 11.7. Code int // Text is the optional text payload. Text string } func (e *CloseError) Error() string { s := []byte("websocket: close ") s = strconv.AppendInt(s, int64(e.Code), 10) switch e.Code { case CloseNormalClosure: s = append(s, " (normal)"...) case CloseGoingAway: s = append(s, " (going away)"...) case CloseProtocolError: s = append(s, " (protocol error)"...) case CloseUnsupportedData: s = append(s, " (unsupported data)"...) case CloseNoStatusReceived: s = append(s, " (no status)"...) case CloseAbnormalClosure: s = append(s, " (abnormal closure)"...) case CloseInvalidFramePayloadData: s = append(s, " (invalid payload data)"...) case ClosePolicyViolation: s = append(s, " (policy violation)"...) case CloseMessageTooBig: s = append(s, " (message too big)"...) case CloseMandatoryExtension: s = append(s, " (mandatory extension missing)"...) case CloseInternalServerErr: s = append(s, " (internal server error)"...) case CloseTLSHandshake: s = append(s, " (TLS handshake error)"...) } if e.Text != "" { s = append(s, ": "...) s = append(s, e.Text...) } return string(s) } // IsCloseError returns boolean indicating whether the error is a *CloseError // with one of the specified codes. func IsCloseError(err error, codes ...int) bool { if e, ok := err.(*CloseError); ok { for _, code := range codes { if e.Code == code { return true } } } return false } // IsUnexpectedCloseError returns boolean indicating whether the error is a // *CloseError with a code not in the list of expected codes. func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { if e, ok := err.(*CloseError); ok { for _, code := range expectedCodes { if e.Code == code { return false } } return true } return false } var ( errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true} errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()} errBadWriteOpCode = errors.New("websocket: bad write message type") errWriteClosed = errors.New("websocket: write closed") errInvalidControlFrame = errors.New("websocket: invalid control frame") ) // maskRand is an io.Reader for generating mask bytes. The reader is initialized // to crypto/rand Reader. Tests swap the reader to a math/rand reader for // reproducible results. var maskRand = rand.Reader // newMaskKey returns a new 32 bit value for masking client frames. func newMaskKey() [4]byte { var k [4]byte _, _ = io.ReadFull(maskRand, k[:]) return k } func hideTempErr(err error) error { if e, ok := err.(net.Error); ok { err = &netError{msg: e.Error(), timeout: e.Timeout()} } return err } func isControl(frameType int) bool { return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage } func isData(frameType int) bool { return frameType == TextMessage || frameType == BinaryMessage } var validReceivedCloseCodes = map[int]bool{ // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number CloseNormalClosure: true, CloseGoingAway: true, CloseProtocolError: true, CloseUnsupportedData: true, CloseNoStatusReceived: false, CloseAbnormalClosure: false, CloseInvalidFramePayloadData: true, ClosePolicyViolation: true, CloseMessageTooBig: true, CloseMandatoryExtension: true, CloseInternalServerErr: true, CloseServiceRestart: true, CloseTryAgainLater: true, CloseTLSHandshake: false, } func isValidReceivedCloseCode(code int) bool { return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999) } // BufferPool represents a pool of buffers. The *sync.Pool type satisfies this // interface. The type of the value stored in a pool is not specified. type BufferPool interface { // Get gets a value from the pool or returns nil if the pool is empty. Get() interface{} // Put adds a value to the pool. Put(interface{}) } // writePoolData is the type added to the write buffer pool. This wrapper is // used to prevent applications from peeking at and depending on the values // added to the pool. type writePoolData struct{ buf []byte } // The Conn type represents a WebSocket connection. type Conn struct { conn net.Conn isServer bool subprotocol string // Write fields mu chan struct{} // used as mutex to protect write to conn writeBuf []byte // frame is constructed in this buffer. writePool BufferPool writeBufSize int writeDeadline time.Time writer io.WriteCloser // the current writer returned to the application isWriting bool // for best-effort concurrent write detection writeErrMu sync.Mutex writeErr error enableWriteCompression bool compressionLevel int newCompressionWriter func(io.WriteCloser, int) io.WriteCloser // Read fields reader io.ReadCloser // the current reader returned to the application readErr error br *bufio.Reader // bytes remaining in current frame. // set setReadRemaining to safely update this value and prevent overflow readRemaining int64 readFinal bool // true the current message has more frames. readLength int64 // Message size. readLimit int64 // Maximum message size. readMaskPos int readMaskKey [4]byte handlePong func(string) error handlePing func(string) error handleClose func(int, string) error readErrCount int messageReader *messageReader // the current low-level reader readDecompress bool // whether last read frame had RSV1 set newDecompressionReader func(io.Reader) io.ReadCloser } func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, writeBufferPool BufferPool, br *bufio.Reader, writeBuf []byte) *Conn { if br == nil { if readBufferSize == 0 { readBufferSize = defaultReadBufferSize } else if readBufferSize < maxControlFramePayloadSize { // must be large enough for control frame readBufferSize = maxControlFramePayloadSize } br = bufio.NewReaderSize(conn, readBufferSize) } if writeBufferSize <= 0 { writeBufferSize = defaultWriteBufferSize } writeBufferSize += maxFrameHeaderSize if writeBuf == nil && writeBufferPool == nil { writeBuf = make([]byte, writeBufferSize) } mu := make(chan struct{}, 1) mu <- struct{}{} c := &Conn{ isServer: isServer, br: br, conn: conn, mu: mu, readFinal: true, writeBuf: writeBuf, writePool: writeBufferPool, writeBufSize: writeBufferSize, enableWriteCompression: true, compressionLevel: defaultCompressionLevel, } c.SetCloseHandler(nil) c.SetPingHandler(nil) c.SetPongHandler(nil) return c } // setReadRemaining tracks the number of bytes remaining on the connection. If n // overflows, an ErrReadLimit is returned. func (c *Conn) setReadRemaining(n int64) error { if n < 0 { return ErrReadLimit } c.readRemaining = n return nil } // Subprotocol returns the negotiated protocol for the connection. func (c *Conn) Subprotocol() string { return c.subprotocol } // Close closes the underlying network connection without sending or waiting // for a close message. func (c *Conn) Close() error { return c.conn.Close() } // LocalAddr returns the local network address. func (c *Conn) LocalAddr() net.Addr { return c.conn.LocalAddr() } // RemoteAddr returns the remote network address. func (c *Conn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() } // Write methods func (c *Conn) writeFatal(err error) error { err = hideTempErr(err) c.writeErrMu.Lock() if c.writeErr == nil { c.writeErr = err } c.writeErrMu.Unlock() return err } func (c *Conn) read(n int) ([]byte, error) { p, err := c.br.Peek(n) if err == io.EOF { err = errUnexpectedEOF } if _, err := c.br.Discard(len(p)); err != nil { return p, err } return p, err } func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error { <-c.mu defer func() { c.mu <- struct{}{} }() c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() if err != nil { return err } if err := c.conn.SetWriteDeadline(deadline); err != nil { return c.writeFatal(err) } if len(buf1) == 0 { _, err = c.conn.Write(buf0) } else { err = c.writeBufs(buf0, buf1) } if err != nil { return c.writeFatal(err) } if frameType == CloseMessage { _ = c.writeFatal(ErrCloseSent) } return nil } func (c *Conn) writeBufs(bufs ...[]byte) error { b := net.Buffers(bufs) _, err := b.WriteTo(c.conn) return err } // WriteControl writes a control message with the given deadline. The allowed // message types are CloseMessage, PingMessage and PongMessage. func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error { if !isControl(messageType) { return errBadWriteOpCode } if len(data) > maxControlFramePayloadSize { return errInvalidControlFrame } b0 := byte(messageType) | finalBit b1 := byte(len(data)) if !c.isServer { b1 |= maskBit } buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize) buf = append(buf, b0, b1) if c.isServer { buf = append(buf, data...) } else { key := newMaskKey() buf = append(buf, key[:]...) buf = append(buf, data...) maskBytes(key, 0, buf[6:]) } d := 1000 * time.Hour if !deadline.IsZero() { d = time.Until(deadline) if d < 0 { return errWriteTimeout } } timer := time.NewTimer(d) select { case <-c.mu: timer.Stop() case <-timer.C: return errWriteTimeout } defer func() { c.mu <- struct{}{} }() c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() if err != nil { return err } if err := c.conn.SetWriteDeadline(deadline); err != nil { return c.writeFatal(err) } _, err = c.conn.Write(buf) if err != nil { return c.writeFatal(err) } if messageType == CloseMessage { _ = c.writeFatal(ErrCloseSent) } return err } // beginMessage prepares a connection and message writer for a new message. func (c *Conn) beginMessage(mw *messageWriter, messageType int) error { // Close previous writer if not already closed by the application. It's // probably better to return an error in this situation, but we cannot // change this without breaking existing applications. if c.writer != nil { _ = c.writer.Close() c.writer = nil } if !isControl(messageType) && !isData(messageType) { return errBadWriteOpCode } c.writeErrMu.Lock() err := c.writeErr c.writeErrMu.Unlock() if err != nil { return err } mw.c = c mw.frameType = messageType mw.pos = maxFrameHeaderSize if c.writeBuf == nil { wpd, ok := c.writePool.Get().(writePoolData) if ok { c.writeBuf = wpd.buf } else { c.writeBuf = make([]byte, c.writeBufSize) } } return nil } // NextWriter returns a writer for the next message to send. The writer's Close // method flushes the complete message to the network. // // There can be at most one open writer on a connection. NextWriter closes the // previous writer if the application has not already done so. // // All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and // PongMessage) are supported. func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) { var mw messageWriter if err := c.beginMessage(&mw, messageType); err != nil { return nil, err } c.writer = &mw if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) { w := c.newCompressionWriter(c.writer, c.compressionLevel) mw.compress = true c.writer = w } return c.writer, nil } type messageWriter struct { c *Conn compress bool // whether next call to flushFrame should set RSV1 pos int // end of data in writeBuf. frameType int // type of the current frame. err error } func (w *messageWriter) endMessage(err error) error { if w.err != nil { return err } c := w.c w.err = err c.writer = nil if c.writePool != nil { c.writePool.Put(writePoolData{buf: c.writeBuf}) c.writeBuf = nil } return err } // flushFrame writes buffered data and extra as a frame to the network. The // final argument indicates that this is the last frame in the message. func (w *messageWriter) flushFrame(final bool, extra []byte) error { c := w.c length := w.pos - maxFrameHeaderSize + len(extra) // Check for invalid control frames. if isControl(w.frameType) && (!final || length > maxControlFramePayloadSize) { return w.endMessage(errInvalidControlFrame) } b0 := byte(w.frameType) if final { b0 |= finalBit } if w.compress { b0 |= rsv1Bit } w.compress = false b1 := byte(0) if !c.isServer { b1 |= maskBit } // Assume that the frame starts at beginning of c.writeBuf. framePos := 0 if c.isServer { // Adjust up if mask not included in the header. framePos = 4 } switch { case length >= 65536: c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | 127 binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length)) case length > 125: framePos += 6 c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | 126 binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length)) default: framePos += 8 c.writeBuf[framePos] = b0 c.writeBuf[framePos+1] = b1 | byte(length) } if !c.isServer { key := newMaskKey() copy(c.writeBuf[maxFrameHeaderSize-4:], key[:]) maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos]) if len(extra) > 0 { return w.endMessage(c.writeFatal(errors.New("websocket: internal error, extra used in client mode"))) } } // Write the buffers to the connection with best-effort detection of // concurrent writes. See the concurrency section in the package // documentation for more info. if c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = true err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra) if !c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = false if err != nil { return w.endMessage(err) } if final { _ = w.endMessage(errWriteClosed) return nil } // Setup for next frame. w.pos = maxFrameHeaderSize w.frameType = continuationFrame return nil } func (w *messageWriter) ncopy(max int) (int, error) { n := len(w.c.writeBuf) - w.pos if n <= 0 { if err := w.flushFrame(false, nil); err != nil { return 0, err } n = len(w.c.writeBuf) - w.pos } if n > max { n = max } return n, nil } func (w *messageWriter) Write(p []byte) (int, error) { if w.err != nil { return 0, w.err } if len(p) > 2*len(w.c.writeBuf) && w.c.isServer { // Don't buffer large messages. err := w.flushFrame(false, p) if err != nil { return 0, err } return len(p), nil } nn := len(p) for len(p) > 0 { n, err := w.ncopy(len(p)) if err != nil { return 0, err } copy(w.c.writeBuf[w.pos:], p[:n]) w.pos += n p = p[n:] } return nn, nil } func (w *messageWriter) WriteString(p string) (int, error) { if w.err != nil { return 0, w.err } nn := len(p) for len(p) > 0 { n, err := w.ncopy(len(p)) if err != nil { return 0, err } copy(w.c.writeBuf[w.pos:], p[:n]) w.pos += n p = p[n:] } return nn, nil } func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) { if w.err != nil { return 0, w.err } for { if w.pos == len(w.c.writeBuf) { err = w.flushFrame(false, nil) if err != nil { break } } var n int n, err = r.Read(w.c.writeBuf[w.pos:]) w.pos += n nn += int64(n) if err != nil { if err == io.EOF { err = nil } break } } return nn, err } func (w *messageWriter) Close() error { if w.err != nil { return w.err } return w.flushFrame(true, nil) } // WritePreparedMessage writes prepared message into connection. func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error { frameType, frameData, err := pm.frame(prepareKey{ isServer: c.isServer, compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType), compressionLevel: c.compressionLevel, }) if err != nil { return err } if c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = true err = c.write(frameType, c.writeDeadline, frameData, nil) if !c.isWriting { panic("concurrent write to websocket connection") } c.isWriting = false return err } // WriteMessage is a helper method for getting a writer using NextWriter, // writing the message and closing the writer. func (c *Conn) WriteMessage(messageType int, data []byte) error { if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) { // Fast path with no allocations and single frame. var mw messageWriter if err := c.beginMessage(&mw, messageType); err != nil { return err } n := copy(c.writeBuf[mw.pos:], data) mw.pos += n data = data[n:] return mw.flushFrame(true, data) } w, err := c.NextWriter(messageType) if err != nil { return err } if _, err = w.Write(data); err != nil { return err } return w.Close() } // SetWriteDeadline sets the write deadline on the underlying network // connection. After a write has timed out, the websocket state is corrupt and // all future writes will return an error. A zero value for t means writes will // not time out. func (c *Conn) SetWriteDeadline(t time.Time) error { c.writeDeadline = t return nil } // Read methods func (c *Conn) advanceFrame() (int, error) { // 1. Skip remainder of previous frame. if c.readRemaining > 0 { if _, err := io.CopyN(io.Discard, c.br, c.readRemaining); err != nil { return noFrame, err } } // 2. Read and parse first two bytes of frame header. // To aid debugging, collect and report all errors in the first two bytes // of the header. var errors []string p, err := c.read(2) if err != nil { return noFrame, err } frameType := int(p[0] & 0xf) final := p[0]&finalBit != 0 rsv1 := p[0]&rsv1Bit != 0 rsv2 := p[0]&rsv2Bit != 0 rsv3 := p[0]&rsv3Bit != 0 mask := p[1]&maskBit != 0 if err := c.setReadRemaining(int64(p[1] & 0x7f)); err != nil { return noFrame, err } c.readDecompress = false if rsv1 { if c.newDecompressionReader != nil { c.readDecompress = true } else { errors = append(errors, "RSV1 set") } } if rsv2 { errors = append(errors, "RSV2 set") } if rsv3 { errors = append(errors, "RSV3 set") } switch frameType { case CloseMessage, PingMessage, PongMessage: if c.readRemaining > maxControlFramePayloadSize { errors = append(errors, "len > 125 for control") } if !final { errors = append(errors, "FIN not set on control") } case TextMessage, BinaryMessage: if !c.readFinal { errors = append(errors, "data before FIN") } c.readFinal = final case continuationFrame: if c.readFinal { errors = append(errors, "continuation after FIN") } c.readFinal = final default: errors = append(errors, "bad opcode "+strconv.Itoa(frameType)) } if mask != c.isServer { errors = append(errors, "bad MASK") } if len(errors) > 0 { return noFrame, c.handleProtocolError(strings.Join(errors, ", ")) } // 3. Read and parse frame length as per // https://tools.ietf.org/html/rfc6455#section-5.2 // // The length of the "Payload data", in bytes: if 0-125, that is the payload // length. // - If 126, the following 2 bytes interpreted as a 16-bit unsigned // integer are the payload length. // - If 127, the following 8 bytes interpreted as // a 64-bit unsigned integer (the most significant bit MUST be 0) are the // payload length. Multibyte length quantities are expressed in network byte // order. switch c.readRemaining { case 126: p, err := c.read(2) if err != nil { return noFrame, err } if err := c.setReadRemaining(int64(binary.BigEndian.Uint16(p))); err != nil { return noFrame, err } case 127: p, err := c.read(8) if err != nil { return noFrame, err } if err := c.setReadRemaining(int64(binary.BigEndian.Uint64(p))); err != nil { return noFrame, err } } // 4. Handle frame masking. if mask { c.readMaskPos = 0 p, err := c.read(len(c.readMaskKey)) if err != nil { return noFrame, err } copy(c.readMaskKey[:], p) } // 5. For text and binary messages, enforce read limit and return. if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage { c.readLength += c.readRemaining // Don't allow readLength to overflow in the presence of a large readRemaining // counter. if c.readLength < 0 { return noFrame, ErrReadLimit } if c.readLimit > 0 && c.readLength > c.readLimit { if err := c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait)); err != nil { return noFrame, err } return noFrame, ErrReadLimit } return frameType, nil } // 6. Read control frame payload. var payload []byte if c.readRemaining > 0 { payload, err = c.read(int(c.readRemaining)) if err := c.setReadRemaining(0); err != nil { return noFrame, err } if err != nil { return noFrame, err } if c.isServer { maskBytes(c.readMaskKey, 0, payload) } } // 7. Process control frame payload. switch frameType { case PongMessage: if err := c.handlePong(string(payload)); err != nil { return noFrame, err } case PingMessage: if err := c.handlePing(string(payload)); err != nil { return noFrame, err } case CloseMessage: closeCode := CloseNoStatusReceived closeText := "" if len(payload) >= 2 { closeCode = int(binary.BigEndian.Uint16(payload)) if !isValidReceivedCloseCode(closeCode) { return noFrame, c.handleProtocolError("bad close code " + strconv.Itoa(closeCode)) } closeText = string(payload[2:]) if !utf8.ValidString(closeText) { return noFrame, c.handleProtocolError("invalid utf8 payload in close frame") } } if err := c.handleClose(closeCode, closeText); err != nil { return noFrame, err } return noFrame, &CloseError{Code: closeCode, Text: closeText} } return frameType, nil } func (c *Conn) handleProtocolError(message string) error { data := FormatCloseMessage(CloseProtocolError, message) if len(data) > maxControlFramePayloadSize { data = data[:maxControlFramePayloadSize] } if err := c.WriteControl(CloseMessage, data, time.Now().Add(writeWait)); err != nil { return err } return errors.New("websocket: " + message) } // NextReader returns the next data message received from the peer. The // returned messageType is either TextMessage or BinaryMessage. // // There can be at most one open reader on a connection. NextReader discards // the previous message if the application has not already consumed it. // // Applications must break out of the application's read loop when this method // returns a non-nil error value. Errors returned from this method are // permanent. Once this method returns a non-nil error, all subsequent calls to // this method return the same error. func (c *Conn) NextReader() (messageType int, r io.Reader, err error) { // Close previous reader, only relevant for decompression. if c.reader != nil { _ = c.reader.Close() c.reader = nil } c.messageReader = nil c.readLength = 0 for c.readErr == nil { frameType, err := c.advanceFrame() if err != nil { c.readErr = hideTempErr(err) break } if frameType == TextMessage || frameType == BinaryMessage { c.messageReader = &messageReader{c} c.reader = c.messageReader if c.readDecompress { c.reader = c.newDecompressionReader(c.reader) } return frameType, c.reader, nil } } // Applications that do handle the error returned from this method spin in // tight loop on connection failure. To help application developers detect // this error, panic on repeated reads to the failed connection. c.readErrCount++ if c.readErrCount >= 1000 { panic("repeated read on failed websocket connection") } return noFrame, nil, c.readErr } type messageReader struct{ c *Conn } func (r *messageReader) Read(b []byte) (int, error) { c := r.c if c.messageReader != r { return 0, io.EOF } for c.readErr == nil { if c.readRemaining > 0 { if int64(len(b)) > c.readRemaining { b = b[:c.readRemaining] } n, err := c.br.Read(b) c.readErr = hideTempErr(err) if c.isServer { c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n]) } rem := c.readRemaining rem -= int64(n) if err := c.setReadRemaining(rem); err != nil { return 0, err } if c.readRemaining > 0 && c.readErr == io.EOF { c.readErr = errUnexpectedEOF } return n, c.readErr } if c.readFinal { c.messageReader = nil return 0, io.EOF } frameType, err := c.advanceFrame() switch { case err != nil: c.readErr = hideTempErr(err) case frameType == TextMessage || frameType == BinaryMessage: c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader") } } err := c.readErr if err == io.EOF && c.messageReader == r { err = errUnexpectedEOF } return 0, err } func (r *messageReader) Close() error { return nil } // ReadMessage is a helper method for getting a reader using NextReader and // reading from that reader to a buffer. func (c *Conn) ReadMessage() (messageType int, p []byte, err error) { var r io.Reader messageType, r, err = c.NextReader() if err != nil { return messageType, nil, err } p, err = io.ReadAll(r) return messageType, p, err } // SetReadDeadline sets the read deadline on the underlying network connection. // After a read has timed out, the websocket connection state is corrupt and // all future reads will return an error. A zero value for t means reads will // not time out. func (c *Conn) SetReadDeadline(t time.Time) error { return c.conn.SetReadDeadline(t) } // SetReadLimit sets the maximum size in bytes for a message read from the peer. If a // message exceeds the limit, the connection sends a close message to the peer // and returns ErrReadLimit to the application. func (c *Conn) SetReadLimit(limit int64) { c.readLimit = limit } // CloseHandler returns the current close handler func (c *Conn) CloseHandler() func(code int, text string) error { return c.handleClose } // SetCloseHandler sets the handler for close messages received from the peer. // The code argument to h is the received close code or CloseNoStatusReceived // if the close message is empty. The default close handler sends a close // message back to the peer. // // The handler function is called from the NextReader, ReadMessage and message // reader Read methods. The application must read the connection to process // close messages as described in the section on Control Messages above. // // The connection read methods return a CloseError when a close message is // received. Most applications should handle close messages as part of their // normal error handling. Applications should only set a close handler when the // application must perform some action before sending a close message back to // the peer. func (c *Conn) SetCloseHandler(h func(code int, text string) error) { if h == nil { h = func(code int, text string) error { message := FormatCloseMessage(code, "") err := c.WriteControl(CloseMessage, message, time.Now().Add(writeWait)) if err != nil && err != ErrCloseSent { return err } return nil } } c.handleClose = h } // PingHandler returns the current ping handler func (c *Conn) PingHandler() func(appData string) error { return c.handlePing } // SetPingHandler sets the handler for ping messages received from the peer. // The appData argument to h is the PING message application data. The default // ping handler sends a pong to the peer. // // The handler function is called from the NextReader, ReadMessage and message // reader Read methods. The application must read the connection to process // ping messages as described in the section on Control Messages above. func (c *Conn) SetPingHandler(h func(appData string) error) { if h == nil { h = func(message string) error { err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait)) if err == ErrCloseSent { return nil } else if _, ok := err.(net.Error); ok { return nil } return err } } c.handlePing = h } // PongHandler returns the current pong handler func (c *Conn) PongHandler() func(appData string) error { return c.handlePong } // SetPongHandler sets the handler for pong messages received from the peer. // The appData argument to h is the PONG message application data. The default // pong handler does nothing. // // The handler function is called from the NextReader, ReadMessage and message // reader Read methods. The application must read the connection to process // pong messages as described in the section on Control Messages above. func (c *Conn) SetPongHandler(h func(appData string) error) { if h == nil { h = func(string) error { return nil } } c.handlePong = h } // NetConn returns the underlying connection that is wrapped by c. // Note that writing to or reading from this connection directly will corrupt the // WebSocket connection. func (c *Conn) NetConn() net.Conn { return c.conn } // UnderlyingConn returns the internal net.Conn. This can be used to further // modifications to connection specific flags. // Deprecated: Use the NetConn method. func (c *Conn) UnderlyingConn() net.Conn { return c.conn } // EnableWriteCompression enables and disables write compression of // subsequent text and binary messages. This function is a noop if // compression was not negotiated with the peer. func (c *Conn) EnableWriteCompression(enable bool) { c.enableWriteCompression = enable } // SetCompressionLevel sets the flate compression level for subsequent text and // binary messages. This function is a noop if compression was not negotiated // with the peer. See the compress/flate package for a description of // compression levels. func (c *Conn) SetCompressionLevel(level int) error { if !isValidCompressionLevel(level) { return errors.New("websocket: invalid compression level") } c.compressionLevel = level return nil } // FormatCloseMessage formats closeCode and text as a WebSocket close message. // An empty message is returned for code CloseNoStatusReceived. func FormatCloseMessage(closeCode int, text string) []byte { if closeCode == CloseNoStatusReceived { // Return empty message because it's illegal to send // CloseNoStatusReceived. Return non-nil value in case application // checks for nil. return []byte{} } buf := make([]byte, 2+len(text)) binary.BigEndian.PutUint16(buf, uint16(closeCode)) copy(buf[2:], text) return buf }
// 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 ( "bufio" "bytes" "errors" "fmt" "io" "net" "reflect" "sync" "testing" "testing/iotest" "time" ) var _ net.Error = errWriteTimeout type fakeNetConn struct { io.Reader io.Writer } func (c fakeNetConn) Close() error { return nil } func (c fakeNetConn) LocalAddr() net.Addr { return localAddr } func (c fakeNetConn) RemoteAddr() net.Addr { return remoteAddr } func (c fakeNetConn) SetDeadline(t time.Time) error { return nil } func (c fakeNetConn) SetReadDeadline(t time.Time) error { return nil } func (c fakeNetConn) SetWriteDeadline(t time.Time) error { return nil } type fakeAddr int var ( localAddr = fakeAddr(1) remoteAddr = fakeAddr(2) ) func (a fakeAddr) Network() string { return "net" } func (a fakeAddr) String() string { return "str" } // newTestConn creates a connnection backed by a fake network connection using // default values for buffering. func newTestConn(r io.Reader, w io.Writer, isServer bool) *Conn { return newConn(fakeNetConn{Reader: r, Writer: w}, isServer, 1024, 1024, nil, nil, nil) } func TestFraming(t *testing.T) { frameSizes := []int{ 0, 1, 2, 124, 125, 126, 127, 128, 129, 65534, 65535, // 65536, 65537 } var readChunkers = []struct { name string f func(io.Reader) io.Reader }{ {"half", iotest.HalfReader}, {"one", iotest.OneByteReader}, {"asis", func(r io.Reader) io.Reader { return r }}, } writeBuf := make([]byte, 65537) for i := range writeBuf { writeBuf[i] = byte(i) } var writers = []struct { name string f func(w io.Writer, n int) (int, error) }{ {"iocopy", func(w io.Writer, n int) (int, error) { nn, err := io.Copy(w, bytes.NewReader(writeBuf[:n])) return int(nn), err }}, {"write", func(w io.Writer, n int) (int, error) { return w.Write(writeBuf[:n]) }}, {"string", func(w io.Writer, n int) (int, error) { return io.WriteString(w, string(writeBuf[:n])) }}, } for _, compress := range []bool{false, true} { for _, isServer := range []bool{true, false} { for _, chunker := range readChunkers { var connBuf bytes.Buffer wc := newTestConn(nil, &connBuf, isServer) rc := newTestConn(chunker.f(&connBuf), nil, !isServer) if compress { wc.newCompressionWriter = compressNoContextTakeover rc.newDecompressionReader = decompressNoContextTakeover } for _, n := range frameSizes { for _, writer := range writers { name := fmt.Sprintf("z:%v, s:%v, r:%s, n:%d w:%s", compress, isServer, chunker.name, n, writer.name) w, err := wc.NextWriter(TextMessage) if err != nil { t.Errorf("%s: wc.NextWriter() returned %v", name, err) continue } nn, err := writer.f(w, n) if err != nil || nn != n { t.Errorf("%s: w.Write(writeBuf[:n]) returned %d, %v", name, nn, err) continue } err = w.Close() if err != nil { t.Errorf("%s: w.Close() returned %v", name, err) continue } opCode, r, err := rc.NextReader() if err != nil || opCode != TextMessage { t.Errorf("%s: NextReader() returned %d, r, %v", name, opCode, err) continue } rbuf, err := io.ReadAll(r) if err != nil { t.Errorf("%s: ReadFull() returned rbuf, %v", name, err) continue } if len(rbuf) != n { t.Errorf("%s: len(rbuf) is %d, want %d", name, len(rbuf), n) continue } for i, b := range rbuf { if byte(i) != b { t.Errorf("%s: bad byte at offset %d", name, i) break } } } } } } } } func TestControl(t *testing.T) { const message = "this is a ping/pong messsage" for _, isServer := range []bool{true, false} { for _, isWriteControl := range []bool{true, false} { name := fmt.Sprintf("s:%v, wc:%v", isServer, isWriteControl) var connBuf bytes.Buffer wc := newTestConn(nil, &connBuf, isServer) rc := newTestConn(&connBuf, nil, !isServer) if isWriteControl { if err := wc.WriteControl(PongMessage, []byte(message), time.Now().Add(time.Second)); err != nil { t.Errorf("%s: wc.WriteControl() returned %v", name, err) continue } } else { w, err := wc.NextWriter(PongMessage) if err != nil { t.Errorf("%s: wc.NextWriter() returned %v", name, err) continue } if _, err := w.Write([]byte(message)); err != nil { t.Errorf("%s: w.Write() returned %v", name, err) continue } if err := w.Close(); err != nil { t.Errorf("%s: w.Close() returned %v", name, err) continue } var actualMessage string rc.SetPongHandler(func(s string) error { actualMessage = s; return nil }) if _, _, err := rc.NextReader(); err != nil { continue } if actualMessage != message { t.Errorf("%s: pong=%q, want %q", name, actualMessage, message) continue } } } } } // simpleBufferPool is an implementation of BufferPool for TestWriteBufferPool. type simpleBufferPool struct { v interface{} } func (p *simpleBufferPool) Get() interface{} { v := p.v p.v = nil return v } func (p *simpleBufferPool) Put(v interface{}) { p.v = v } func TestWriteBufferPool(t *testing.T) { const message = "Now is the time for all good people to come to the aid of the party." var buf bytes.Buffer var pool simpleBufferPool rc := newTestConn(&buf, nil, false) // Specify writeBufferSize smaller than message size to ensure that pooling // works with fragmented messages. wc := newConn(fakeNetConn{Writer: &buf}, true, 1024, len(message)-1, &pool, nil, nil) if wc.writeBuf != nil { t.Fatal("writeBuf not nil after create") } // Part 1: test NextWriter/Write/Close w, err := wc.NextWriter(TextMessage) if err != nil { t.Fatalf("wc.NextWriter() returned %v", err) } if wc.writeBuf == nil { t.Fatal("writeBuf is nil after NextWriter") } writeBufAddr := &wc.writeBuf[0] if _, err := io.WriteString(w, message); err != nil { t.Fatalf("io.WriteString(w, message) returned %v", err) } if err := w.Close(); err != nil { t.Fatalf("w.Close() returned %v", err) } if wc.writeBuf != nil { t.Fatal("writeBuf not nil after w.Close()") } if wpd, ok := pool.v.(writePoolData); !ok || len(wpd.buf) == 0 || &wpd.buf[0] != writeBufAddr { t.Fatal("writeBuf not returned to pool") } opCode, p, err := rc.ReadMessage() if opCode != TextMessage || err != nil { t.Fatalf("ReadMessage() returned %d, p, %v", opCode, err) } if s := string(p); s != message { t.Fatalf("message is %s, want %s", s, message) } // Part 2: Test WriteMessage. if err := wc.WriteMessage(TextMessage, []byte(message)); err != nil { t.Fatalf("wc.WriteMessage() returned %v", err) } if wc.writeBuf != nil { t.Fatal("writeBuf not nil after wc.WriteMessage()") } if wpd, ok := pool.v.(writePoolData); !ok || len(wpd.buf) == 0 || &wpd.buf[0] != writeBufAddr { t.Fatal("writeBuf not returned to pool after WriteMessage") } opCode, p, err = rc.ReadMessage() if opCode != TextMessage || err != nil { t.Fatalf("ReadMessage() returned %d, p, %v", opCode, err) } if s := string(p); s != message { t.Fatalf("message is %s, want %s", s, message) } } // TestWriteBufferPoolSync ensures that *sync.Pool works as a buffer pool. func TestWriteBufferPoolSync(t *testing.T) { var buf bytes.Buffer var pool sync.Pool wc := newConn(fakeNetConn{Writer: &buf}, true, 1024, 1024, &pool, nil, nil) rc := newTestConn(&buf, nil, false) const message = "Hello World!" for i := 0; i < 3; i++ { if err := wc.WriteMessage(TextMessage, []byte(message)); err != nil { t.Fatalf("wc.WriteMessage() returned %v", err) } opCode, p, err := rc.ReadMessage() if opCode != TextMessage || err != nil { t.Fatalf("ReadMessage() returned %d, p, %v", opCode, err) } if s := string(p); s != message { t.Fatalf("message is %s, want %s", s, message) } } } // errorWriter is an io.Writer than returns an error on all writes. type errorWriter struct{} func (ew errorWriter) Write(p []byte) (int, error) { return 0, errors.New("error") } // TestWriteBufferPoolError ensures that buffer is returned to pool after error // on write. func TestWriteBufferPoolError(t *testing.T) { // Part 1: Test NextWriter/Write/Close var pool simpleBufferPool wc := newConn(fakeNetConn{Writer: errorWriter{}}, true, 1024, 1024, &pool, nil, nil) w, err := wc.NextWriter(TextMessage) if err != nil { t.Fatalf("wc.NextWriter() returned %v", err) } if wc.writeBuf == nil { t.Fatal("writeBuf is nil after NextWriter") } writeBufAddr := &wc.writeBuf[0] if _, err := io.WriteString(w, "Hello"); err != nil { t.Fatalf("io.WriteString(w, message) returned %v", err) } if err := w.Close(); err == nil { t.Fatalf("w.Close() did not return error") } if wpd, ok := pool.v.(writePoolData); !ok || len(wpd.buf) == 0 || &wpd.buf[0] != writeBufAddr { t.Fatal("writeBuf not returned to pool") } // Part 2: Test WriteMessage wc = newConn(fakeNetConn{Writer: errorWriter{}}, true, 1024, 1024, &pool, nil, nil) if err := wc.WriteMessage(TextMessage, []byte("Hello")); err == nil { t.Fatalf("wc.WriteMessage did not return error") } if wpd, ok := pool.v.(writePoolData); !ok || len(wpd.buf) == 0 || &wpd.buf[0] != writeBufAddr { t.Fatal("writeBuf not returned to pool") } } func TestCloseFrameBeforeFinalMessageFrame(t *testing.T) { const bufSize = 512 expectedErr := &CloseError{Code: CloseNormalClosure, Text: "hello"} var b1, b2 bytes.Buffer wc := newConn(&fakeNetConn{Reader: nil, Writer: &b1}, false, 1024, bufSize, nil, nil, nil) rc := newTestConn(&b1, &b2, true) w, _ := wc.NextWriter(BinaryMessage) if _, err := w.Write(make([]byte, bufSize+bufSize/2)); err != nil { t.Fatalf("w.Write() returned %v", err) } if err := wc.WriteControl(CloseMessage, FormatCloseMessage(expectedErr.Code, expectedErr.Text), time.Now().Add(10*time.Second)); err != nil { t.Fatalf("wc.WriteControl() returned %v", err) } w.Close() op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } _, err = io.Copy(io.Discard, r) if !reflect.DeepEqual(err, expectedErr) { t.Fatalf("io.Copy() returned %v, want %v", err, expectedErr) } _, _, err = rc.NextReader() if !reflect.DeepEqual(err, expectedErr) { t.Fatalf("NextReader() returned %v, want %v", err, expectedErr) } } func TestEOFWithinFrame(t *testing.T) { const bufSize = 64 for n := 0; ; n++ { var b bytes.Buffer wc := newTestConn(nil, &b, false) rc := newTestConn(&b, nil, true) w, _ := wc.NextWriter(BinaryMessage) if _, err := w.Write(make([]byte, bufSize)); err != nil { t.Fatalf("%d: w.Write() returned %v", n, err) } w.Close() if n >= b.Len() { break } b.Truncate(n) op, r, err := rc.NextReader() if err == errUnexpectedEOF { continue } if op != BinaryMessage || err != nil { t.Fatalf("%d: NextReader() returned %d, %v", n, op, err) } _, err = io.Copy(io.Discard, r) if err != errUnexpectedEOF { t.Fatalf("%d: io.Copy() returned %v, want %v", n, err, errUnexpectedEOF) } _, _, err = rc.NextReader() if err != errUnexpectedEOF { t.Fatalf("%d: NextReader() returned %v, want %v", n, err, errUnexpectedEOF) } } } func TestEOFBeforeFinalFrame(t *testing.T) { const bufSize = 512 var b1, b2 bytes.Buffer wc := newConn(&fakeNetConn{Writer: &b1}, false, 1024, bufSize, nil, nil, nil) rc := newTestConn(&b1, &b2, true) w, _ := wc.NextWriter(BinaryMessage) if _, err := w.Write(make([]byte, bufSize+bufSize/2)); err != nil { t.Fatalf("w.Write() returned %v", err) } op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } _, err = io.Copy(io.Discard, r) if err != errUnexpectedEOF { t.Fatalf("io.Copy() returned %v, want %v", err, errUnexpectedEOF) } _, _, err = rc.NextReader() if err != errUnexpectedEOF { t.Fatalf("NextReader() returned %v, want %v", err, errUnexpectedEOF) } } func TestWriteAfterMessageWriterClose(t *testing.T) { wc := newTestConn(nil, &bytes.Buffer{}, false) w, _ := wc.NextWriter(BinaryMessage) if _, err := io.WriteString(w, "hello"); err != nil { t.Fatalf("unexpected error writing, %v", err) } if err := w.Close(); err != nil { t.Fatalf("unxpected error closing message writer, %v", err) } if _, err := io.WriteString(w, "world"); err == nil { t.Fatalf("no error writing after close") } w, _ = wc.NextWriter(BinaryMessage) if _, err := io.WriteString(w, "hello"); err != nil { t.Fatalf("unexpected error writing after getting new writer, %v", err) } // close w by getting next writer _, err := wc.NextWriter(BinaryMessage) if err != nil { t.Fatalf("unexpected error getting next writer, %v", err) } if _, err := io.WriteString(w, "world"); err == nil { t.Fatalf("no error writing after close") } } func TestWriteHandlerDoesNotReturnErrCloseSent(t *testing.T) { var b1, b2 bytes.Buffer client := newTestConn(&b2, &b1, false) server := newTestConn(&b1, &b2, true) msg := FormatCloseMessage(CloseNormalClosure, "") if err := client.WriteMessage(CloseMessage, msg); err != nil { t.Fatalf("unexpected error when writing close message, %v", err) } if _, _, err := server.NextReader(); !IsCloseError(err, 1000) { t.Fatalf("server expects a close message, %v returned", err) } if _, _, err := client.NextReader(); !IsCloseError(err, 1000) { t.Fatalf("client expects a close message, %v returned", err) } } func TestReadLimit(t *testing.T) { t.Run("Test ReadLimit is enforced", func(t *testing.T) { const readLimit = 512 message := make([]byte, readLimit+1) var b1, b2 bytes.Buffer wc := newConn(&fakeNetConn{Writer: &b1}, false, 1024, readLimit-2, nil, nil, nil) rc := newTestConn(&b1, &b2, true) rc.SetReadLimit(readLimit) // Send message at the limit with interleaved pong. w, _ := wc.NextWriter(BinaryMessage) if _, err := w.Write(message[:readLimit-1]); err != nil { t.Fatalf("w.WriteMessage() returned %v", err) } if err := wc.WriteControl(PongMessage, []byte("this is a pong"), time.Now().Add(10*time.Second)); err != nil { t.Fatalf("wc.WriteControl() returned %v", err) } if _, err := w.Write(message[:1]); err != nil { t.Fatalf("w.Write() returned %v", err) } w.Close() // Send message larger than the limit. if err := wc.WriteMessage(BinaryMessage, message[:readLimit+1]); err != nil { t.Fatalf("wc.WriteMessage() returned %v", err) } op, _, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("1: NextReader() returned %d, %v", op, err) } op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("2: NextReader() returned %d, %v", op, err) } _, err = io.Copy(io.Discard, r) if err != ErrReadLimit { t.Fatalf("io.Copy() returned %v", err) } }) t.Run("Test that ReadLimit cannot be overflowed", func(t *testing.T) { const readLimit = 1 var b1, b2 bytes.Buffer rc := newTestConn(&b1, &b2, true) rc.SetReadLimit(readLimit) // First, send a non-final binary message b1.Write([]byte("\x02\x81")) // Mask key b1.Write([]byte("\x00\x00\x00\x00")) // First payload b1.Write([]byte("A")) // Next, send a negative-length, non-final continuation frame b1.Write([]byte("\x00\xFF\x80\x00\x00\x00\x00\x00\x00\x00")) // Mask key b1.Write([]byte("\x00\x00\x00\x00")) // Next, send a too long, final continuation frame b1.Write([]byte("\x80\xFF\x00\x00\x00\x00\x00\x00\x00\x05")) // Mask key b1.Write([]byte("\x00\x00\x00\x00")) // Too-long payload b1.Write([]byte("BCDEF")) op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("1: NextReader() returned %d, %v", op, err) } var buf [10]byte var read int n, err := r.Read(buf[:]) if err != nil && err != ErrReadLimit { t.Fatalf("unexpected error testing read limit: %v", err) } read += n n, err = r.Read(buf[:]) if err != nil && err != ErrReadLimit { t.Fatalf("unexpected error testing read limit: %v", err) } read += n if err == nil && read > readLimit { t.Fatalf("read limit exceeded: limit %d, read %d", readLimit, read) } }) } func TestAddrs(t *testing.T) { c := newTestConn(nil, nil, true) if c.LocalAddr() != localAddr { t.Errorf("LocalAddr = %v, want %v", c.LocalAddr(), localAddr) } if c.RemoteAddr() != remoteAddr { t.Errorf("RemoteAddr = %v, want %v", c.RemoteAddr(), remoteAddr) } } func TestDeprecatedUnderlyingConn(t *testing.T) { var b1, b2 bytes.Buffer fc := fakeNetConn{Reader: &b1, Writer: &b2} c := newConn(fc, true, 1024, 1024, nil, nil, nil) ul := c.UnderlyingConn() if ul != fc { t.Fatalf("Underlying conn is not what it should be.") } } func TestNetConn(t *testing.T) { var b1, b2 bytes.Buffer fc := fakeNetConn{Reader: &b1, Writer: &b2} c := newConn(fc, true, 1024, 1024, nil, nil, nil) ul := c.NetConn() if ul != fc { t.Fatalf("Underlying conn is not what it should be.") } } func TestBufioReadBytes(t *testing.T) { // Test calling bufio.ReadBytes for value longer than read buffer size. m := make([]byte, 512) m[len(m)-1] = '\n' var b1, b2 bytes.Buffer wc := newConn(fakeNetConn{Writer: &b1}, false, len(m)+64, len(m)+64, nil, nil, nil) rc := newConn(fakeNetConn{Reader: &b1, Writer: &b2}, true, len(m)-64, len(m)-64, nil, nil, nil) w, _ := wc.NextWriter(BinaryMessage) if _, err := w.Write(m); err != nil { t.Fatalf("w.Write() returned %v", err) } w.Close() op, r, err := rc.NextReader() if op != BinaryMessage || err != nil { t.Fatalf("NextReader() returned %d, %v", op, err) } br := bufio.NewReader(r) p, err := br.ReadBytes('\n') if err != nil { t.Fatalf("ReadBytes() returned %v", err) } if len(p) != len(m) { t.Fatalf("read returned %d bytes, want %d bytes", len(p), len(m)) } } var closeErrorTests = []struct { err error codes []int ok bool }{ {&CloseError{Code: CloseNormalClosure}, []int{CloseNormalClosure}, true}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived}, false}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived, CloseNormalClosure}, true}, {errors.New("hello"), []int{CloseNormalClosure}, false}, } func TestCloseError(t *testing.T) { for _, tt := range closeErrorTests { ok := IsCloseError(tt.err, tt.codes...) if ok != tt.ok { t.Errorf("IsCloseError(%#v, %#v) returned %v, want %v", tt.err, tt.codes, ok, tt.ok) } } } var unexpectedCloseErrorTests = []struct { err error codes []int ok bool }{ {&CloseError{Code: CloseNormalClosure}, []int{CloseNormalClosure}, false}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived}, true}, {&CloseError{Code: CloseNormalClosure}, []int{CloseNoStatusReceived, CloseNormalClosure}, false}, {errors.New("hello"), []int{CloseNormalClosure}, false}, } func TestUnexpectedCloseErrors(t *testing.T) { for _, tt := range unexpectedCloseErrorTests { ok := IsUnexpectedCloseError(tt.err, tt.codes...) if ok != tt.ok { t.Errorf("IsUnexpectedCloseError(%#v, %#v) returned %v, want %v", tt.err, tt.codes, ok, tt.ok) } } } type blockingWriter struct { c1, c2 chan struct{} } func (w blockingWriter) Write(p []byte) (int, error) { // Allow main to continue close(w.c1) // Wait for panic in main <-w.c2 return len(p), nil } func TestConcurrentWritePanic(t *testing.T) { w := blockingWriter{make(chan struct{}), make(chan struct{})} c := newTestConn(nil, w, false) go func() { if err := c.WriteMessage(TextMessage, []byte{}); err != nil { t.Error(err) } }() // wait for goroutine to block in write. <-w.c1 defer func() { close(w.c2) if v := recover(); v != nil { return } }() if err := c.WriteMessage(TextMessage, []byte{}); err != nil { t.Error(err) } t.Fatal("should not get here") } type failingReader struct{} func (r failingReader) Read(p []byte) (int, error) { return 0, io.EOF } func TestFailedConnectionReadPanic(t *testing.T) { c := newTestConn(failingReader{}, nil, false) defer func() { if v := recover(); v != nil { return } }() for i := 0; i < 20000; i++ { _, _, _ = c.ReadMessage() } t.Fatal("should not get here") }
35
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: import copyToClipboard from 'copy-to-clipboard'; import log from 'loglevel'; import { clone } from 'lodash'; import React from 'react'; import { render } from 'react-dom'; import browser from 'webextension-polyfill'; import { getEnvironmentType } from '../app/scripts/lib/util'; import { AlertTypes } from '../shared/constants/alerts'; import { maskObject } from '../shared/modules/object.utils'; import { SENTRY_UI_STATE } from '../app/scripts/lib/setupSentry'; import { ENVIRONMENT_TYPE_POPUP } from '../shared/constants/app'; import { COPY_OPTIONS } from '../shared/constants/copy'; import switchDirection from '../shared/lib/switch-direction'; import { setupLocale } from '../shared/lib/error-utils'; import * as actions from './store/actions'; import configureStore from './store/store'; import { getPermittedAccountsForCurrentTab, getSelectedAddress, getUnapprovedTransactions, } from './selectors'; import { ALERT_STATE } from './ducks/alerts'; import { getUnconnectedAccountAlertEnabledness, getUnconnectedAccountAlertShown, } from './ducks/metamask/metamask'; import Root from './pages'; import txHelper from './helpers/utils/tx-helper'; import { setBackgroundConnection } from './store/background-connection'; log.setLevel(global.METAMASK_DEBUG ? 'debug' : 'warn', false); let reduxStore; /** * Method to update backgroundConnection object use by UI * * @param backgroundConnection - connection object to background */ export const updateBackgroundConnection = (backgroundConnection) => { setBackgroundConnection(backgroundConnection); backgroundConnection.onNotification((data) => { if (data.method === 'sendUpdate') { reduxStore.dispatch(actions.updateMetamaskState(data.params[0])); } else { throw new Error( `Internal JSON-RPC Notification Not Handled:\n\n ${JSON.stringify( data, )}`, ); } }); }; export default function launchMetamaskUi(opts, cb) { const { backgroundConnection } = opts; ///: BEGIN:ONLY_INCLUDE_IF(desktop) let desktopEnabled = false; backgroundConnection.getDesktopEnabled(function (err, result) { if (err) { return; } desktopEnabled = result; }); ///: END:ONLY_INCLUDE_IF // check if we are unlocked first backgroundConnection.getState(function (err, metamaskState) { if (err) { cb( err, { ...metamaskState, ///: BEGIN:ONLY_INCLUDE_IF(desktop) desktopEnabled, ///: END:ONLY_INCLUDE_IF }, backgroundConnection, ); return; } startApp(metamaskState, backgroundConnection, opts).then((store) => { setupStateHooks(store); cb( null, store, ///: BEGIN:ONLY_INCLUDE_IF(desktop) backgroundConnection, ///: END:ONLY_INCLUDE_IF ); }); }); } async function startApp(metamaskState, backgroundConnection, opts) { // parse opts if (!metamaskState.featureFlags) { metamaskState.featureFlags = {}; } const { currentLocaleMessages, enLocaleMessages } = await setupLocale( metamaskState.currentLocale, ); if (metamaskState.textDirection === 'rtl') { await switchDirection('rtl'); } const draftInitialState = { activeTab: opts.activeTab, // metamaskState represents the cross-tab state metamask: metamaskState, // appState represents the current tab's popup state appState: {}, localeMessages: { currentLocale: metamaskState.currentLocale, current: currentLocaleMessages, en: enLocaleMessages, }, }; updateBackgroundConnection(backgroundConnection); if (getEnvironmentType() === ENVIRONMENT_TYPE_POPUP) { const { origin } = draftInitialState.activeTab; const permittedAccountsForCurrentTab = getPermittedAccountsForCurrentTab(draftInitialState); const selectedAddress = getSelectedAddress(draftInitialState); const unconnectedAccountAlertShownOrigins = getUnconnectedAccountAlertShown(draftInitialState); const unconnectedAccountAlertIsEnabled = getUnconnectedAccountAlertEnabledness(draftInitialState); if ( origin && unconnectedAccountAlertIsEnabled && !unconnectedAccountAlertShownOrigins[origin] && permittedAccountsForCurrentTab.length > 0 && !permittedAccountsForCurrentTab.includes(selectedAddress) ) { draftInitialState[AlertTypes.unconnectedAccount] = { state: ALERT_STATE.OPEN, }; actions.setUnconnectedAccountAlertShown(origin); } } const store = configureStore(draftInitialState); reduxStore = store; const unapprovedTxs = getUnapprovedTransactions(metamaskState); // if unconfirmed txs, start on txConf page const unapprovedTxsAll = txHelper( unapprovedTxs, metamaskState.unapprovedMsgs, metamaskState.unapprovedPersonalMsgs, metamaskState.unapprovedDecryptMsgs, metamaskState.unapprovedEncryptionPublicKeyMsgs, metamaskState.unapprovedTypedMessages, metamaskState.providerConfig.chainId, ); const numberOfUnapprovedTx = unapprovedTxsAll.length; if (numberOfUnapprovedTx > 0) { store.dispatch( actions.showConfTxPage({ id: unapprovedTxsAll[0].id, }), ); } // global metamask api - used by tooling global.metamask = { updateCurrentLocale: (code) => { store.dispatch(actions.updateCurrentLocale(code)); }, setProviderType: (type) => { store.dispatch(actions.setProviderType(type)); }, setFeatureFlag: (key, value) => { store.dispatch(actions.setFeatureFlag(key, value)); }, }; // start app render(<Root store={store} />, opts.container); return store; } /** * Setup functions on `window.stateHooks`. Some of these support * application features, and some are just for debugging or testing. * * @param {object} store - The Redux store. */ function setupStateHooks(store) { if (process.env.METAMASK_DEBUG || process.env.IN_TEST) { /** * The following stateHook is a method intended to throw an error, used in * our E2E test to ensure that errors are attempted to be sent to sentry. * * @param {string} [msg] - The error message to throw, defaults to 'Test Error' */ window.stateHooks.throwTestError = async function (msg = 'Test Error') { const error = new Error(msg); error.name = 'TestError'; throw error; }; /** * The following stateHook is a method intended to throw an error in the * background, used in our E2E test to ensure that errors are attempted to be * sent to sentry. * * @param {string} [msg] - The error message to throw, defaults to 'Test Error' */ window.stateHooks.throwTestBackgroundError = async function ( msg = 'Test Error', ) { store.dispatch(actions.throwTestBackgroundError(msg)); }; } window.stateHooks.getCleanAppState = async function () { const state = clone(store.getState()); state.version = global.platform.getVersion(); state.browser = window.navigator.userAgent; state.completeTxList = await actions.getTransactions({ filterToCurrentNetwork: false, }); return state; }; window.stateHooks.getSentryAppState = function () { const reduxState = store.getState(); return maskObject(reduxState, SENTRY_UI_STATE); }; window.stateHooks.getLogs = function () { // These logs are logged by LoggingController const reduxState = store.getState(); const { logs } = reduxState.metamask; const logsArray = Object.values(logs).sort((a, b) => { return a.timestamp - b.timestamp; }); return logsArray; }; } window.logStateString = async function (cb) { const state = await window.stateHooks.getCleanAppState(); const logs = window.stateHooks.getLogs(); browser.runtime .getPlatformInfo() .then((platform) => { state.platform = platform; state.logs = logs; const stateString = JSON.stringify(state, null, 2); cb(null, stateString); }) .catch((err) => { cb(err); }); }; window.logState = function (toClipboard) { return window.logStateString((err, result) => { if (err) { console.error(err.message); } else if (toClipboard) { copyToClipboard(result, COPY_OPTIONS); console.log('State log copied'); } else { console.log(result); } }); };
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
36
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: export * from './confirm'; export * from './confirm-transaction'; export * from './custom-gas'; export * from './first-time-flow'; export * from './metametrics'; export * from './permissions'; export * from './selectors'; export * from './transactions'; export * from './approvals';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
37
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: import { combineReducers } from 'redux'; import { AlertTypes } from '../../shared/constants/alerts'; import confirmReducer from './confirm/confirm'; import metamaskReducer from './metamask/metamask'; import localeMessagesReducer from './locale/locale'; import sendReducer from './send/send'; import domainReducer from './domains'; import appStateReducer from './app/app'; import confirmTransactionReducer from './confirm-transaction/confirm-transaction.duck'; import gasReducer from './gas/gas.duck'; import { invalidCustomNetwork, unconnectedAccount } from './alerts'; import swapsReducer from './swaps/swaps'; import historyReducer from './history/history'; export default combineReducers({ [AlertTypes.invalidCustomNetwork]: invalidCustomNetwork, [AlertTypes.unconnectedAccount]: unconnectedAccount, activeTab: (s) => (s === undefined ? null : s), metamask: metamaskReducer, appState: appStateReducer, DNS: domainReducer, history: historyReducer, send: sendReducer, confirm: confirmReducer, confirmTransaction: confirmTransactionReducer, swaps: swapsReducer, gas: gasReducer, localeMessages: localeMessagesReducer, });
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
38
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: export { default as unconnectedAccount } from './unconnected-account'; export { default as invalidCustomNetwork } from './invalid-custom-network'; export { ALERT_STATE } from './enums';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
39
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: export * from './send';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
40
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: export { default as institutionalFeature } from './institutional';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
41
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: import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { Provider } from 'react-redux'; import { HashRouter } from 'react-router-dom'; import * as Sentry from '@sentry/browser'; import { I18nProvider, LegacyI18nProvider } from '../contexts/i18n'; import { MetaMetricsProvider, LegacyMetaMetricsProvider, } from '../contexts/metametrics'; import ErrorPage from './error'; import Routes from './routes'; class Index extends PureComponent { state = {}; static getDerivedStateFromError(error) { return { error }; } componentDidCatch(error) { Sentry.captureException(error); } render() { const { error, errorId } = this.state; const { store } = this.props; if (error) { return ( <Provider store={store}> <I18nProvider> <LegacyI18nProvider> <ErrorPage error={error} errorId={errorId} /> </LegacyI18nProvider> </I18nProvider> </Provider> ); } return ( <Provider store={store}> <HashRouter hashType="noslash"> <MetaMetricsProvider> <LegacyMetaMetricsProvider> <I18nProvider> <LegacyI18nProvider> <Routes /> </LegacyI18nProvider> </I18nProvider> </LegacyMetaMetricsProvider> </MetaMetricsProvider> </HashRouter> </Provider> ); } } Index.propTypes = { store: PropTypes.object, }; export default Index;
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
42
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: export { default } from './send';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
43
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: export { default } from './gas-display';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
44
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: export { default } from './send-content.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
45
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: export { default } from './send-gas-row.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
46
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: export { default } from './add-recipient.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
47
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: export { default } from './send-row-wrapper.component';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
48
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: export { default } from './send-row-error-message.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
49
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: export { default } from './send-amount-row.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
50
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: export { default } from './amount-max-button';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
51
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: export { default } from './send-asset-row.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
52
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: export { default } from './send-hex-data-row.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
53
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: export { default } from './send-header.component';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
54
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: export { default } from './send-footer.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
55
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: export { default } from './token-details-page';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
56
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: export { default } from './confirm-add-suggested-nft';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
57
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: export { default } from './asset';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
58
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: export { default } from './desktop-pairing.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
59
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: export { default } from './confirm-transaction-base.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
60
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: export { default } from './settings.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
61
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: export { default } from './security-tab.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
62
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: export { default } from './networks-tab';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
63
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: export { default } from './networks-tab-content';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
64
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: export { default } from './networks-form';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
65
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: export { default } from './networks-list-item';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
66
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: export { default } from './custom-content-search';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
67
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: export { default } from './networks-list';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
68
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: export { default } from './networks-tab-subheader';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
69
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: export { default } from './info-tab.component';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
70
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: export { default } from './experimental-tab.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
71
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: export { default } from './alerts-tab';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
72
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: export { default } from './contact-list-tab.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
73
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: export { default } from './add-contact.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
74
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: export { default } from './view-contact.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
75
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: export { default } from './edit-contact.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
76
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: export { default } from './advanced-tab.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
77
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: import SettingsSearchList from './settings-search-list'; export default SettingsSearchList;
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
78
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: export { default } from './settings-tab.container';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
79
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: import SettingsSearch from './settings-search'; export default SettingsSearch;
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
80
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: import React, { useEffect, useRef, useContext, useState, useCallback, } from 'react'; import { shallowEqual, useDispatch, useSelector } from 'react-redux'; import { Switch, Route, useLocation, useHistory, Redirect, } from 'react-router-dom'; import { shuffle, isEqual } from 'lodash'; import classnames from 'classnames'; import { TransactionStatus } from '@metamask/transaction-controller'; import { I18nContext } from '../../contexts/i18n'; import { getSelectedAccount, getCurrentChainId, getIsSwapsChain, isHardwareWallet, getHardwareWalletType, getTokenList, } from '../../selectors/selectors'; import { getQuotes, clearSwapsState, getTradeTxId, getApproveTxId, getFetchingQuotes, setTopAssets, getFetchParams, setAggregatorMetadata, getAggregatorMetadata, getBackgroundSwapRouteState, getSwapsErrorKey, getSwapsFeatureIsLive, prepareToLeaveSwaps, fetchAndSetSwapsGasPriceInfo, fetchSwapsLivenessAndFeatureFlags, getReviewSwapClickedTimestamp, getPendingSmartTransactions, getSmartTransactionsOptInStatus, getSmartTransactionsEnabled, getCurrentSmartTransactionsEnabled, getCurrentSmartTransactionsError, navigateBackToBuildQuote, getSwapRedesignEnabled, setTransactionSettingsOpened, getLatestAddedTokenTo, } from '../../ducks/swaps/swaps'; import { checkNetworkAndAccountSupports1559, getCurrentNetworkTransactions, } from '../../selectors'; import { AWAITING_SIGNATURES_ROUTE, AWAITING_SWAP_ROUTE, SMART_TRANSACTION_STATUS_ROUTE, BUILD_QUOTE_ROUTE, VIEW_QUOTE_ROUTE, LOADING_QUOTES_ROUTE, SWAPS_ERROR_ROUTE, DEFAULT_ROUTE, SWAPS_MAINTENANCE_ROUTE, PREPARE_SWAP_ROUTE, SWAPS_NOTIFICATION_ROUTE, } from '../../helpers/constants/routes'; import { ERROR_FETCHING_QUOTES, QUOTES_NOT_AVAILABLE_ERROR, SWAP_FAILED_ERROR, CONTRACT_DATA_DISABLED_ERROR, OFFLINE_FOR_MAINTENANCE, } from '../../../shared/constants/swaps'; import { resetBackgroundSwapsState, setSwapsTokens, ignoreTokens, setBackgroundSwapRouteState, setSwapsErrorKey, } from '../../store/actions'; import { useGasFeeEstimates } from '../../hooks/useGasFeeEstimates'; import FeatureToggledRoute from '../../helpers/higher-order-components/feature-toggled-route'; import { MetaMetricsEventCategory } from '../../../shared/constants/metametrics'; import { MetaMetricsContext } from '../../contexts/metametrics'; import { getSwapsTokensReceivedFromTxMeta } from '../../../shared/lib/transactions-controller-utils'; import { Icon, IconName, IconSize } from '../../components/component-library'; import Box from '../../components/ui/box'; import { DISPLAY, JustifyContent, IconColor, FRACTIONS, } from '../../helpers/constants/design-system'; import { fetchTokens, fetchTopAssets, fetchAggregatorMetadata, } from './swaps.util'; import AwaitingSignatures from './awaiting-signatures'; import SmartTransactionStatus from './smart-transaction-status'; import AwaitingSwap from './awaiting-swap'; import LoadingQuote from './loading-swaps-quotes'; import BuildQuote from './build-quote'; import PrepareSwapPage from './prepare-swap-page/prepare-swap-page'; import NotificationPage from './notification-page/notification-page'; import ViewQuote from './view-quote'; export default function Swap() { const t = useContext(I18nContext); const history = useHistory(); const dispatch = useDispatch(); const trackEvent = useContext(MetaMetricsContext); const { pathname } = useLocation(); const isAwaitingSwapRoute = pathname === AWAITING_SWAP_ROUTE; const isAwaitingSignaturesRoute = pathname === AWAITING_SIGNATURES_ROUTE; const isSwapsErrorRoute = pathname === SWAPS_ERROR_ROUTE; const isLoadingQuotesRoute = pathname === LOADING_QUOTES_ROUTE; const isSmartTransactionStatusRoute = pathname === SMART_TRANSACTION_STATUS_ROUTE; const isViewQuoteRoute = pathname === VIEW_QUOTE_ROUTE; const isPrepareSwapRoute = pathname === PREPARE_SWAP_ROUTE; const [currentStxErrorTracked, setCurrentStxErrorTracked] = useState(false); const fetchParams = useSelector(getFetchParams, isEqual); const { destinationTokenInfo = {} } = fetchParams?.metaData || {}; const routeState = useSelector(getBackgroundSwapRouteState); const selectedAccount = useSelector(getSelectedAccount, shallowEqual); const quotes = useSelector(getQuotes, isEqual); const latestAddedTokenTo = useSelector(getLatestAddedTokenTo, isEqual); const txList = useSelector(getCurrentNetworkTransactions, shallowEqual); const tradeTxId = useSelector(getTradeTxId); const approveTxId = useSelector(getApproveTxId); const aggregatorMetadata = useSelector(getAggregatorMetadata, shallowEqual); const fetchingQuotes = useSelector(getFetchingQuotes); let swapsErrorKey = useSelector(getSwapsErrorKey); const swapsEnabled = useSelector(getSwapsFeatureIsLive); const chainId = useSelector(getCurrentChainId); const isSwapsChain = useSelector(getIsSwapsChain); const networkAndAccountSupports1559 = useSelector( checkNetworkAndAccountSupports1559, ); const tokenList = useSelector(getTokenList, isEqual); const shuffledTokensList = shuffle(Object.values(tokenList)); const reviewSwapClickedTimestamp = useSelector(getReviewSwapClickedTimestamp); const pendingSmartTransactions = useSelector(getPendingSmartTransactions); const reviewSwapClicked = Boolean(reviewSwapClickedTimestamp); const smartTransactionsOptInStatus = useSelector( getSmartTransactionsOptInStatus, ); const smartTransactionsEnabled = useSelector(getSmartTransactionsEnabled); const currentSmartTransactionsEnabled = useSelector( getCurrentSmartTransactionsEnabled, ); const swapRedesignEnabled = useSelector(getSwapRedesignEnabled); const currentSmartTransactionsError = useSelector( getCurrentSmartTransactionsError, ); useEffect(() => { const leaveSwaps = async () => { await dispatch(prepareToLeaveSwaps()); // We need to wait until "prepareToLeaveSwaps" is done, because otherwise // a user would be redirected from DEFAULT_ROUTE back to Swaps. history.push(DEFAULT_ROUTE); }; if (!isSwapsChain) { leaveSwaps(); } }, [isSwapsChain, dispatch, history]); // This will pre-load gas fees before going to the View Quote page. useGasFeeEstimates(); const { balance: ethBalance, address: selectedAccountAddress } = selectedAccount; const approveTxData = approveTxId && txList.find(({ id }) => approveTxId === id); const tradeTxData = tradeTxId && txList.find(({ id }) => tradeTxId === id); const tokensReceived = tradeTxData?.txReceipt && getSwapsTokensReceivedFromTxMeta( destinationTokenInfo?.symbol, tradeTxData, destinationTokenInfo?.address, selectedAccountAddress, destinationTokenInfo?.decimals, approveTxData, chainId, ); const tradeConfirmed = tradeTxData?.status === TransactionStatus.confirmed; const approveError = approveTxData?.status === TransactionStatus.failed || approveTxData?.txReceipt?.status === '0x0'; const tradeError = tradeTxData?.status === TransactionStatus.failed || tradeTxData?.txReceipt?.status === '0x0'; const conversionError = approveError || tradeError; if (conversionError && swapsErrorKey !== CONTRACT_DATA_DISABLED_ERROR) { swapsErrorKey = SWAP_FAILED_ERROR; } const clearTemporaryTokenRef = useRef(); useEffect(() => { clearTemporaryTokenRef.current = () => { if (latestAddedTokenTo && (!isAwaitingSwapRoute || conversionError)) { dispatch( ignoreTokens({ tokensToIgnore: latestAddedTokenTo, dontShowLoadingIndicator: true, }), ); } }; }, [ conversionError, dispatch, latestAddedTokenTo, destinationTokenInfo, fetchParams, isAwaitingSwapRoute, ]); useEffect(() => { return () => { clearTemporaryTokenRef.current(); }; }, []); // eslint-disable-next-line useEffect(() => { if (!isSwapsChain) { return undefined; } fetchTokens(chainId) .then((tokens) => { dispatch(setSwapsTokens(tokens)); }) .catch((error) => console.error(error)); fetchTopAssets(chainId).then((topAssets) => { dispatch(setTopAssets(topAssets)); }); fetchAggregatorMetadata(chainId).then((newAggregatorMetadata) => { dispatch(setAggregatorMetadata(newAggregatorMetadata)); }); if (!networkAndAccountSupports1559) { dispatch(fetchAndSetSwapsGasPriceInfo(chainId)); } return () => { dispatch(prepareToLeaveSwaps()); }; }, [dispatch, chainId, networkAndAccountSupports1559, isSwapsChain]); const hardwareWalletUsed = useSelector(isHardwareWallet); const hardwareWalletType = useSelector(getHardwareWalletType); const trackExitedSwapsEvent = () => { trackEvent({ event: 'Exited Swaps', category: MetaMetricsEventCategory.Swaps, sensitiveProperties: { token_from: fetchParams?.sourceTokenInfo?.symbol, token_from_amount: fetchParams?.value, request_type: fetchParams?.balanceError, token_to: fetchParams?.destinationTokenInfo?.symbol, slippage: fetchParams?.slippage, custom_slippage: fetchParams?.slippage !== 2, current_screen: pathname.match(/\/swaps\/(.+)/u)[1], is_hardware_wallet: hardwareWalletUsed, hardware_wallet_type: hardwareWalletType, stx_enabled: smartTransactionsEnabled, current_stx_enabled: currentSmartTransactionsEnabled, stx_user_opt_in: smartTransactionsOptInStatus, }, }); }; const exitEventRef = useRef(); useEffect(() => { exitEventRef.current = () => { trackExitedSwapsEvent(); }; }); useEffect(() => { const fetchSwapsLivenessAndFeatureFlagsWrapper = async () => { await dispatch(fetchSwapsLivenessAndFeatureFlags()); }; fetchSwapsLivenessAndFeatureFlagsWrapper(); return () => { exitEventRef.current(); }; }, [dispatch]); useEffect(() => { // If there is a swapsErrorKey and reviewSwapClicked is false, there was an error in silent quotes prefetching // and we don't want to show the error page in that case, because another API call for quotes can be successful. if (swapsErrorKey && !isSwapsErrorRoute && reviewSwapClicked) { history.push(SWAPS_ERROR_ROUTE); } }, [history, swapsErrorKey, isSwapsErrorRoute, reviewSwapClicked]); const beforeUnloadEventAddedRef = useRef(); useEffect(() => { const fn = () => { clearTemporaryTokenRef.current(); if (isLoadingQuotesRoute) { dispatch(prepareToLeaveSwaps()); } return null; }; if (isLoadingQuotesRoute && !beforeUnloadEventAddedRef.current) { beforeUnloadEventAddedRef.current = true; window.addEventListener('beforeunload', fn); } return () => window.removeEventListener('beforeunload', fn); }, [dispatch, isLoadingQuotesRoute]); const trackErrorStxEvent = useCallback(() => { trackEvent({ event: 'Error Smart Transactions', category: MetaMetricsEventCategory.Swaps, sensitiveProperties: { token_from: fetchParams?.sourceTokenInfo?.symbol, token_from_amount: fetchParams?.value, request_type: fetchParams?.balanceError, token_to: fetchParams?.destinationTokenInfo?.symbol, slippage: fetchParams?.slippage, custom_slippage: fetchParams?.slippage !== 2, current_screen: pathname.match(/\/swaps\/(.+)/u)[1], is_hardware_wallet: hardwareWalletUsed, hardware_wallet_type: hardwareWalletType, stx_enabled: smartTransactionsEnabled, current_stx_enabled: currentSmartTransactionsEnabled, stx_user_opt_in: smartTransactionsOptInStatus, stx_error: currentSmartTransactionsError, }, }); }, [ currentSmartTransactionsError, currentSmartTransactionsEnabled, trackEvent, fetchParams?.balanceError, fetchParams?.destinationTokenInfo?.symbol, fetchParams?.slippage, fetchParams?.sourceTokenInfo?.symbol, fetchParams?.value, hardwareWalletType, hardwareWalletUsed, pathname, smartTransactionsEnabled, smartTransactionsOptInStatus, ]); useEffect(() => { if (currentSmartTransactionsError && !currentStxErrorTracked) { setCurrentStxErrorTracked(true); trackErrorStxEvent(); } }, [ currentSmartTransactionsError, trackErrorStxEvent, currentStxErrorTracked, ]); if (!isSwapsChain) { // A user is being redirected outside of Swaps via the async "leaveSwaps" function above. In the meantime // we have to prevent the code below this condition, which wouldn't work on an unsupported chain. return <></>; } const redirectToDefaultRoute = async () => { clearTemporaryTokenRef.current(); history.push({ pathname: DEFAULT_ROUTE, state: { stayOnHomePage: true }, }); dispatch(clearSwapsState()); await dispatch(resetBackgroundSwapsState()); }; return ( <div className="swaps"> <div className="swaps__container"> <div className="swaps__header"> {!swapRedesignEnabled && ( <div className="swaps__header-edit" onClick={async () => { await dispatch(navigateBackToBuildQuote(history)); }} > {isViewQuoteRoute && t('edit')} </div> )} {swapRedesignEnabled && ( <Box display={DISPLAY.FLEX} justifyContent={JustifyContent.center} marginLeft={4} width={FRACTIONS.ONE_TWELFTH} tabIndex="0" onKeyUp={(e) => { if (e.key === 'Enter') { redirectToDefaultRoute(); } }} > {!isAwaitingSwapRoute && !isAwaitingSignaturesRoute && !isSmartTransactionStatusRoute && ( <Icon name={IconName.Arrow2Left} size={IconSize.Lg} color={IconColor.iconAlternative} onClick={redirectToDefaultRoute} style={{ cursor: 'pointer' }} title={t('cancel')} /> )} </Box> )} <div className="swaps__title">{t('swap')}</div> {!swapRedesignEnabled && ( <div className="swaps__header-cancel" onClick={async () => { clearTemporaryTokenRef.current(); dispatch(clearSwapsState()); await dispatch(resetBackgroundSwapsState()); history.push(DEFAULT_ROUTE); }} > {!isAwaitingSwapRoute && !isAwaitingSignaturesRoute && !isSmartTransactionStatusRoute && t('cancel')} </div> )} {swapRedesignEnabled && ( <Box display={DISPLAY.FLEX} justifyContent={JustifyContent.center} marginRight={4} width={FRACTIONS.ONE_TWELFTH} tabIndex="0" onKeyUp={(e) => { if (e.key === 'Enter') { dispatch(setTransactionSettingsOpened(true)); } }} > {isPrepareSwapRoute && ( <Icon name={IconName.Setting} size={IconSize.Lg} color={IconColor.iconAlternative} onClick={() => { dispatch(setTransactionSettingsOpened(true)); }} style={{ cursor: 'pointer' }} title={t('transactionSettings')} /> )} </Box> )} </div> <div className={classnames('swaps__content', { 'swaps__content--redesign-enabled': swapRedesignEnabled, })} > <Switch> <FeatureToggledRoute redirectRoute={SWAPS_MAINTENANCE_ROUTE} flag={swapsEnabled} path={BUILD_QUOTE_ROUTE} exact render={() => { if (swapRedesignEnabled) { return <Redirect to={{ pathname: PREPARE_SWAP_ROUTE }} />; } if (tradeTxData && !conversionError) { return <Redirect to={{ pathname: AWAITING_SWAP_ROUTE }} />; } else if (tradeTxData && routeState) { return <Redirect to={{ pathname: SWAPS_ERROR_ROUTE }} />; } else if (routeState === 'loading' && aggregatorMetadata) { return <Redirect to={{ pathname: LOADING_QUOTES_ROUTE }} />; } return ( <BuildQuote ethBalance={ethBalance} selectedAccountAddress={selectedAccountAddress} shuffledTokensList={shuffledTokensList} /> ); }} /> <FeatureToggledRoute redirectRoute={SWAPS_MAINTENANCE_ROUTE} flag={swapsEnabled} path={PREPARE_SWAP_ROUTE} exact render={() => { if (!swapRedesignEnabled) { return <Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />; } return ( <PrepareSwapPage ethBalance={ethBalance} selectedAccountAddress={selectedAccountAddress} shuffledTokensList={shuffledTokensList} /> ); }} /> <FeatureToggledRoute redirectRoute={SWAPS_MAINTENANCE_ROUTE} flag={swapsEnabled} path={VIEW_QUOTE_ROUTE} exact render={() => { if ( pendingSmartTransactions.length > 0 && routeState === 'smartTransactionStatus' ) { return ( <Redirect to={{ pathname: SMART_TRANSACTION_STATUS_ROUTE }} /> ); } if (swapRedesignEnabled) { return <Redirect to={{ pathname: PREPARE_SWAP_ROUTE }} />; } if (Object.values(quotes).length) { return ( <ViewQuote numberOfQuotes={Object.values(quotes).length} /> ); } else if (fetchParams) { return <Redirect to={{ pathname: SWAPS_ERROR_ROUTE }} />; } return <Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />; }} /> <Route path={SWAPS_ERROR_ROUTE} exact render={() => { if (swapsErrorKey) { return ( <AwaitingSwap swapComplete={false} errorKey={swapsErrorKey} txHash={tradeTxData?.hash} txId={tradeTxData?.id} submittedTime={tradeTxData?.submittedTime} /> ); } return <Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} />; }} /> <Route path={SWAPS_NOTIFICATION_ROUTE} exact render={() => { if (!swapsErrorKey) { return <Redirect to={{ pathname: PREPARE_SWAP_ROUTE }} />; } return <NotificationPage notificationKey={swapsErrorKey} />; }} /> <FeatureToggledRoute redirectRoute={SWAPS_MAINTENANCE_ROUTE} flag={swapsEnabled} path={LOADING_QUOTES_ROUTE} exact render={() => { return aggregatorMetadata ? ( <LoadingQuote loadingComplete={ !fetchingQuotes && Boolean(Object.values(quotes).length) } onDone={async () => { await dispatch(setBackgroundSwapRouteState('')); if ( swapsErrorKey === ERROR_FETCHING_QUOTES || swapsErrorKey === QUOTES_NOT_AVAILABLE_ERROR ) { dispatch(setSwapsErrorKey(QUOTES_NOT_AVAILABLE_ERROR)); history.push(SWAPS_ERROR_ROUTE); } else { history.push(VIEW_QUOTE_ROUTE); } }} aggregatorMetadata={aggregatorMetadata} /> ) : ( <Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} /> ); }} /> <Route path={SWAPS_MAINTENANCE_ROUTE} exact render={() => { return swapsEnabled === false ? ( <AwaitingSwap errorKey={OFFLINE_FOR_MAINTENANCE} /> ) : ( <Redirect to={{ pathname: BUILD_QUOTE_ROUTE }} /> ); }} /> <Route path={AWAITING_SIGNATURES_ROUTE} exact render={() => { return <AwaitingSignatures />; }} /> <Route path={SMART_TRANSACTION_STATUS_ROUTE} exact render={() => { return <SmartTransactionStatus txId={tradeTxData?.id} />; }} /> <Route path={AWAITING_SWAP_ROUTE} exact render={() => { return routeState === 'awaiting' || tradeTxData ? ( <AwaitingSwap swapComplete={tradeConfirmed} txHash={tradeTxData?.hash} tokensReceived={tokensReceived} txId={tradeTxData?.id} submittingSwap={ routeState === 'awaiting' && !(approveTxId || tradeTxId) } /> ) : ( <Redirect to={{ pathname: DEFAULT_ROUTE }} /> ); }} /> </Switch> </div> </div> </div> ); }
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
81
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: export { default } from './awaiting-signatures';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
82
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: export { default } from './countdown-timer';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
83
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: export { default } from './fee-card';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
84
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: export { default } from './exchange-rate-display';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
85
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: export { default } from './slippage-buttons';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
86
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: export { default } from './view-on-block-explorer';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
87
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: export { default } from './awaiting-swap';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
88
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: export { default } from './searchable-item-list';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
89
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: export { default } from './item-list.component';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
90
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: export { default } from './list-item-search.component';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
91
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: export { default } from './dropdown-input-pair';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
92
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: export { default } from './loading-swaps-quotes';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
93
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: export { default } from './smart-transaction-status';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
94
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: export { default } from './view-quote';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
95
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: export { default } from './build-quote';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
96
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: export { default } from './create-new-swap';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
97
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: export { default } from './main-quote-summary';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
98
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: export { default } from './swaps-footer';
import { setupLocale } from '../shared/lib/error-utils'; const enMessages = { troubleStarting: { message: 'MetaMask had trouble starting. This error could be intermittent, so try restarting the extension.', }, restartMetamask: { message: 'Restart MetaMask', }, stillGettingMessage: { message: 'Still getting this message?', }, sendBugReport: { message: 'Send us a bug report.', }, }; const esMessages = { troubleStarting: { message: 'MetaMask tuvo problemas para iniciarse. Este error podría ser intermitente, así que intente reiniciar la extensión.', }, restartMetamask: { message: 'Reiniciar metamáscara', }, sendBugReport: { message: 'Envíenos un informe de errores.', }, }; jest.mock('../shared/modules/i18n', () => ({ fetchLocale: jest.fn((locale) => (locale === 'en' ? enMessages : esMessages)), loadRelativeTimeFormatLocaleData: jest.fn(), })); describe('Index Tests', () => { it('should get locale messages by calling setupLocale', async () => { let result = await setupLocale('en'); const { currentLocaleMessages: clm, enLocaleMessages: elm } = result; expect(clm).toBeDefined(); expect(elm).toBeDefined(); expect(clm.troubleStarting).toStrictEqual(enMessages.troubleStarting); expect(clm.restartMetamask).toStrictEqual(enMessages.restartMetamask); expect(clm.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm.sendBugReport).toStrictEqual(enMessages.sendBugReport); result = await setupLocale('es'); const { currentLocaleMessages: clm2, enLocaleMessages: elm2 } = result; expect(clm2).toBeDefined(); expect(elm2).toBeDefined(); expect(clm2.troubleStarting).toStrictEqual(esMessages.troubleStarting); expect(clm2.restartMetamask).toStrictEqual(esMessages.restartMetamask); expect(clm2.stillGettingMessage).toBeUndefined(); expect(elm2.stillGettingMessage).toStrictEqual( enMessages.stillGettingMessage, ); expect(clm2.sendBugReport).toStrictEqual(esMessages.sendBugReport); }); });
99