code.gitea.io/gitea@v1.21.7/build/codeformat/formatimports_test.go (about) 1 // Copyright 2021 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package codeformat 5 6 import ( 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestFormatImportsSimple(t *testing.T) { 13 formatted, err := formatGoImports([]byte(` 14 package codeformat 15 16 import ( 17 "github.com/stretchr/testify/assert" 18 "testing" 19 ) 20 `)) 21 22 expected := ` 23 package codeformat 24 25 import ( 26 "testing" 27 28 "github.com/stretchr/testify/assert" 29 ) 30 ` 31 32 assert.NoError(t, err) 33 assert.Equal(t, expected, string(formatted)) 34 } 35 36 func TestFormatImportsGroup(t *testing.T) { 37 // gofmt/goimports won't group the packages, for example, they produce such code: 38 // "bytes" 39 // "image" 40 // (a blank line) 41 // "fmt" 42 // "image/color/palette" 43 // our formatter does better, and these packages are grouped into one. 44 45 formatted, err := formatGoImports([]byte(` 46 package test 47 48 import ( 49 "bytes" 50 "fmt" 51 "image" 52 "image/color" 53 54 _ "image/gif" // for processing gif images 55 _ "image/jpeg" // for processing jpeg images 56 _ "image/png" // for processing png images 57 58 "code.gitea.io/other/package" 59 60 "code.gitea.io/gitea/modules/setting" 61 "code.gitea.io/gitea/modules/util" 62 63 "xorm.io/the/package" 64 65 "github.com/issue9/identicon" 66 "github.com/nfnt/resize" 67 "github.com/oliamb/cutter" 68 ) 69 `)) 70 71 expected := ` 72 package test 73 74 import ( 75 "bytes" 76 "fmt" 77 "image" 78 "image/color" 79 80 _ "image/gif" // for processing gif images 81 _ "image/jpeg" // for processing jpeg images 82 _ "image/png" // for processing png images 83 84 "code.gitea.io/gitea/modules/setting" 85 "code.gitea.io/gitea/modules/util" 86 87 "code.gitea.io/other/package" 88 "github.com/issue9/identicon" 89 "github.com/nfnt/resize" 90 "github.com/oliamb/cutter" 91 "xorm.io/the/package" 92 ) 93 ` 94 95 assert.NoError(t, err) 96 assert.Equal(t, expected, string(formatted)) 97 } 98 99 func TestFormatImportsInvalidComment(t *testing.T) { 100 // why we shouldn't write comments between imports: it breaks the grouping of imports 101 // for example: 102 // "pkg1" 103 // "pkg2" 104 // // a comment 105 // "pkgA" 106 // "pkgB" 107 // the comment splits the packages into two groups, pkg1/2 are sorted separately, pkgA/B are sorted separately 108 // we don't want such code, so the code should be: 109 // "pkg1" 110 // "pkg2" 111 // "pkgA" // a comment 112 // "pkgB" 113 114 _, err := formatGoImports([]byte(` 115 package test 116 117 import ( 118 "image/jpeg" 119 // for processing gif images 120 "image/gif" 121 ) 122 `)) 123 assert.ErrorIs(t, err, errInvalidCommentBetweenImports) 124 }