blob: dfda8157b57af4b136c09c776eb5c5cf72ad83bc [file] [log] [blame]
// Copyright 2019 The Fuchsia 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 gotidy_test
import (
"go/format"
"testing"
"fuchsia.googlesource.com/infra/infra/gotidy"
)
func gofmt(t *testing.T, input string) string {
output, err := format.Source([]byte(input))
if err != nil {
t.Errorf("maformed input: %v", err)
}
return string(output)
}
func TestCopyrightHeader(t *testing.T) {
tests := []struct {
name string
input string
step *gotidy.AddCopyrightHeader
expected string
}{
{
name: "should handle unformatted input",
step: &gotidy.AddCopyrightHeader{Year: 2019},
input: `package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
`,
expected: `// Copyright 2019 The Fuchsia 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 "fmt"
func main() {
fmt.Println("Hello, World!")
}
`},
{
name: "should add copyright if missing",
step: &gotidy.AddCopyrightHeader{Year: 2019},
input: gofmt(t, `
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
`),
expected: gofmt(t, `
// Copyright 2019 The Fuchsia 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 "fmt"
func main() {
fmt.Println("Hello, World!")
}
`),
}, {
name: "should not overwrite existing header",
step: &gotidy.AddCopyrightHeader{Year: 2019},
input: gofmt(t, `
// Copyright 2015 The Fuchsia 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 "fmt"
func main() {
fmt.Println("Hello, World!")
}
`),
expected: gofmt(t, `
// Copyright 2015 The Fuchsia 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 "fmt"
func main() {
fmt.Println("Hello, World!")
}
`),
}, {
name: "should preserve package doc comment",
step: &gotidy.AddCopyrightHeader{Year: 2019},
// No space between package decl and header
input: gofmt(t, `
// Package main says hello.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
`),
expected: gofmt(t, `
// Copyright 2019 The Fuchsia 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 says hello.
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
output, err := tt.step.Tidy([]byte(tt.input))
if err != nil {
t.Fatal(err)
}
if string(output) != tt.expected {
t.Errorf("case '%s'\ngot:\n'%s'\nwant:\n'%s'\n", tt.name, output, tt.expected)
}
})
}
}