tests: Convert from testify to quicktest

This commit is contained in:
Bjørn Erik Pedersen 2019-08-10 21:05:17 +02:00
parent 6027ee1108
commit 9e57182705
No known key found for this signature in database
GPG key ID: 330E6E2BD4859D8F
195 changed files with 3919 additions and 3693 deletions

View file

@ -14,14 +14,18 @@
package bufferpool package bufferpool
import ( import (
"github.com/stretchr/testify/assert"
"testing" "testing"
qt "github.com/frankban/quicktest"
) )
func TestBufferPool(t *testing.T) { func TestBufferPool(t *testing.T) {
c := qt.New(t)
buff := GetBuffer() buff := GetBuffer()
buff.WriteString("do be do be do") buff.WriteString("do be do be do")
assert.Equal(t, "do be do be do", buff.String()) c.Assert(buff.String(), qt.Equals, "do be do be do")
PutBuffer(buff) PutBuffer(buff)
assert.Equal(t, 0, buff.Len())
c.Assert(buff.Len(), qt.Equals, 0)
} }

View file

@ -24,14 +24,14 @@ import (
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
qt "github.com/frankban/quicktest"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestDecodeConfig(t *testing.T) { func TestDecodeConfig(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
configStr := ` configStr := `
resourceDir = "myresources" resourceDir = "myresources"
@ -55,27 +55,27 @@ dir = "/path/to/c3"
` `
cfg, err := config.FromConfigString(configStr, "toml") cfg, err := config.FromConfigString(configStr, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
decoded, err := DecodeConfig(fs, cfg) decoded, err := DecodeConfig(fs, cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(5, len(decoded)) c.Assert(len(decoded), qt.Equals, 5)
c2 := decoded["getcsv"] c2 := decoded["getcsv"]
assert.Equal("11h0m0s", c2.MaxAge.String()) c.Assert(c2.MaxAge.String(), qt.Equals, "11h0m0s")
assert.Equal(filepath.FromSlash("/path/to/c2/filecache/getcsv"), c2.Dir) c.Assert(c2.Dir, qt.Equals, filepath.FromSlash("/path/to/c2/filecache/getcsv"))
c3 := decoded["images"] c3 := decoded["images"]
assert.Equal(time.Duration(-1), c3.MaxAge) c.Assert(c3.MaxAge, qt.Equals, time.Duration(-1))
assert.Equal(filepath.FromSlash("/path/to/c3/filecache/images"), c3.Dir) c.Assert(c3.Dir, qt.Equals, filepath.FromSlash("/path/to/c3/filecache/images"))
} }
func TestDecodeConfigIgnoreCache(t *testing.T) { func TestDecodeConfigIgnoreCache(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
configStr := ` configStr := `
resourceDir = "myresources" resourceDir = "myresources"
@ -100,21 +100,21 @@ dir = "/path/to/c3"
` `
cfg, err := config.FromConfigString(configStr, "toml") cfg, err := config.FromConfigString(configStr, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
decoded, err := DecodeConfig(fs, cfg) decoded, err := DecodeConfig(fs, cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(5, len(decoded)) c.Assert(len(decoded), qt.Equals, 5)
for _, v := range decoded { for _, v := range decoded {
assert.Equal(time.Duration(0), v.MaxAge) c.Assert(v.MaxAge, qt.Equals, time.Duration(0))
} }
} }
func TestDecodeConfigDefault(t *testing.T) { func TestDecodeConfigDefault(t *testing.T) {
assert := require.New(t) c := qt.New(t)
cfg := newTestConfig() cfg := newTestConfig()
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
@ -130,28 +130,28 @@ func TestDecodeConfigDefault(t *testing.T) {
decoded, err := DecodeConfig(fs, cfg) decoded, err := DecodeConfig(fs, cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(5, len(decoded)) c.Assert(len(decoded), qt.Equals, 5)
imgConfig := decoded[cacheKeyImages] imgConfig := decoded[cacheKeyImages]
jsonConfig := decoded[cacheKeyGetJSON] jsonConfig := decoded[cacheKeyGetJSON]
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
assert.Equal(filepath.FromSlash("_gen/images"), imgConfig.Dir) c.Assert(imgConfig.Dir, qt.Equals, filepath.FromSlash("_gen/images"))
} else { } else {
assert.Equal("_gen/images", imgConfig.Dir) c.Assert(imgConfig.Dir, qt.Equals, "_gen/images")
assert.Equal("/cache/thecache/hugoproject/filecache/getjson", jsonConfig.Dir) c.Assert(jsonConfig.Dir, qt.Equals, "/cache/thecache/hugoproject/filecache/getjson")
} }
assert.True(imgConfig.isResourceDir) c.Assert(imgConfig.isResourceDir, qt.Equals, true)
assert.False(jsonConfig.isResourceDir) c.Assert(jsonConfig.isResourceDir, qt.Equals, false)
} }
func TestDecodeConfigInvalidDir(t *testing.T) { func TestDecodeConfigInvalidDir(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
configStr := ` configStr := `
resourceDir = "myresources" resourceDir = "myresources"
@ -173,11 +173,11 @@ dir = "/"
} }
cfg, err := config.FromConfigString(configStr, "toml") cfg, err := config.FromConfigString(configStr, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
_, err = DecodeConfig(fs, cfg) _, err = DecodeConfig(fs, cfg)
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
} }

View file

@ -20,13 +20,13 @@ import (
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestPrune(t *testing.T) { func TestPrune(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
configStr := ` configStr := `
resourceDir = "myresources" resourceDir = "myresources"
@ -53,10 +53,10 @@ dir = ":resourceDir/_gen"
` `
for _, name := range []string{cacheKeyGetCSV, cacheKeyGetJSON, cacheKeyAssets, cacheKeyImages} { for _, name := range []string{cacheKeyGetCSV, cacheKeyGetJSON, cacheKeyAssets, cacheKeyImages} {
msg := fmt.Sprintf("cache: %s", name) msg := qt.Commentf("cache: %s", name)
p := newPathsSpec(t, afero.NewMemMapFs(), configStr) p := newPathsSpec(t, afero.NewMemMapFs(), configStr)
caches, err := NewCaches(p) caches, err := NewCaches(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
cache := caches[name] cache := caches[name]
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
id := fmt.Sprintf("i%d", i) id := fmt.Sprintf("i%d", i)
@ -70,21 +70,21 @@ dir = ":resourceDir/_gen"
} }
count, err := caches.Prune() count, err := caches.Prune()
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(5, count, msg) c.Assert(count, qt.Equals, 5, msg)
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
id := fmt.Sprintf("i%d", i) id := fmt.Sprintf("i%d", i)
v := cache.getString(id) v := cache.getString(id)
if i < 5 { if i < 5 {
assert.Equal("", v, id) c.Assert(v, qt.Equals, "")
} else { } else {
assert.Equal("abc", v, id) c.Assert(v, qt.Equals, "abc")
} }
} }
caches, err = NewCaches(p) caches, err = NewCaches(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
cache = caches[name] cache = caches[name]
// Touch one and then prune. // Touch one and then prune.
cache.GetOrCreateBytes("i5", func() ([]byte, error) { cache.GetOrCreateBytes("i5", func() ([]byte, error) {
@ -92,17 +92,17 @@ dir = ":resourceDir/_gen"
}) })
count, err = caches.Prune() count, err = caches.Prune()
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(4, count) c.Assert(count, qt.Equals, 4)
// Now only the i5 should be left. // Now only the i5 should be left.
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
id := fmt.Sprintf("i%d", i) id := fmt.Sprintf("i%d", i)
v := cache.getString(id) v := cache.getString(id)
if i != 5 { if i != 5 {
assert.Equal("", v, id) c.Assert(v, qt.Equals, "")
} else { } else {
assert.Equal("abc", v, id) c.Assert(v, qt.Equals, "abc")
} }
} }

View file

@ -19,7 +19,6 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp"
"strings" "strings"
"sync" "sync"
"testing" "testing"
@ -35,19 +34,19 @@ import (
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestFileCache(t *testing.T) { func TestFileCache(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
tempWorkingDir, err := ioutil.TempDir("", "hugo_filecache_test_work") tempWorkingDir, err := ioutil.TempDir("", "hugo_filecache_test_work")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer os.Remove(tempWorkingDir) defer os.Remove(tempWorkingDir)
tempCacheDir, err := ioutil.TempDir("", "hugo_filecache_test_cache") tempCacheDir, err := ioutil.TempDir("", "hugo_filecache_test_cache")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer os.Remove(tempCacheDir) defer os.Remove(tempCacheDir)
osfs := afero.NewOsFs() osfs := afero.NewOsFs()
@ -89,30 +88,30 @@ dir = ":cacheDir/c"
p := newPathsSpec(t, osfs, configStr) p := newPathsSpec(t, osfs, configStr)
caches, err := NewCaches(p) caches, err := NewCaches(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
cache := caches.Get("GetJSON") cache := caches.Get("GetJSON")
assert.NotNil(cache) c.Assert(cache, qt.Not(qt.IsNil))
assert.Equal("10h0m0s", cache.maxAge.String()) c.Assert(cache.maxAge.String(), qt.Equals, "10h0m0s")
bfs, ok := cache.Fs.(*afero.BasePathFs) bfs, ok := cache.Fs.(*afero.BasePathFs)
assert.True(ok) c.Assert(ok, qt.Equals, true)
filename, err := bfs.RealPath("key") filename, err := bfs.RealPath("key")
assert.NoError(err) c.Assert(err, qt.IsNil)
if test.cacheDir != "" { if test.cacheDir != "" {
assert.Equal(filepath.Join(test.cacheDir, "c/"+filecacheRootDirname+"/getjson/key"), filename) c.Assert(filename, qt.Equals, filepath.Join(test.cacheDir, "c/"+filecacheRootDirname+"/getjson/key"))
} else { } else {
// Temp dir. // Temp dir.
assert.Regexp(regexp.MustCompile(".*hugo_cache.*"+filecacheRootDirname+".*key"), filename) c.Assert(filename, qt.Matches, ".*hugo_cache.*"+filecacheRootDirname+".*key")
} }
cache = caches.Get("Images") cache = caches.Get("Images")
assert.NotNil(cache) c.Assert(cache, qt.Not(qt.IsNil))
assert.Equal(time.Duration(-1), cache.maxAge) c.Assert(cache.maxAge, qt.Equals, time.Duration(-1))
bfs, ok = cache.Fs.(*afero.BasePathFs) bfs, ok = cache.Fs.(*afero.BasePathFs)
assert.True(ok) c.Assert(ok, qt.Equals, true)
filename, _ = bfs.RealPath("key") filename, _ = bfs.RealPath("key")
assert.Equal(filepath.FromSlash("_gen/images/key"), filename) c.Assert(filename, qt.Equals, filepath.FromSlash("_gen/images/key"))
rf := func(s string) func() (io.ReadCloser, error) { rf := func(s string) func() (io.ReadCloser, error) {
return func() (io.ReadCloser, error) { return func() (io.ReadCloser, error) {
@ -130,55 +129,55 @@ dir = ":cacheDir/c"
return []byte("bcd"), nil return []byte("bcd"), nil
} }
for _, c := range []*Cache{caches.ImageCache(), caches.AssetsCache(), caches.GetJSONCache(), caches.GetCSVCache()} { for _, ca := range []*Cache{caches.ImageCache(), caches.AssetsCache(), caches.GetJSONCache(), caches.GetCSVCache()} {
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
info, r, err := c.GetOrCreate("a", rf("abc")) info, r, err := ca.GetOrCreate("a", rf("abc"))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(r) c.Assert(r, qt.Not(qt.IsNil))
assert.Equal("a", info.Name) c.Assert(info.Name, qt.Equals, "a")
b, _ := ioutil.ReadAll(r) b, _ := ioutil.ReadAll(r)
r.Close() r.Close()
assert.Equal("abc", string(b)) c.Assert(string(b), qt.Equals, "abc")
info, b, err = c.GetOrCreateBytes("b", bf) info, b, err = ca.GetOrCreateBytes("b", bf)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(r) c.Assert(r, qt.Not(qt.IsNil))
assert.Equal("b", info.Name) c.Assert(info.Name, qt.Equals, "b")
assert.Equal("bcd", string(b)) c.Assert(string(b), qt.Equals, "bcd")
_, b, err = c.GetOrCreateBytes("a", bf) _, b, err = ca.GetOrCreateBytes("a", bf)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("abc", string(b)) c.Assert(string(b), qt.Equals, "abc")
_, r, err = c.GetOrCreate("a", rf("bcd")) _, r, err = ca.GetOrCreate("a", rf("bcd"))
assert.NoError(err) c.Assert(err, qt.IsNil)
b, _ = ioutil.ReadAll(r) b, _ = ioutil.ReadAll(r)
r.Close() r.Close()
assert.Equal("abc", string(b)) c.Assert(string(b), qt.Equals, "abc")
} }
} }
assert.NotNil(caches.Get("getJSON")) c.Assert(caches.Get("getJSON"), qt.Not(qt.IsNil))
info, w, err := caches.ImageCache().WriteCloser("mykey") info, w, err := caches.ImageCache().WriteCloser("mykey")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("mykey", info.Name) c.Assert(info.Name, qt.Equals, "mykey")
io.WriteString(w, "Hugo is great!") io.WriteString(w, "Hugo is great!")
w.Close() w.Close()
assert.Equal("Hugo is great!", caches.ImageCache().getString("mykey")) c.Assert(caches.ImageCache().getString("mykey"), qt.Equals, "Hugo is great!")
info, r, err := caches.ImageCache().Get("mykey") info, r, err := caches.ImageCache().Get("mykey")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(r) c.Assert(r, qt.Not(qt.IsNil))
assert.Equal("mykey", info.Name) c.Assert(info.Name, qt.Equals, "mykey")
b, _ := ioutil.ReadAll(r) b, _ := ioutil.ReadAll(r)
r.Close() r.Close()
assert.Equal("Hugo is great!", string(b)) c.Assert(string(b), qt.Equals, "Hugo is great!")
info, b, err = caches.ImageCache().GetBytes("mykey") info, b, err = caches.ImageCache().GetBytes("mykey")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("mykey", info.Name) c.Assert(info.Name, qt.Equals, "mykey")
assert.Equal("Hugo is great!", string(b)) c.Assert(string(b), qt.Equals, "Hugo is great!")
} }
@ -187,7 +186,7 @@ dir = ":cacheDir/c"
func TestFileCacheConcurrent(t *testing.T) { func TestFileCacheConcurrent(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
configStr := ` configStr := `
resourceDir = "myresources" resourceDir = "myresources"
@ -208,7 +207,7 @@ dir = "/cache/c"
p := newPathsSpec(t, afero.NewMemMapFs(), configStr) p := newPathsSpec(t, afero.NewMemMapFs(), configStr)
caches, err := NewCaches(p) caches, err := NewCaches(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
const cacheName = "getjson" const cacheName = "getjson"
@ -225,16 +224,16 @@ dir = "/cache/c"
go func(i int) { go func(i int) {
defer wg.Done() defer wg.Done()
for j := 0; j < 20; j++ { for j := 0; j < 20; j++ {
c := caches.Get(cacheName) ca := caches.Get(cacheName)
assert.NotNil(c) c.Assert(ca, qt.Not(qt.IsNil))
filename, data := filenameData(i) filename, data := filenameData(i)
_, r, err := c.GetOrCreate(filename, func() (io.ReadCloser, error) { _, r, err := ca.GetOrCreate(filename, func() (io.ReadCloser, error) {
return hugio.ToReadCloser(strings.NewReader(data)), nil return hugio.ToReadCloser(strings.NewReader(data)), nil
}) })
assert.NoError(err) c.Assert(err, qt.IsNil)
b, _ := ioutil.ReadAll(r) b, _ := ioutil.ReadAll(r)
r.Close() r.Close()
assert.Equal(data, string(b)) c.Assert(string(b), qt.Equals, data)
// Trigger some expiration. // Trigger some expiration.
time.Sleep(50 * time.Millisecond) time.Sleep(50 * time.Millisecond)
} }
@ -245,9 +244,9 @@ dir = "/cache/c"
} }
func TestCleanID(t *testing.T) { func TestCleanID(t *testing.T) {
assert := require.New(t) c := qt.New(t)
assert.Equal(filepath.FromSlash("a/b/c.txt"), cleanID(filepath.FromSlash("/a/b//c.txt"))) c.Assert(cleanID(filepath.FromSlash("/a/b//c.txt")), qt.Equals, filepath.FromSlash("a/b/c.txt"))
assert.Equal(filepath.FromSlash("a/b/c.txt"), cleanID(filepath.FromSlash("a/b//c.txt"))) c.Assert(cleanID(filepath.FromSlash("a/b//c.txt")), qt.Equals, filepath.FromSlash("a/b/c.txt"))
} }
func initConfig(fs afero.Fs, cfg config.Provider) error { func initConfig(fs afero.Fs, cfg config.Provider) error {
@ -288,12 +287,12 @@ func initConfig(fs afero.Fs, cfg config.Provider) error {
} }
func newPathsSpec(t *testing.T, fs afero.Fs, configStr string) *helpers.PathSpec { func newPathsSpec(t *testing.T, fs afero.Fs, configStr string) *helpers.PathSpec {
assert := require.New(t) c := qt.New(t)
cfg, err := config.FromConfigString(configStr, "toml") cfg, err := config.FromConfigString(configStr, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
initConfig(fs, cfg) initConfig(fs, cfg)
p, err := helpers.NewPathSpec(hugofs.NewFrom(fs, cfg), cfg, nil) p, err := helpers.NewPathSpec(hugofs.NewFrom(fs, cfg), cfg, nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
return p return p
} }

View file

@ -18,12 +18,12 @@ import (
"sync" "sync"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestNamedCache(t *testing.T) { func TestNamedCache(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
cache := New() cache := New()
@ -35,24 +35,24 @@ func TestNamedCache(t *testing.T) {
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {
v1, err := cache.GetOrCreate("a1", create) v1, err := cache.GetOrCreate("a1", create)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(1, v1) c.Assert(v1, qt.Equals, 1)
v2, err := cache.GetOrCreate("a2", create) v2, err := cache.GetOrCreate("a2", create)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(2, v2) c.Assert(v2, qt.Equals, 2)
} }
cache.Clear() cache.Clear()
v3, err := cache.GetOrCreate("a2", create) v3, err := cache.GetOrCreate("a2", create)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(3, v3) c.Assert(v3, qt.Equals, 3)
} }
func TestNamedCacheConcurrent(t *testing.T) { func TestNamedCacheConcurrent(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
var wg sync.WaitGroup var wg sync.WaitGroup
@ -71,8 +71,8 @@ func TestNamedCacheConcurrent(t *testing.T) {
for j := 0; j < 100; j++ { for j := 0; j < 100; j++ {
id := fmt.Sprintf("id%d", j) id := fmt.Sprintf("id%d", j)
v, err := cache.GetOrCreate(id, create(j)) v, err := cache.GetOrCreate(id, create(j))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(j, v) c.Assert(v, qt.Equals, j)
} }
}() }()
} }

View file

@ -18,13 +18,13 @@ import (
"sync" "sync"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestNewPartitionedLazyCache(t *testing.T) { func TestNewPartitionedLazyCache(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
p1 := Partition{ p1 := Partition{
Key: "p1", Key: "p1",
@ -51,28 +51,28 @@ func TestNewPartitionedLazyCache(t *testing.T) {
cache := NewPartitionedLazyCache(p1, p2) cache := NewPartitionedLazyCache(p1, p2)
v, err := cache.Get("p1", "p1_1") v, err := cache.Get("p1", "p1_1")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("p1v1", v) c.Assert(v, qt.Equals, "p1v1")
v, err = cache.Get("p1", "p2_1") v, err = cache.Get("p1", "p2_1")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Nil(v) c.Assert(v, qt.IsNil)
v, err = cache.Get("p1", "p1_nil") v, err = cache.Get("p1", "p1_nil")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Nil(v) c.Assert(v, qt.IsNil)
v, err = cache.Get("p2", "p2_3") v, err = cache.Get("p2", "p2_3")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("p2v3", v) c.Assert(v, qt.Equals, "p2v3")
v, err = cache.Get("doesnotexist", "p1_1") v, err = cache.Get("doesnotexist", "p1_1")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Nil(v) c.Assert(v, qt.IsNil)
v, err = cache.Get("p1", "doesnotexist") v, err = cache.Get("p1", "doesnotexist")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Nil(v) c.Assert(v, qt.IsNil)
errorP := Partition{ errorP := Partition{
Key: "p3", Key: "p3",
@ -84,18 +84,18 @@ func TestNewPartitionedLazyCache(t *testing.T) {
cache = NewPartitionedLazyCache(errorP) cache = NewPartitionedLazyCache(errorP)
v, err = cache.Get("p1", "doesnotexist") v, err = cache.Get("p1", "doesnotexist")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Nil(v) c.Assert(v, qt.IsNil)
_, err = cache.Get("p3", "doesnotexist") _, err = cache.Get("p3", "doesnotexist")
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
} }
func TestConcurrentPartitionedLazyCache(t *testing.T) { func TestConcurrentPartitionedLazyCache(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
var wg sync.WaitGroup var wg sync.WaitGroup
@ -129,8 +129,8 @@ func TestConcurrentPartitionedLazyCache(t *testing.T) {
defer wg.Done() defer wg.Done()
for j := 0; j < 10; j++ { for j := 0; j < 10; j++ {
v, err := cache.Get("p1", "p1_1") v, err := cache.Get("p1", "p1_1")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("p1v1", v) c.Assert(v, qt.Equals, "p1v1")
} }
}() }()
} }

View file

@ -20,8 +20,8 @@ import (
"reflect" "reflect"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/herrors"
"github.com/stretchr/testify/require"
) )
func TestMethods(t *testing.T) { func TestMethods(t *testing.T) {
@ -33,47 +33,47 @@ func TestMethods(t *testing.T) {
) )
dir, _ := os.Getwd() dir, _ := os.Getwd()
c := NewInspector(dir) insp := NewInspector(dir)
t.Run("MethodsFromTypes", func(t *testing.T) { t.Run("MethodsFromTypes", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
methods := c.MethodsFromTypes([]reflect.Type{zeroI}, nil) methods := insp.MethodsFromTypes([]reflect.Type{zeroI}, nil)
methodsStr := fmt.Sprint(methods) methodsStr := fmt.Sprint(methods)
assert.Contains(methodsStr, "Method1(arg0 herrors.ErrorContext)") c.Assert(methodsStr, qt.Contains, "Method1(arg0 herrors.ErrorContext)")
assert.Contains(methodsStr, "Method7() interface {}") c.Assert(methodsStr, qt.Contains, "Method7() interface {}")
assert.Contains(methodsStr, "Method0() string\n Method4() string") c.Assert(methodsStr, qt.Contains, "Method0() string\n Method4() string")
assert.Contains(methodsStr, "MethodEmbed3(arg0 string) string\n MethodEmbed1() string") c.Assert(methodsStr, qt.Contains, "MethodEmbed3(arg0 string) string\n MethodEmbed1() string")
assert.Contains(methods.Imports(), "github.com/gohugoio/hugo/common/herrors") c.Assert(methods.Imports(), qt.Contains, "github.com/gohugoio/hugo/common/herrors")
}) })
t.Run("EmbedOnly", func(t *testing.T) { t.Run("EmbedOnly", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
methods := c.MethodsFromTypes([]reflect.Type{zeroIEOnly}, nil) methods := insp.MethodsFromTypes([]reflect.Type{zeroIEOnly}, nil)
methodsStr := fmt.Sprint(methods) methodsStr := fmt.Sprint(methods)
assert.Contains(methodsStr, "MethodEmbed3(arg0 string) string") c.Assert(methodsStr, qt.Contains, "MethodEmbed3(arg0 string) string")
}) })
t.Run("ToMarshalJSON", func(t *testing.T) { t.Run("ToMarshalJSON", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
m, pkg := c.MethodsFromTypes( m, pkg := insp.MethodsFromTypes(
[]reflect.Type{zeroI}, []reflect.Type{zeroI},
[]reflect.Type{zeroIE}).ToMarshalJSON("*page", "page") []reflect.Type{zeroIE}).ToMarshalJSON("*page", "page")
assert.Contains(m, "method6 := p.Method6()") c.Assert(m, qt.Contains, "method6 := p.Method6()")
assert.Contains(m, "Method0: method0,") c.Assert(m, qt.Contains, "Method0: method0,")
assert.Contains(m, "return json.Marshal(&s)") c.Assert(m, qt.Contains, "return json.Marshal(&s)")
assert.Contains(pkg, "github.com/gohugoio/hugo/common/herrors") c.Assert(pkg, qt.Contains, "github.com/gohugoio/hugo/common/herrors")
assert.Contains(pkg, "encoding/json") c.Assert(pkg, qt.Contains, "encoding/json")
fmt.Println(pkg) fmt.Println(pkg)

View file

@ -25,29 +25,29 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestExecute(t *testing.T) { func TestExecute(t *testing.T) {
assert := require.New(t) c := qt.New(t)
dir, err := createSimpleTestSite(t, testSiteConfig{}) dir, err := createSimpleTestSite(t, testSiteConfig{})
assert.NoError(err) c.Assert(err, qt.IsNil)
defer func() { defer func() {
os.RemoveAll(dir) os.RemoveAll(dir)
}() }()
resp := Execute([]string{"-s=" + dir}) resp := Execute([]string{"-s=" + dir})
assert.NoError(resp.Err) c.Assert(resp.Err, qt.IsNil)
result := resp.Result result := resp.Result
assert.True(len(result.Sites) == 1) c.Assert(len(result.Sites) == 1, qt.Equals, true)
assert.True(len(result.Sites[0].RegularPages()) == 1) c.Assert(len(result.Sites[0].RegularPages()) == 1, qt.Equals, true)
} }
func TestCommandsPersistentFlags(t *testing.T) { func TestCommandsPersistentFlags(t *testing.T) {
assert := require.New(t) c := qt.New(t)
noOpRunE := func(cmd *cobra.Command, args []string) error { noOpRunE := func(cmd *cobra.Command, args []string) error {
return nil return nil
@ -83,10 +83,10 @@ func TestCommandsPersistentFlags(t *testing.T) {
for _, command := range commands { for _, command := range commands {
if b, ok := command.(commandsBuilderGetter); ok { if b, ok := command.(commandsBuilderGetter); ok {
v := b.getCommandsBuilder().hugoBuilderCommon v := b.getCommandsBuilder().hugoBuilderCommon
assert.Equal("myconfig.toml", v.cfgFile) c.Assert(v.cfgFile, qt.Equals, "myconfig.toml")
assert.Equal("myconfigdir", v.cfgDir) c.Assert(v.cfgDir, qt.Equals, "myconfigdir")
assert.Equal("mysource", v.source) c.Assert(v.source, qt.Equals, "mysource")
assert.Equal("https://example.com/b/", v.baseURL) c.Assert(v.baseURL, qt.Equals, "https://example.com/b/")
} }
if srvCmd, ok := command.(*serverCmd); ok { if srvCmd, ok := command.(*serverCmd); ok {
@ -94,32 +94,32 @@ func TestCommandsPersistentFlags(t *testing.T) {
} }
} }
assert.NotNil(sc) c.Assert(sc, qt.Not(qt.IsNil))
assert.True(sc.navigateToChanged) c.Assert(sc.navigateToChanged, qt.Equals, true)
assert.True(sc.disableLiveReload) c.Assert(sc.disableLiveReload, qt.Equals, true)
assert.True(sc.noHTTPCache) c.Assert(sc.noHTTPCache, qt.Equals, true)
assert.True(sc.renderToDisk) c.Assert(sc.renderToDisk, qt.Equals, true)
assert.Equal(1366, sc.serverPort) c.Assert(sc.serverPort, qt.Equals, 1366)
assert.Equal("testing", sc.environment) c.Assert(sc.environment, qt.Equals, "testing")
cfg := viper.New() cfg := viper.New()
sc.flagsToConfig(cfg) sc.flagsToConfig(cfg)
assert.Equal("/tmp/mydestination", cfg.GetString("publishDir")) c.Assert(cfg.GetString("publishDir"), qt.Equals, "/tmp/mydestination")
assert.Equal("mycontent", cfg.GetString("contentDir")) c.Assert(cfg.GetString("contentDir"), qt.Equals, "mycontent")
assert.Equal("mylayouts", cfg.GetString("layoutDir")) c.Assert(cfg.GetString("layoutDir"), qt.Equals, "mylayouts")
assert.Equal([]string{"mytheme"}, cfg.GetStringSlice("theme")) c.Assert(cfg.GetStringSlice("theme"), qt.DeepEquals, []string{"mytheme"})
assert.Equal("mythemes", cfg.GetString("themesDir")) c.Assert(cfg.GetString("themesDir"), qt.Equals, "mythemes")
assert.Equal("https://example.com/b/", cfg.GetString("baseURL")) c.Assert(cfg.GetString("baseURL"), qt.Equals, "https://example.com/b/")
assert.Equal([]string{"page", "home"}, cfg.Get("disableKinds")) c.Assert(cfg.Get("disableKinds"), qt.DeepEquals, []string{"page", "home"})
assert.True(cfg.GetBool("gc")) c.Assert(cfg.GetBool("gc"), qt.Equals, true)
// The flag is named path-warnings // The flag is named path-warnings
assert.True(cfg.GetBool("logPathWarnings")) c.Assert(cfg.GetBool("logPathWarnings"), qt.Equals, true)
// The flag is named i18n-warnings // The flag is named i18n-warnings
assert.True(cfg.GetBool("logI18nWarnings")) c.Assert(cfg.GetBool("logI18nWarnings"), qt.Equals, true)
}}} }}}
@ -136,7 +136,7 @@ func TestCommandsPersistentFlags(t *testing.T) {
} }
rootCmd := root.getCommand() rootCmd := root.getCommand()
rootCmd.SetArgs(test.args) rootCmd.SetArgs(test.args)
assert.NoError(rootCmd.Execute()) c.Assert(rootCmd.Execute(), qt.IsNil)
test.check(b.commands) test.check(b.commands)
} }
@ -144,13 +144,13 @@ func TestCommandsPersistentFlags(t *testing.T) {
func TestCommandsExecute(t *testing.T) { func TestCommandsExecute(t *testing.T) {
assert := require.New(t) c := qt.New(t)
dir, err := createSimpleTestSite(t, testSiteConfig{}) dir, err := createSimpleTestSite(t, testSiteConfig{})
assert.NoError(err) c.Assert(err, qt.IsNil)
dirOut, err := ioutil.TempDir("", "hugo-cli-out") dirOut, err := ioutil.TempDir("", "hugo-cli-out")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer func() { defer func() {
os.RemoveAll(dir) os.RemoveAll(dir)
@ -200,17 +200,17 @@ func TestCommandsExecute(t *testing.T) {
_, err := hugoCmd.ExecuteC() _, err := hugoCmd.ExecuteC()
if test.expectErrToContain != "" { if test.expectErrToContain != "" {
assert.Error(err, fmt.Sprintf("%v", test.commands)) c.Assert(err, qt.Not(qt.IsNil))
assert.Contains(err.Error(), test.expectErrToContain) c.Assert(err.Error(), qt.Contains, test.expectErrToContain)
} else { } else {
assert.NoError(err, fmt.Sprintf("%v", test.commands)) c.Assert(err, qt.IsNil)
} }
// Assert that we have not left any development debug artifacts in // Assert that we have not left any development debug artifacts in
// the code. // the code.
if b.c != nil { if b.c != nil {
_, ok := b.c.destinationFs.(types.DevMarker) _, ok := b.c.destinationFs.(types.DevMarker)
assert.False(ok) c.Assert(ok, qt.Equals, false)
} }
} }

View file

@ -17,12 +17,12 @@ import (
"os" "os"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
// Issue #5662 // Issue #5662
func TestHugoWithContentDirOverride(t *testing.T) { func TestHugoWithContentDirOverride(t *testing.T) {
assert := require.New(t) c := qt.New(t)
hugoCmd := newCommandsBuilder().addAll().build() hugoCmd := newCommandsBuilder().addAll().build()
cmd := hugoCmd.getCommand() cmd := hugoCmd.getCommand()
@ -38,7 +38,7 @@ contentDir = "thisdoesnotexist"
` `
dir, err := createSimpleTestSite(t, testSiteConfig{configTOML: cfgStr, contentDir: contentDir}) dir, err := createSimpleTestSite(t, testSiteConfig{configTOML: cfgStr, contentDir: contentDir})
assert.NoError(err) c.Assert(err, qt.IsNil)
defer func() { defer func() {
os.RemoveAll(dir) os.RemoveAll(dir)
@ -47,6 +47,6 @@ contentDir = "thisdoesnotexist"
cmd.SetArgs([]string{"-s=" + dir, "-c=" + contentDir}) cmd.SetArgs([]string{"-s=" + dir, "-c=" + contentDir})
_, err = cmd.ExecuteC() _, err = cmd.ExecuteC()
assert.NoError(err) c.Assert(err, qt.IsNil)
} }

View file

@ -15,12 +15,14 @@ package commands
import ( import (
"encoding/json" "encoding/json"
"github.com/stretchr/testify/assert"
"testing" "testing"
"time" "time"
qt "github.com/frankban/quicktest"
) )
func TestParseJekyllFilename(t *testing.T) { func TestParseJekyllFilename(t *testing.T) {
c := qt.New(t)
filenameArray := []string{ filenameArray := []string{
"2015-01-02-test.md", "2015-01-02-test.md",
"2012-03-15-中文.markup", "2012-03-15-中文.markup",
@ -36,13 +38,14 @@ func TestParseJekyllFilename(t *testing.T) {
for i, filename := range filenameArray { for i, filename := range filenameArray {
postDate, postName, err := parseJekyllFilename(filename) postDate, postName, err := parseJekyllFilename(filename)
assert.Equal(t, err, nil) c.Assert(err, qt.IsNil)
assert.Equal(t, expectResult[i].postDate.Format("2006-01-02"), postDate.Format("2006-01-02")) c.Assert(expectResult[i].postDate.Format("2006-01-02"), qt.Equals, postDate.Format("2006-01-02"))
assert.Equal(t, expectResult[i].postName, postName) c.Assert(expectResult[i].postName, qt.Equals, postName)
} }
} }
func TestConvertJekyllMetadata(t *testing.T) { func TestConvertJekyllMetadata(t *testing.T) {
c := qt.New(t)
testDataList := []struct { testDataList := []struct {
metadata interface{} metadata interface{}
postName string postName string
@ -73,14 +76,15 @@ func TestConvertJekyllMetadata(t *testing.T) {
for _, data := range testDataList { for _, data := range testDataList {
result, err := convertJekyllMetaData(data.metadata, data.postName, data.postDate, data.draft) result, err := convertJekyllMetaData(data.metadata, data.postName, data.postDate, data.draft)
assert.Equal(t, nil, err) c.Assert(err, qt.IsNil)
jsonResult, err := json.Marshal(result) jsonResult, err := json.Marshal(result)
assert.Equal(t, nil, err) c.Assert(err, qt.IsNil)
assert.Equal(t, data.expect, string(jsonResult)) c.Assert(string(jsonResult), qt.Equals, data.expect)
} }
} }
func TestConvertJekyllContent(t *testing.T) { func TestConvertJekyllContent(t *testing.T) {
c := qt.New(t)
testDataList := []struct { testDataList := []struct {
metadata interface{} metadata interface{}
content string content string
@ -124,6 +128,6 @@ func TestConvertJekyllContent(t *testing.T) {
for _, data := range testDataList { for _, data := range testDataList {
result := convertJekyllContent(data.metadata, data.content) result := convertJekyllContent(data.metadata, data.content)
assert.Equal(t, data.expect, result) c.Assert(data.expect, qt.Equals, result)
} }
} }

View file

@ -9,8 +9,8 @@ import (
"strings" "strings"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/stretchr/testify/require"
) )
func captureStdout(f func() (*cobra.Command, error)) (string, error) { func captureStdout(f func() (*cobra.Command, error)) (string, error) {
@ -33,10 +33,10 @@ func captureStdout(f func() (*cobra.Command, error)) (string, error) {
} }
func TestListAll(t *testing.T) { func TestListAll(t *testing.T) {
assert := require.New(t) c := qt.New(t)
dir, err := createSimpleTestSite(t, testSiteConfig{}) dir, err := createSimpleTestSite(t, testSiteConfig{})
assert.NoError(err) c.Assert(err, qt.IsNil)
hugoCmd := newCommandsBuilder().addAll().build() hugoCmd := newCommandsBuilder().addAll().build()
cmd := hugoCmd.getCommand() cmd := hugoCmd.getCommand()
@ -48,24 +48,25 @@ func TestListAll(t *testing.T) {
cmd.SetArgs([]string{"-s=" + dir, "list", "all"}) cmd.SetArgs([]string{"-s=" + dir, "list", "all"})
out, err := captureStdout(cmd.ExecuteC) out, err := captureStdout(cmd.ExecuteC)
assert.NoError(err) c.Assert(err, qt.IsNil)
r := csv.NewReader(strings.NewReader(out)) r := csv.NewReader(strings.NewReader(out))
header, err := r.Read() header, err := r.Read()
assert.NoError(err)
assert.Equal([]string{ c.Assert(err, qt.IsNil)
c.Assert(header, qt.DeepEquals, []string{
"path", "slug", "title", "path", "slug", "title",
"date", "expiryDate", "publishDate", "date", "expiryDate", "publishDate",
"draft", "permalink", "draft", "permalink",
}, header) })
record, err := r.Read() record, err := r.Read()
assert.NoError(err)
assert.Equal([]string{ c.Assert(err, qt.IsNil)
c.Assert(record, qt.DeepEquals, []string{
filepath.Join("content", "p1.md"), "", "P1", filepath.Join("content", "p1.md"), "", "P1",
"0001-01-01T00:00:00Z", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00Z", "0001-01-01T00:00:00Z",
"false", "https://example.org/p1/", "false", "https://example.org/p1/",
}, record) })
} }

View file

@ -19,19 +19,20 @@ import (
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
// Issue #1133 // Issue #1133
func TestNewContentPathSectionWithForwardSlashes(t *testing.T) { func TestNewContentPathSectionWithForwardSlashes(t *testing.T) {
c := qt.New(t)
p, s := newContentPathSection(nil, "/post/new.md") p, s := newContentPathSection(nil, "/post/new.md")
assert.Equal(t, filepath.FromSlash("/post/new.md"), p) c.Assert(p, qt.Equals, filepath.FromSlash("/post/new.md"))
assert.Equal(t, "post", s) c.Assert(s, qt.Equals, "post")
} }
func checkNewSiteInited(fs *hugofs.Fs, basepath string, t *testing.T) { func checkNewSiteInited(fs *hugofs.Fs, basepath string, t *testing.T) {
c := qt.New(t)
paths := []string{ paths := []string{
filepath.Join(basepath, "layouts"), filepath.Join(basepath, "layouts"),
filepath.Join(basepath, "content"), filepath.Join(basepath, "content"),
@ -43,77 +44,82 @@ func checkNewSiteInited(fs *hugofs.Fs, basepath string, t *testing.T) {
for _, path := range paths { for _, path := range paths {
_, err := fs.Source.Stat(path) _, err := fs.Source.Stat(path)
require.NoError(t, err) c.Assert(err, qt.IsNil)
} }
} }
func TestDoNewSite(t *testing.T) { func TestDoNewSite(t *testing.T) {
c := qt.New(t)
n := newNewSiteCmd() n := newNewSiteCmd()
basepath := filepath.Join("base", "blog") basepath := filepath.Join("base", "blog")
_, fs := newTestCfg() _, fs := newTestCfg()
require.NoError(t, n.doNewSite(fs, basepath, false)) c.Assert(n.doNewSite(fs, basepath, false), qt.IsNil)
checkNewSiteInited(fs, basepath, t) checkNewSiteInited(fs, basepath, t)
} }
func TestDoNewSite_noerror_base_exists_but_empty(t *testing.T) { func TestDoNewSite_noerror_base_exists_but_empty(t *testing.T) {
c := qt.New(t)
basepath := filepath.Join("base", "blog") basepath := filepath.Join("base", "blog")
_, fs := newTestCfg() _, fs := newTestCfg()
n := newNewSiteCmd() n := newNewSiteCmd()
require.NoError(t, fs.Source.MkdirAll(basepath, 0777)) c.Assert(fs.Source.MkdirAll(basepath, 0777), qt.IsNil)
require.NoError(t, n.doNewSite(fs, basepath, false)) c.Assert(n.doNewSite(fs, basepath, false), qt.IsNil)
} }
func TestDoNewSite_error_base_exists(t *testing.T) { func TestDoNewSite_error_base_exists(t *testing.T) {
c := qt.New(t)
basepath := filepath.Join("base", "blog") basepath := filepath.Join("base", "blog")
_, fs := newTestCfg() _, fs := newTestCfg()
n := newNewSiteCmd() n := newNewSiteCmd()
require.NoError(t, fs.Source.MkdirAll(basepath, 0777)) c.Assert(fs.Source.MkdirAll(basepath, 0777), qt.IsNil)
_, err := fs.Source.Create(filepath.Join(basepath, "foo")) _, err := fs.Source.Create(filepath.Join(basepath, "foo"))
require.NoError(t, err) c.Assert(err, qt.IsNil)
// Since the directory already exists and isn't empty, expect an error // Since the directory already exists and isn't empty, expect an error
require.Error(t, n.doNewSite(fs, basepath, false)) c.Assert(n.doNewSite(fs, basepath, false), qt.Not(qt.IsNil))
} }
func TestDoNewSite_force_empty_dir(t *testing.T) { func TestDoNewSite_force_empty_dir(t *testing.T) {
c := qt.New(t)
basepath := filepath.Join("base", "blog") basepath := filepath.Join("base", "blog")
_, fs := newTestCfg() _, fs := newTestCfg()
n := newNewSiteCmd() n := newNewSiteCmd()
require.NoError(t, fs.Source.MkdirAll(basepath, 0777)) c.Assert(fs.Source.MkdirAll(basepath, 0777), qt.IsNil)
c.Assert(n.doNewSite(fs, basepath, true), qt.IsNil)
require.NoError(t, n.doNewSite(fs, basepath, true))
checkNewSiteInited(fs, basepath, t) checkNewSiteInited(fs, basepath, t)
} }
func TestDoNewSite_error_force_dir_inside_exists(t *testing.T) { func TestDoNewSite_error_force_dir_inside_exists(t *testing.T) {
c := qt.New(t)
basepath := filepath.Join("base", "blog") basepath := filepath.Join("base", "blog")
_, fs := newTestCfg() _, fs := newTestCfg()
n := newNewSiteCmd() n := newNewSiteCmd()
contentPath := filepath.Join(basepath, "content") contentPath := filepath.Join(basepath, "content")
require.NoError(t, fs.Source.MkdirAll(contentPath, 0777)) c.Assert(fs.Source.MkdirAll(contentPath, 0777), qt.IsNil)
require.Error(t, n.doNewSite(fs, basepath, true)) c.Assert(n.doNewSite(fs, basepath, true), qt.Not(qt.IsNil))
} }
func TestDoNewSite_error_force_config_inside_exists(t *testing.T) { func TestDoNewSite_error_force_config_inside_exists(t *testing.T) {
c := qt.New(t)
basepath := filepath.Join("base", "blog") basepath := filepath.Join("base", "blog")
_, fs := newTestCfg() _, fs := newTestCfg()
n := newNewSiteCmd() n := newNewSiteCmd()
configPath := filepath.Join(basepath, "config.toml") configPath := filepath.Join(basepath, "config.toml")
require.NoError(t, fs.Source.MkdirAll(basepath, 0777)) c.Assert(fs.Source.MkdirAll(basepath, 0777), qt.IsNil)
_, err := fs.Source.Create(configPath) _, err := fs.Source.Create(configPath)
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Error(t, n.doNewSite(fs, basepath, true)) c.Assert(n.doNewSite(fs, basepath, true), qt.Not(qt.IsNil))
} }
func newTestCfg() (*viper.Viper, *hugofs.Fs) { func newTestCfg() (*viper.Viper, *hugofs.Fs) {

View file

@ -24,8 +24,8 @@ import (
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
qt "github.com/frankban/quicktest"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestServer(t *testing.T) { func TestServer(t *testing.T) {
@ -33,9 +33,9 @@ func TestServer(t *testing.T) {
// TODO(bep) not sure why server tests have started to fail on the Windows CI server. // TODO(bep) not sure why server tests have started to fail on the Windows CI server.
t.Skip("Skip server test on appveyor") t.Skip("Skip server test on appveyor")
} }
assert := require.New(t) c := qt.New(t)
dir, err := createSimpleTestSite(t, testSiteConfig{}) dir, err := createSimpleTestSite(t, testSiteConfig{})
assert.NoError(err) c.Assert(err, qt.IsNil)
// Let us hope that this port is available on all systems ... // Let us hope that this port is available on all systems ...
port := 1331 port := 1331
@ -54,7 +54,7 @@ func TestServer(t *testing.T) {
go func() { go func() {
_, err = cmd.ExecuteC() _, err = cmd.ExecuteC()
assert.NoError(err) c.Assert(err, qt.IsNil)
}() }()
// There is no way to know exactly when the server is ready for connections. // There is no way to know exactly when the server is ready for connections.
@ -63,12 +63,12 @@ func TestServer(t *testing.T) {
time.Sleep(2 * time.Second) time.Sleep(2 * time.Second)
resp, err := http.Get("http://localhost:1331/") resp, err := http.Get("http://localhost:1331/")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer resp.Body.Close() defer resp.Body.Close()
homeContent := helpers.ReaderToString(resp.Body) homeContent := helpers.ReaderToString(resp.Body)
assert.Contains(homeContent, "List: Hugo Commands") c.Assert(homeContent, qt.Contains, "List: Hugo Commands")
assert.Contains(homeContent, "Environment: development") c.Assert(homeContent, qt.Contains, "Environment: development")
// Stop the server. // Stop the server.
stop <- true stop <- true
@ -118,14 +118,14 @@ func TestFixURL(t *testing.T) {
} }
func TestRemoveErrorPrefixFromLog(t *testing.T) { func TestRemoveErrorPrefixFromLog(t *testing.T) {
assert := require.New(t) c := qt.New(t)
content := `ERROR 2018/10/07 13:11:12 Error while rendering "home": template: _default/baseof.html:4:3: executing "main" at <partial "logo" .>: error calling partial: template: partials/logo.html:5:84: executing "partials/logo.html" at <$resized.AHeight>: can't evaluate field AHeight in type *resource.Image content := `ERROR 2018/10/07 13:11:12 Error while rendering "home": template: _default/baseof.html:4:3: executing "main" at <partial "logo" .>: error calling partial: template: partials/logo.html:5:84: executing "partials/logo.html" at <$resized.AHeight>: can't evaluate field AHeight in type *resource.Image
ERROR 2018/10/07 13:11:12 Rebuild failed: logged 1 error(s) ERROR 2018/10/07 13:11:12 Rebuild failed: logged 1 error(s)
` `
withoutError := removeErrorPrefixFromLog(content) withoutError := removeErrorPrefixFromLog(content)
assert.False(strings.Contains(withoutError, "ERROR"), withoutError) c.Assert(strings.Contains(withoutError, "ERROR"), qt.Equals, false)
} }

View file

@ -14,17 +14,16 @@
package collections package collections
import ( import (
"fmt"
"reflect"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestAppend(t *testing.T) { func TestAppend(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
for i, test := range []struct { for _, test := range []struct {
start interface{} start interface{}
addend []interface{} addend []interface{}
expected interface{} expected interface{}
@ -59,20 +58,16 @@ func TestAppend(t *testing.T) {
false}, false},
} { } {
errMsg := fmt.Sprintf("[%d]", i)
result, err := Append(test.start, test.addend...) result, err := Append(test.start, test.addend...)
if b, ok := test.expected.(bool); ok && !b { if b, ok := test.expected.(bool); ok && !b {
require.Error(t, err, errMsg)
c.Assert(err, qt.Not(qt.IsNil))
continue continue
} }
require.NoError(t, err, errMsg) c.Assert(err, qt.IsNil)
c.Assert(result, qt.DeepEquals, test.expected)
if !reflect.DeepEqual(test.expected, result) {
t.Fatalf("%s got\n%T: %v\nexpected\n%T: %v", errMsg, result, result, test.expected, test.expected)
}
} }
} }

View file

@ -15,10 +15,9 @@ package collections
import ( import (
"errors" "errors"
"fmt"
"testing" "testing"
"github.com/alecthomas/assert" qt "github.com/frankban/quicktest"
) )
var _ Slicer = (*tstSlicer)(nil) var _ Slicer = (*tstSlicer)(nil)
@ -34,15 +33,15 @@ type testSlicerInterface interface {
type testSlicerInterfaces []testSlicerInterface type testSlicerInterfaces []testSlicerInterface
type tstSlicerIn1 struct { type tstSlicerIn1 struct {
name string TheName string
} }
type tstSlicerIn2 struct { type tstSlicerIn2 struct {
name string TheName string
} }
type tstSlicer struct { type tstSlicer struct {
name string TheName string
} }
func (p *tstSlicerIn1) Slice(in interface{}) (interface{}, error) { func (p *tstSlicerIn1) Slice(in interface{}) (interface{}, error) {
@ -75,11 +74,11 @@ func (p *tstSlicerIn2) Slice(in interface{}) (interface{}, error) {
} }
func (p *tstSlicerIn1) Name() string { func (p *tstSlicerIn1) Name() string {
return p.name return p.TheName
} }
func (p *tstSlicerIn2) Name() string { func (p *tstSlicerIn2) Name() string {
return p.name return p.TheName
} }
func (p *tstSlicer) Slice(in interface{}) (interface{}, error) { func (p *tstSlicer) Slice(in interface{}) (interface{}, error) {
@ -100,6 +99,7 @@ type tstSlicers []*tstSlicer
func TestSlice(t *testing.T) { func TestSlice(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
for i, test := range []struct { for i, test := range []struct {
args []interface{} args []interface{}
@ -114,12 +114,11 @@ func TestSlice(t *testing.T) {
{[]interface{}{&tstSlicerIn1{"a"}, &tstSlicerIn2{"b"}}, testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn2{"b"}}}, {[]interface{}{&tstSlicerIn1{"a"}, &tstSlicerIn2{"b"}}, testSlicerInterfaces{&tstSlicerIn1{"a"}, &tstSlicerIn2{"b"}}},
{[]interface{}{&tstSlicerIn1{"a"}, &tstSlicer{"b"}}, []interface{}{&tstSlicerIn1{"a"}, &tstSlicer{"b"}}}, {[]interface{}{&tstSlicerIn1{"a"}, &tstSlicer{"b"}}, []interface{}{&tstSlicerIn1{"a"}, &tstSlicer{"b"}}},
} { } {
errMsg := fmt.Sprintf("[%d] %v", i, test.args) errMsg := qt.Commentf("[%d] %v", i, test.args)
result := Slice(test.args...) result := Slice(test.args...)
assert.Equal(t, test.expected, result, errMsg) c.Assert(test.expected, qt.DeepEquals, result, errMsg)
} }
assert.Len(t, Slice(), 0)
} }

View file

@ -18,11 +18,11 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestErrorLocator(t *testing.T) { func TestErrorLocator(t *testing.T) {
assert := require.New(t) c := qt.New(t)
lineMatcher := func(m LineMatcher) bool { lineMatcher := func(m LineMatcher) bool {
return strings.Contains(m.Line, "THEONE") return strings.Contains(m.Line, "THEONE")
@ -39,45 +39,45 @@ LINE 8
` `
location := locateErrorInString(lines, lineMatcher) location := locateErrorInString(lines, lineMatcher)
assert.Equal([]string{"LINE 3", "LINE 4", "This is THEONE", "LINE 6", "LINE 7"}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"LINE 3", "LINE 4", "This is THEONE", "LINE 6", "LINE 7"})
pos := location.Position() pos := location.Position()
assert.Equal(5, pos.LineNumber) c.Assert(pos.LineNumber, qt.Equals, 5)
assert.Equal(2, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 2)
assert.Equal([]string{"This is THEONE"}, locateErrorInString(`This is THEONE`, lineMatcher).Lines) c.Assert(locateErrorInString(`This is THEONE`, lineMatcher).Lines, qt.DeepEquals, []string{"This is THEONE"})
location = locateErrorInString(`L1 location = locateErrorInString(`L1
This is THEONE This is THEONE
L2 L2
`, lineMatcher) `, lineMatcher)
assert.Equal(2, location.Position().LineNumber) c.Assert(location.Position().LineNumber, qt.Equals, 2)
assert.Equal(1, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 1)
assert.Equal([]string{"L1", "This is THEONE", "L2", ""}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"L1", "This is THEONE", "L2", ""})
location = locateErrorInString(`This is THEONE location = locateErrorInString(`This is THEONE
L2 L2
`, lineMatcher) `, lineMatcher)
assert.Equal(0, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 0)
assert.Equal([]string{"This is THEONE", "L2", ""}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"This is THEONE", "L2", ""})
location = locateErrorInString(`L1 location = locateErrorInString(`L1
This THEONE This THEONE
`, lineMatcher) `, lineMatcher)
assert.Equal([]string{"L1", "This THEONE", ""}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"L1", "This THEONE", ""})
assert.Equal(1, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 1)
location = locateErrorInString(`L1 location = locateErrorInString(`L1
L2 L2
This THEONE This THEONE
`, lineMatcher) `, lineMatcher)
assert.Equal([]string{"L1", "L2", "This THEONE", ""}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"L1", "L2", "This THEONE", ""})
assert.Equal(2, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 2)
location = locateErrorInString("NO MATCH", lineMatcher) location = locateErrorInString("NO MATCH", lineMatcher)
assert.Equal(-1, location.Position().LineNumber) c.Assert(location.Position().LineNumber, qt.Equals, -1)
assert.Equal(-1, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, -1)
assert.Equal(0, len(location.Lines)) c.Assert(len(location.Lines), qt.Equals, 0)
lineMatcher = func(m LineMatcher) bool { lineMatcher = func(m LineMatcher) bool {
return m.LineNumber == 6 return m.LineNumber == 6
@ -94,9 +94,9 @@ H
I I
J`, lineMatcher) J`, lineMatcher)
assert.Equal([]string{"D", "E", "F", "G", "H"}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"D", "E", "F", "G", "H"})
assert.Equal(6, location.Position().LineNumber) c.Assert(location.Position().LineNumber, qt.Equals, 6)
assert.Equal(2, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 2)
// Test match EOF // Test match EOF
lineMatcher = func(m LineMatcher) bool { lineMatcher = func(m LineMatcher) bool {
@ -108,9 +108,9 @@ B
C C
`, lineMatcher) `, lineMatcher)
assert.Equal([]string{"B", "C", ""}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"B", "C", ""})
assert.Equal(4, location.Position().LineNumber) c.Assert(location.Position().LineNumber, qt.Equals, 4)
assert.Equal(2, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 2)
offsetMatcher := func(m LineMatcher) bool { offsetMatcher := func(m LineMatcher) bool {
return m.Offset == 1 return m.Offset == 1
@ -122,8 +122,8 @@ C
D D
E`, offsetMatcher) E`, offsetMatcher)
assert.Equal([]string{"A", "B", "C", "D"}, location.Lines) c.Assert(location.Lines, qt.DeepEquals, []string{"A", "B", "C", "D"})
assert.Equal(2, location.Position().LineNumber) c.Assert(location.Position().LineNumber, qt.Equals, 2)
assert.Equal(1, location.LinesPos) c.Assert(location.LinesPos, qt.Equals, 1)
} }

View file

@ -14,18 +14,17 @@
package herrors package herrors
import ( import (
"fmt"
"testing" "testing"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestToLineNumberError(t *testing.T) { func TestToLineNumberError(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
for i, test := range []struct { for i, test := range []struct {
in error in error
@ -43,15 +42,15 @@ func TestToLineNumberError(t *testing.T) {
got := ToFileError("template", test.in) got := ToFileError("template", test.in)
errMsg := fmt.Sprintf("[%d][%T]", i, got) errMsg := qt.Commentf("[%d][%T]", i, got)
le, ok := got.(FileError) le, ok := got.(FileError)
assert.True(ok) c.Assert(ok, qt.Equals, true)
assert.True(ok, errMsg) c.Assert(ok, qt.Equals, true, errMsg)
pos := le.Position() pos := le.Position()
assert.Equal(test.lineNumber, pos.LineNumber, errMsg) c.Assert(pos.LineNumber, qt.Equals, test.lineNumber, errMsg)
assert.Equal(test.columnNumber, pos.ColumnNumber, errMsg) c.Assert(pos.ColumnNumber, qt.Equals, test.columnNumber, errMsg)
assert.Error(errors.Cause(got)) c.Assert(errors.Cause(got), qt.Not(qt.IsNil))
} }
} }

View file

@ -18,16 +18,16 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestIsTruthful(t *testing.T) { func TestIsTruthful(t *testing.T) {
assert := require.New(t) c := qt.New(t)
assert.True(IsTruthful(true)) c.Assert(IsTruthful(true), qt.Equals, true)
assert.False(IsTruthful(false)) c.Assert(IsTruthful(false), qt.Equals, false)
assert.True(IsTruthful(time.Now())) c.Assert(IsTruthful(time.Now()), qt.Equals, true)
assert.False(IsTruthful(time.Time{})) c.Assert(IsTruthful(time.Time{}), qt.Equals, false)
} }
func BenchmarkIsTruthFul(b *testing.B) { func BenchmarkIsTruthFul(b *testing.B) {

View file

@ -17,19 +17,19 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestHugoInfo(t *testing.T) { func TestHugoInfo(t *testing.T) {
assert := require.New(t) c := qt.New(t)
hugoInfo := NewInfo("") hugoInfo := NewInfo("")
assert.Equal(CurrentVersion.Version(), hugoInfo.Version()) c.Assert(hugoInfo.Version(), qt.Equals, CurrentVersion.Version())
assert.IsType(VersionString(""), hugoInfo.Version()) c.Assert(fmt.Sprintf("%T", VersionString("")), qt.Equals, fmt.Sprintf("%T", hugoInfo.Version()))
assert.Equal(commitHash, hugoInfo.CommitHash) c.Assert(hugoInfo.CommitHash, qt.Equals, commitHash)
assert.Equal(buildDate, hugoInfo.BuildDate) c.Assert(hugoInfo.BuildDate, qt.Equals, buildDate)
assert.Equal("production", hugoInfo.Environment) c.Assert(hugoInfo.Environment, qt.Equals, "production")
assert.Contains(hugoInfo.Generator(), fmt.Sprintf("Hugo %s", hugoInfo.Version())) c.Assert(string(hugoInfo.Generator()), qt.Contains, fmt.Sprintf("Hugo %s", hugoInfo.Version()))
} }

View file

@ -16,70 +16,73 @@ package hugo
import ( import (
"testing" "testing"
"github.com/stretchr/testify/assert" qt "github.com/frankban/quicktest"
"github.com/stretchr/testify/require"
) )
func TestHugoVersion(t *testing.T) { func TestHugoVersion(t *testing.T) {
assert.Equal(t, "0.15-DEV", version(0.15, 0, "-DEV")) c := qt.New(t)
assert.Equal(t, "0.15.2-DEV", version(0.15, 2, "-DEV"))
c.Assert(version(0.15, 0, "-DEV"), qt.Equals, "0.15-DEV")
c.Assert(version(0.15, 2, "-DEV"), qt.Equals, "0.15.2-DEV")
v := Version{Number: 0.21, PatchLevel: 0, Suffix: "-DEV"} v := Version{Number: 0.21, PatchLevel: 0, Suffix: "-DEV"}
require.Equal(t, v.ReleaseVersion().String(), "0.21") c.Assert(v.ReleaseVersion().String(), qt.Equals, "0.21")
require.Equal(t, "0.21-DEV", v.String()) c.Assert(v.String(), qt.Equals, "0.21-DEV")
require.Equal(t, "0.22", v.Next().String()) c.Assert(v.Next().String(), qt.Equals, "0.22")
nextVersionString := v.Next().Version() nextVersionString := v.Next().Version()
require.Equal(t, "0.22", nextVersionString.String()) c.Assert(nextVersionString.String(), qt.Equals, "0.22")
require.True(t, nextVersionString.Eq("0.22")) c.Assert(nextVersionString.Eq("0.22"), qt.Equals, true)
require.False(t, nextVersionString.Eq("0.21")) c.Assert(nextVersionString.Eq("0.21"), qt.Equals, false)
require.True(t, nextVersionString.Eq(nextVersionString)) c.Assert(nextVersionString.Eq(nextVersionString), qt.Equals, true)
require.Equal(t, "0.20.3", v.NextPatchLevel(3).String()) c.Assert(v.NextPatchLevel(3).String(), qt.Equals, "0.20.3")
// We started to use full semver versions even for main // We started to use full semver versions even for main
// releases in v0.54.0 // releases in v0.54.0
v = Version{Number: 0.53, PatchLevel: 0} v = Version{Number: 0.53, PatchLevel: 0}
require.Equal(t, "0.53", v.String()) c.Assert(v.String(), qt.Equals, "0.53")
require.Equal(t, "0.54.0", v.Next().String()) c.Assert(v.Next().String(), qt.Equals, "0.54.0")
require.Equal(t, "0.55.0", v.Next().Next().String()) c.Assert(v.Next().Next().String(), qt.Equals, "0.55.0")
v = Version{Number: 0.54, PatchLevel: 0, Suffix: "-DEV"} v = Version{Number: 0.54, PatchLevel: 0, Suffix: "-DEV"}
require.Equal(t, "0.54.0-DEV", v.String()) c.Assert(v.String(), qt.Equals, "0.54.0-DEV")
} }
func TestCompareVersions(t *testing.T) { func TestCompareVersions(t *testing.T) {
require.Equal(t, 0, compareVersions(0.20, 0, 0.20)) c := qt.New(t)
require.Equal(t, 0, compareVersions(0.20, 0, float32(0.20)))
require.Equal(t, 0, compareVersions(0.20, 0, float64(0.20)))
require.Equal(t, 1, compareVersions(0.19, 1, 0.20))
require.Equal(t, 1, compareVersions(0.19, 3, "0.20.2"))
require.Equal(t, -1, compareVersions(0.19, 1, 0.01))
require.Equal(t, 1, compareVersions(0, 1, 3))
require.Equal(t, 1, compareVersions(0, 1, int32(3)))
require.Equal(t, 1, compareVersions(0, 1, int64(3)))
require.Equal(t, 0, compareVersions(0.20, 0, "0.20"))
require.Equal(t, 0, compareVersions(0.20, 1, "0.20.1"))
require.Equal(t, -1, compareVersions(0.20, 1, "0.20"))
require.Equal(t, 1, compareVersions(0.20, 0, "0.20.1"))
require.Equal(t, 1, compareVersions(0.20, 1, "0.20.2"))
require.Equal(t, 1, compareVersions(0.21, 1, "0.22.1"))
require.Equal(t, -1, compareVersions(0.22, 0, "0.22-DEV"))
require.Equal(t, 1, compareVersions(0.22, 0, "0.22.1-DEV"))
require.Equal(t, 1, compareVersionsWithSuffix(0.22, 0, "-DEV", "0.22"))
require.Equal(t, -1, compareVersionsWithSuffix(0.22, 1, "-DEV", "0.22"))
require.Equal(t, 0, compareVersionsWithSuffix(0.22, 1, "-DEV", "0.22.1-DEV"))
c.Assert(compareVersions(0.20, 0, 0.20), qt.Equals, 0)
c.Assert(compareVersions(0.20, 0, float32(0.20)), qt.Equals, 0)
c.Assert(compareVersions(0.20, 0, float64(0.20)), qt.Equals, 0)
c.Assert(compareVersions(0.19, 1, 0.20), qt.Equals, 1)
c.Assert(compareVersions(0.19, 3, "0.20.2"), qt.Equals, 1)
c.Assert(compareVersions(0.19, 1, 0.01), qt.Equals, -1)
c.Assert(compareVersions(0, 1, 3), qt.Equals, 1)
c.Assert(compareVersions(0, 1, int32(3)), qt.Equals, 1)
c.Assert(compareVersions(0, 1, int64(3)), qt.Equals, 1)
c.Assert(compareVersions(0.20, 0, "0.20"), qt.Equals, 0)
c.Assert(compareVersions(0.20, 1, "0.20.1"), qt.Equals, 0)
c.Assert(compareVersions(0.20, 1, "0.20"), qt.Equals, -1)
c.Assert(compareVersions(0.20, 0, "0.20.1"), qt.Equals, 1)
c.Assert(compareVersions(0.20, 1, "0.20.2"), qt.Equals, 1)
c.Assert(compareVersions(0.21, 1, "0.22.1"), qt.Equals, 1)
c.Assert(compareVersions(0.22, 0, "0.22-DEV"), qt.Equals, -1)
c.Assert(compareVersions(0.22, 0, "0.22.1-DEV"), qt.Equals, 1)
c.Assert(compareVersionsWithSuffix(0.22, 0, "-DEV", "0.22"), qt.Equals, 1)
c.Assert(compareVersionsWithSuffix(0.22, 1, "-DEV", "0.22"), qt.Equals, -1)
c.Assert(compareVersionsWithSuffix(0.22, 1, "-DEV", "0.22.1-DEV"), qt.Equals, 0)
} }
func TestParseHugoVersion(t *testing.T) { func TestParseHugoVersion(t *testing.T) {
require.Equal(t, "0.25", MustParseVersion("0.25").String()) c := qt.New(t)
require.Equal(t, "0.25.2", MustParseVersion("0.25.2").String())
require.Equal(t, "0.25-test", MustParseVersion("0.25-test").String())
require.Equal(t, "0.25-DEV", MustParseVersion("0.25-DEV").String())
c.Assert(MustParseVersion("0.25").String(), qt.Equals, "0.25")
c.Assert(MustParseVersion("0.25.2").String(), qt.Equals, "0.25.2")
c.Assert(MustParseVersion("0.25-test").String(), qt.Equals, "0.25-test")
c.Assert(MustParseVersion("0.25-DEV").String(), qt.Equals, "0.25-DEV")
} }
func TestGoMinorVersion(t *testing.T) { func TestGoMinorVersion(t *testing.T) {
assert := require.New(t) c := qt.New(t)
assert.Equal(12, goMinorVersion("go1.12.5")) c.Assert(goMinorVersion("go1.12.5"), qt.Equals, 12)
assert.True(GoMinorVersion() >= 11) c.Assert(GoMinorVersion() >= 11, qt.Equals, true)
} }

View file

@ -16,17 +16,17 @@ package loggers
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestLogger(t *testing.T) { func TestLogger(t *testing.T) {
assert := require.New(t) c := qt.New(t)
l := NewWarningLogger() l := NewWarningLogger()
l.ERROR.Println("One error") l.ERROR.Println("One error")
l.ERROR.Println("Two error") l.ERROR.Println("Two error")
l.WARN.Println("A warning") l.WARN.Println("A warning")
assert.Equal(uint64(2), l.ErrorCounter.Count()) c.Assert(l.ErrorCounter.Count(), qt.Equals, uint64(2))
} }

View file

@ -17,7 +17,7 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestToLower(t *testing.T) { func TestToLower(t *testing.T) {
@ -74,7 +74,7 @@ func TestToLower(t *testing.T) {
} }
func TestRenameKeys(t *testing.T) { func TestRenameKeys(t *testing.T) {
assert := require.New(t) c := qt.New(t)
m := map[string]interface{}{ m := map[string]interface{}{
"a": 32, "a": 32,
@ -112,7 +112,7 @@ func TestRenameKeys(t *testing.T) {
"{ren1,sub/*/ren1}", "new1", "{ren1,sub/*/ren1}", "new1",
"{Ren2,sub/ren2}", "new2", "{Ren2,sub/ren2}", "new2",
) )
assert.NoError(err) c.Assert(err, qt.IsNil)
renamer.Rename(m) renamer.Rename(m)

View file

@ -16,7 +16,7 @@ package maps
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestGetNestedParam(t *testing.T) { func TestGetNestedParam(t *testing.T) {
@ -33,19 +33,19 @@ func TestGetNestedParam(t *testing.T) {
}, },
} }
assert := require.New(t) c := qt.New(t)
must := func(keyStr, separator string, candidates ...map[string]interface{}) interface{} { must := func(keyStr, separator string, candidates ...map[string]interface{}) interface{} {
v, err := GetNestedParam(keyStr, separator, candidates...) v, err := GetNestedParam(keyStr, separator, candidates...)
assert.NoError(err) c.Assert(err, qt.IsNil)
return v return v
} }
assert.Equal(1, must("first", "_", m)) c.Assert(must("first", "_", m), qt.Equals, 1)
assert.Equal(1, must("First", "_", m)) c.Assert(must("First", "_", m), qt.Equals, 1)
assert.Equal(2, must("with_underscore", "_", m)) c.Assert(must("with_underscore", "_", m), qt.Equals, 2)
assert.Equal("blue", must("nested_color", "_", m)) c.Assert(must("nested_color", "_", m), qt.Equals, "blue")
assert.Equal("green", must("nested.nestednested.color", ".", m)) c.Assert(must("nested.nestednested.color", ".", m), qt.Equals, "green")
assert.Nil(must("string.name", ".", m)) c.Assert(must("string.name", ".", m), qt.IsNil)
} }

View file

@ -18,31 +18,31 @@ import (
"sync" "sync"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestScratchAdd(t *testing.T) { func TestScratchAdd(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
scratch := NewScratch() scratch := NewScratch()
scratch.Add("int1", 10) scratch.Add("int1", 10)
scratch.Add("int1", 20) scratch.Add("int1", 20)
scratch.Add("int2", 20) scratch.Add("int2", 20)
assert.Equal(int64(30), scratch.Get("int1")) c.Assert(scratch.Get("int1"), qt.Equals, int64(30))
assert.Equal(20, scratch.Get("int2")) c.Assert(scratch.Get("int2"), qt.Equals, 20)
scratch.Add("float1", float64(10.5)) scratch.Add("float1", float64(10.5))
scratch.Add("float1", float64(20.1)) scratch.Add("float1", float64(20.1))
assert.Equal(float64(30.6), scratch.Get("float1")) c.Assert(scratch.Get("float1"), qt.Equals, float64(30.6))
scratch.Add("string1", "Hello ") scratch.Add("string1", "Hello ")
scratch.Add("string1", "big ") scratch.Add("string1", "big ")
scratch.Add("string1", "World!") scratch.Add("string1", "World!")
assert.Equal("Hello big World!", scratch.Get("string1")) c.Assert(scratch.Get("string1"), qt.Equals, "Hello big World!")
scratch.Add("scratch", scratch) scratch.Add("scratch", scratch)
_, err := scratch.Add("scratch", scratch) _, err := scratch.Add("scratch", scratch)
@ -55,14 +55,14 @@ func TestScratchAdd(t *testing.T) {
func TestScratchAddSlice(t *testing.T) { func TestScratchAddSlice(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
scratch := NewScratch() scratch := NewScratch()
_, err := scratch.Add("intSlice", []int{1, 2}) _, err := scratch.Add("intSlice", []int{1, 2})
assert.NoError(err) c.Assert(err, qt.IsNil)
_, err = scratch.Add("intSlice", 3) _, err = scratch.Add("intSlice", 3)
assert.NoError(err) c.Assert(err, qt.IsNil)
sl := scratch.Get("intSlice") sl := scratch.Get("intSlice")
expected := []int{1, 2, 3} expected := []int{1, 2, 3}
@ -72,7 +72,7 @@ func TestScratchAddSlice(t *testing.T) {
} }
_, err = scratch.Add("intSlice", []int{4, 5}) _, err = scratch.Add("intSlice", []int{4, 5})
assert.NoError(err) c.Assert(err, qt.IsNil)
sl = scratch.Get("intSlice") sl = scratch.Get("intSlice")
expected = []int{1, 2, 3, 4, 5} expected = []int{1, 2, 3, 4, 5}
@ -85,49 +85,49 @@ func TestScratchAddSlice(t *testing.T) {
// https://github.com/gohugoio/hugo/issues/5275 // https://github.com/gohugoio/hugo/issues/5275
func TestScratchAddTypedSliceToInterfaceSlice(t *testing.T) { func TestScratchAddTypedSliceToInterfaceSlice(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
scratch := NewScratch() scratch := NewScratch()
scratch.Set("slice", []interface{}{}) scratch.Set("slice", []interface{}{})
_, err := scratch.Add("slice", []int{1, 2}) _, err := scratch.Add("slice", []int{1, 2})
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]int{1, 2}, scratch.Get("slice")) c.Assert(scratch.Get("slice"), qt.DeepEquals, []int{1, 2})
} }
// https://github.com/gohugoio/hugo/issues/5361 // https://github.com/gohugoio/hugo/issues/5361
func TestScratchAddDifferentTypedSliceToInterfaceSlice(t *testing.T) { func TestScratchAddDifferentTypedSliceToInterfaceSlice(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
scratch := NewScratch() scratch := NewScratch()
scratch.Set("slice", []string{"foo"}) scratch.Set("slice", []string{"foo"})
_, err := scratch.Add("slice", []int{1, 2}) _, err := scratch.Add("slice", []int{1, 2})
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]interface{}{"foo", 1, 2}, scratch.Get("slice")) c.Assert(scratch.Get("slice"), qt.DeepEquals, []interface{}{"foo", 1, 2})
} }
func TestScratchSet(t *testing.T) { func TestScratchSet(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
scratch := NewScratch() scratch := NewScratch()
scratch.Set("key", "val") scratch.Set("key", "val")
assert.Equal("val", scratch.Get("key")) c.Assert(scratch.Get("key"), qt.Equals, "val")
} }
func TestScratchDelete(t *testing.T) { func TestScratchDelete(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
scratch := NewScratch() scratch := NewScratch()
scratch.Set("key", "val") scratch.Set("key", "val")
scratch.Delete("key") scratch.Delete("key")
scratch.Add("key", "Lucy Parsons") scratch.Add("key", "Lucy Parsons")
assert.Equal("Lucy Parsons", scratch.Get("key")) c.Assert(scratch.Get("key"), qt.Equals, "Lucy Parsons")
} }
// Issue #2005 // Issue #2005
@ -177,7 +177,7 @@ func TestScratchGet(t *testing.T) {
func TestScratchSetInMap(t *testing.T) { func TestScratchSetInMap(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
scratch := NewScratch() scratch := NewScratch()
scratch.SetInMap("key", "lux", "Lux") scratch.SetInMap("key", "lux", "Lux")
@ -185,7 +185,7 @@ func TestScratchSetInMap(t *testing.T) {
scratch.SetInMap("key", "zyx", "Zyx") scratch.SetInMap("key", "zyx", "Zyx")
scratch.SetInMap("key", "abc", "Abc (updated)") scratch.SetInMap("key", "abc", "Abc (updated)")
scratch.SetInMap("key", "def", "Def") scratch.SetInMap("key", "def", "Def")
assert.Equal([]interface{}{0: "Abc (updated)", 1: "Def", 2: "Lux", 3: "Zyx"}, scratch.GetSortedMapValues("key")) c.Assert(scratch.GetSortedMapValues("key"), qt.DeepEquals, []interface{}{0: "Abc (updated)", 1: "Def", 2: "Lux", 3: "Zyx"})
} }
func TestScratchGetSortedMapValues(t *testing.T) { func TestScratchGetSortedMapValues(t *testing.T) {

View file

@ -14,17 +14,16 @@
package math package math
import ( import (
"fmt"
"testing" "testing"
"github.com/alecthomas/assert" qt "github.com/frankban/quicktest"
"github.com/stretchr/testify/require"
) )
func TestDoArithmetic(t *testing.T) { func TestDoArithmetic(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
for i, test := range []struct { for _, test := range []struct {
a interface{} a interface{}
b interface{} b interface{}
op rune op rune
@ -94,16 +93,14 @@ func TestDoArithmetic(t *testing.T) {
{"foo", "bar", '-', false}, {"foo", "bar", '-', false},
{3, 2, '%', false}, {3, 2, '%', false},
} { } {
errMsg := fmt.Sprintf("[%d] %v", i, test)
result, err := DoArithmetic(test.a, test.b, test.op) result, err := DoArithmetic(test.a, test.b, test.op)
if b, ok := test.expect.(bool); ok && !b { if b, ok := test.expect.(bool); ok && !b {
require.Error(t, err, errMsg) c.Assert(err, qt.Not(qt.IsNil))
continue continue
} }
require.NoError(t, err, errMsg) c.Assert(err, qt.IsNil)
assert.Equal(t, test.expect, result, errMsg) c.Assert(test.expect, qt.Equals, result)
} }
} }

View file

@ -16,18 +16,18 @@ package text
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestPositionStringFormatter(t *testing.T) { func TestPositionStringFormatter(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pos := Position{Filename: "/my/file.txt", LineNumber: 12, ColumnNumber: 13, Offset: 14} pos := Position{Filename: "/my/file.txt", LineNumber: 12, ColumnNumber: 13, Offset: 14}
assert.Equal("/my/file.txt|13|12", createPositionStringFormatter(":file|:col|:line")(pos)) c.Assert(createPositionStringFormatter(":file|:col|:line")(pos), qt.Equals, "/my/file.txt|13|12")
assert.Equal("13|/my/file.txt|12", createPositionStringFormatter(":col|:file|:line")(pos)) c.Assert(createPositionStringFormatter(":col|:file|:line")(pos), qt.Equals, "13|/my/file.txt|12")
assert.Equal("好:13", createPositionStringFormatter("好::col")(pos)) c.Assert(createPositionStringFormatter("好::col")(pos), qt.Equals, "好:13")
assert.Equal("\"/my/file.txt:12:13\"", createPositionStringFormatter("")(pos)) c.Assert(createPositionStringFormatter("")(pos), qt.Equals, "\"/my/file.txt:12:13\"")
assert.Equal("\"/my/file.txt:12:13\"", pos.String()) c.Assert(pos.String(), qt.Equals, "\"/my/file.txt:12:13\"")
} }

View file

@ -17,36 +17,36 @@ import (
"sync" "sync"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestEvictingStringQueue(t *testing.T) { func TestEvictingStringQueue(t *testing.T) {
assert := require.New(t) c := qt.New(t)
queue := NewEvictingStringQueue(3) queue := NewEvictingStringQueue(3)
assert.Equal("", queue.Peek()) c.Assert(queue.Peek(), qt.Equals, "")
queue.Add("a") queue.Add("a")
queue.Add("b") queue.Add("b")
queue.Add("a") queue.Add("a")
assert.Equal("b", queue.Peek()) c.Assert(queue.Peek(), qt.Equals, "b")
queue.Add("b") queue.Add("b")
assert.Equal("b", queue.Peek()) c.Assert(queue.Peek(), qt.Equals, "b")
queue.Add("a") queue.Add("a")
queue.Add("b") queue.Add("b")
assert.True(queue.Contains("a")) c.Assert(queue.Contains("a"), qt.Equals, true)
assert.False(queue.Contains("foo")) c.Assert(queue.Contains("foo"), qt.Equals, false)
assert.Equal([]string{"b", "a"}, queue.PeekAll()) c.Assert(queue.PeekAll(), qt.DeepEquals, []string{"b", "a"})
assert.Equal("b", queue.Peek()) c.Assert(queue.Peek(), qt.Equals, "b")
queue.Add("c") queue.Add("c")
queue.Add("d") queue.Add("d")
// Overflowed, a should now be removed. // Overflowed, a should now be removed.
assert.Equal([]string{"d", "c", "b"}, queue.PeekAll()) c.Assert(queue.PeekAll(), qt.DeepEquals, []string{"d", "c", "b"})
assert.Len(queue.PeekAllSet(), 3) c.Assert(len(queue.PeekAllSet()), qt.Equals, 3)
assert.True(queue.PeekAllSet()["c"]) c.Assert(queue.PeekAllSet()["c"], qt.Equals, true)
} }
func TestEvictingStringQueueConcurrent(t *testing.T) { func TestEvictingStringQueueConcurrent(t *testing.T) {

View file

@ -16,14 +16,14 @@ package types
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestKeyValues(t *testing.T) { func TestKeyValues(t *testing.T) {
assert := require.New(t) c := qt.New(t)
kv := NewKeyValuesStrings("key", "a1", "a2") kv := NewKeyValuesStrings("key", "a1", "a2")
assert.Equal("key", kv.KeyString()) c.Assert(kv.KeyString(), qt.Equals, "key")
assert.Equal([]interface{}{"a1", "a2"}, kv.Values) c.Assert(kv.Values, qt.DeepEquals, []interface{}{"a1", "a2"})
} }

View file

@ -14,17 +14,16 @@
package compare package compare
import ( import (
"fmt"
"sort" "sort"
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestCompare(t *testing.T) { func TestCompare(t *testing.T) {
assert := require.New(t) c := qt.New(t)
for i, test := range []struct { for _, test := range []struct {
a string a string
b string b string
}{ }{
@ -47,13 +46,13 @@ func TestCompare(t *testing.T) {
expect := strings.Compare(strings.ToLower(test.a), strings.ToLower(test.b)) expect := strings.Compare(strings.ToLower(test.a), strings.ToLower(test.b))
got := compareFold(test.a, test.b) got := compareFold(test.a, test.b)
assert.Equal(expect, got, fmt.Sprintf("test %d: %d", i, expect)) c.Assert(got, qt.Equals, expect)
} }
} }
func TestLexicographicSort(t *testing.T) { func TestLexicographicSort(t *testing.T) {
assert := require.New(t) c := qt.New(t)
s := []string{"b", "Bz", "ba", "A", "Ba", "ba"} s := []string{"b", "Bz", "ba", "A", "Ba", "ba"}
@ -61,6 +60,6 @@ func TestLexicographicSort(t *testing.T) {
return LessStrings(s[i], s[j]) return LessStrings(s[i], s[j])
}) })
assert.Equal([]string{"A", "b", "Ba", "ba", "ba", "Bz"}, s) c.Assert(s, qt.DeepEquals, []string{"A", "b", "Ba", "ba", "ba", "Bz"})
} }

View file

@ -17,18 +17,18 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestIsValidConfigFileName(t *testing.T) { func TestIsValidConfigFileName(t *testing.T) {
assert := require.New(t) c := qt.New(t)
for _, ext := range ValidConfigFileExtensions { for _, ext := range ValidConfigFileExtensions {
filename := "config." + ext filename := "config." + ext
assert.True(IsValidConfigFilename(filename), ext) c.Assert(IsValidConfigFilename(filename), qt.Equals, true)
assert.True(IsValidConfigFilename(strings.ToUpper(filename))) c.Assert(IsValidConfigFilename(strings.ToUpper(filename)), qt.Equals, true)
} }
assert.False(IsValidConfigFilename("")) c.Assert(IsValidConfigFilename(""), qt.Equals, false)
assert.False(IsValidConfigFilename("config.toml.swp")) c.Assert(IsValidConfigFilename("config.toml.swp"), qt.Equals, false)
} }

View file

@ -16,12 +16,12 @@ package config
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestGetStringSlicePreserveString(t *testing.T) { func TestGetStringSlicePreserveString(t *testing.T) {
assert := require.New(t) c := qt.New(t)
cfg := viper.New() cfg := viper.New()
s := "This is a string" s := "This is a string"
@ -30,7 +30,7 @@ func TestGetStringSlicePreserveString(t *testing.T) {
cfg.Set("s1", s) cfg.Set("s1", s)
cfg.Set("s2", sSlice) cfg.Set("s2", sSlice)
assert.Equal([]string{s}, GetStringSlicePreserveString(cfg, "s1")) c.Assert(GetStringSlicePreserveString(cfg, "s1"), qt.DeepEquals, []string{s})
assert.Equal(sSlice, GetStringSlicePreserveString(cfg, "s2")) c.Assert(GetStringSlicePreserveString(cfg, "s2"), qt.DeepEquals, sSlice)
assert.Nil(GetStringSlicePreserveString(cfg, "s3")) c.Assert(GetStringSlicePreserveString(cfg, "s3"), qt.IsNil)
} }

View file

@ -16,17 +16,17 @@ package config
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestSetEnvVars(t *testing.T) { func TestSetEnvVars(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
vars := []string{"FOO=bar", "HUGO=cool", "BAR=foo"} vars := []string{"FOO=bar", "HUGO=cool", "BAR=foo"}
SetEnvVars(&vars, "HUGO", "rocking!", "NEW", "bar") SetEnvVars(&vars, "HUGO", "rocking!", "NEW", "bar")
assert.Equal([]string{"FOO=bar", "HUGO=rocking!", "BAR=foo", "NEW=bar"}, vars) c.Assert(vars, qt.DeepEquals, []string{"FOO=bar", "HUGO=rocking!", "BAR=foo", "NEW=bar"})
key, val := SplitEnvVar("HUGO=rocks") key, val := SplitEnvVar("HUGO=rocks")
assert.Equal("HUGO", key) c.Assert(key, qt.Equals, "HUGO")
assert.Equal("rocks", val) c.Assert(val, qt.Equals, "rocks")
} }

View file

@ -16,13 +16,13 @@ package privacy
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestDecodeConfigFromTOML(t *testing.T) { func TestDecodeConfigFromTOML(t *testing.T) {
assert := require.New(t) c := qt.New(t)
tomlConfig := ` tomlConfig := `
@ -52,30 +52,27 @@ privacyEnhanced = true
simple = true simple = true
` `
cfg, err := config.FromConfigString(tomlConfig, "toml") cfg, err := config.FromConfigString(tomlConfig, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
pc, err := DecodeConfig(cfg) pc, err := DecodeConfig(cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(pc) c.Assert(pc, qt.Not(qt.IsNil))
got := []bool{
pc.Disqus.Disable, pc.GoogleAnalytics.Disable,
pc.GoogleAnalytics.RespectDoNotTrack, pc.GoogleAnalytics.AnonymizeIP,
pc.GoogleAnalytics.UseSessionStorage, pc.Instagram.Disable,
pc.Instagram.Simple, pc.Twitter.Disable, pc.Twitter.EnableDNT,
pc.Twitter.Simple, pc.Vimeo.Disable, pc.Vimeo.Simple,
pc.YouTube.PrivacyEnhanced, pc.YouTube.Disable,
}
c.Assert(got, qt.All(qt.Equals), true)
assert.True(pc.Disqus.Disable)
assert.True(pc.GoogleAnalytics.Disable)
assert.True(pc.GoogleAnalytics.RespectDoNotTrack)
assert.True(pc.GoogleAnalytics.AnonymizeIP)
assert.True(pc.GoogleAnalytics.UseSessionStorage)
assert.True(pc.Instagram.Disable)
assert.True(pc.Instagram.Simple)
assert.True(pc.Twitter.Disable)
assert.True(pc.Twitter.EnableDNT)
assert.True(pc.Twitter.Simple)
assert.True(pc.Vimeo.Disable)
assert.True(pc.Vimeo.Simple)
assert.True(pc.YouTube.PrivacyEnhanced)
assert.True(pc.YouTube.Disable)
} }
func TestDecodeConfigFromTOMLCaseInsensitive(t *testing.T) { func TestDecodeConfigFromTOMLCaseInsensitive(t *testing.T) {
assert := require.New(t) c := qt.New(t)
tomlConfig := ` tomlConfig := `
@ -86,19 +83,19 @@ someOtherValue = "foo"
PrivacyENhanced = true PrivacyENhanced = true
` `
cfg, err := config.FromConfigString(tomlConfig, "toml") cfg, err := config.FromConfigString(tomlConfig, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
pc, err := DecodeConfig(cfg) pc, err := DecodeConfig(cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(pc) c.Assert(pc, qt.Not(qt.IsNil))
assert.True(pc.YouTube.PrivacyEnhanced) c.Assert(pc.YouTube.PrivacyEnhanced, qt.Equals, true)
} }
func TestDecodeConfigDefault(t *testing.T) { func TestDecodeConfigDefault(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pc, err := DecodeConfig(viper.New()) pc, err := DecodeConfig(viper.New())
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(pc) c.Assert(pc, qt.Not(qt.IsNil))
assert.False(pc.YouTube.PrivacyEnhanced) c.Assert(pc.YouTube.PrivacyEnhanced, qt.Equals, false)
} }

View file

@ -16,13 +16,13 @@ package services
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestDecodeConfigFromTOML(t *testing.T) { func TestDecodeConfigFromTOML(t *testing.T) {
assert := require.New(t) c := qt.New(t)
tomlConfig := ` tomlConfig := `
@ -39,31 +39,31 @@ disableInlineCSS = true
disableInlineCSS = true disableInlineCSS = true
` `
cfg, err := config.FromConfigString(tomlConfig, "toml") cfg, err := config.FromConfigString(tomlConfig, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
config, err := DecodeConfig(cfg) config, err := DecodeConfig(cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(config) c.Assert(config, qt.Not(qt.IsNil))
assert.Equal("DS", config.Disqus.Shortname) c.Assert(config.Disqus.Shortname, qt.Equals, "DS")
assert.Equal("ga_id", config.GoogleAnalytics.ID) c.Assert(config.GoogleAnalytics.ID, qt.Equals, "ga_id")
assert.True(config.Instagram.DisableInlineCSS) c.Assert(config.Instagram.DisableInlineCSS, qt.Equals, true)
} }
// Support old root-level GA settings etc. // Support old root-level GA settings etc.
func TestUseSettingsFromRootIfSet(t *testing.T) { func TestUseSettingsFromRootIfSet(t *testing.T) {
assert := require.New(t) c := qt.New(t)
cfg := viper.New() cfg := viper.New()
cfg.Set("disqusShortname", "root_short") cfg.Set("disqusShortname", "root_short")
cfg.Set("googleAnalytics", "ga_root") cfg.Set("googleAnalytics", "ga_root")
config, err := DecodeConfig(cfg) config, err := DecodeConfig(cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(config) c.Assert(config, qt.Not(qt.IsNil))
assert.Equal("root_short", config.Disqus.Shortname) c.Assert(config.Disqus.Shortname, qt.Equals, "root_short")
assert.Equal("ga_root", config.GoogleAnalytics.ID) c.Assert(config.GoogleAnalytics.ID, qt.Equals, "ga_root")
} }

View file

@ -27,11 +27,11 @@ import (
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/create"
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestNewContent(t *testing.T) { func TestNewContent(t *testing.T) {
@ -62,25 +62,25 @@ func TestNewContent(t *testing.T) {
"{{</* comment */>}}\n{{%/* comment */%}}"}}, // shortcodes "{{</* comment */>}}\n{{%/* comment */%}}"}}, // shortcodes
} }
for i, c := range cases { for i, cas := range cases {
c := c cas := cas
t.Run(fmt.Sprintf("%s-%d", c.kind, i), func(t *testing.T) { t.Run(fmt.Sprintf("%s-%d", cas.kind, i), func(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
mm := afero.NewMemMapFs() mm := afero.NewMemMapFs()
assert.NoError(initFs(mm)) c.Assert(initFs(mm), qt.IsNil)
cfg, fs := newTestCfg(assert, mm) cfg, fs := newTestCfg(c, mm)
h, err := hugolib.NewHugoSites(deps.DepsCfg{Cfg: cfg, Fs: fs}) h, err := hugolib.NewHugoSites(deps.DepsCfg{Cfg: cfg, Fs: fs})
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NoError(create.NewContent(h, c.kind, c.path)) c.Assert(create.NewContent(h, cas.kind, cas.path), qt.IsNil)
fname := filepath.FromSlash(c.path) fname := filepath.FromSlash(cas.path)
if !strings.HasPrefix(fname, "content") { if !strings.HasPrefix(fname, "content") {
fname = filepath.Join("content", fname) fname = filepath.Join("content", fname)
} }
content := readFileFromFs(t, fs.Source, fname) content := readFileFromFs(t, fs.Source, fname)
for _, v := range c.expected { for _, v := range cas.expected {
found := strings.Contains(content, v) found := strings.Contains(content, v)
if !found { if !found {
t.Fatalf("[%d] %q missing from output:\n%q", i, v, content) t.Fatalf("[%d] %q missing from output:\n%q", i, v, content)
@ -93,13 +93,13 @@ func TestNewContent(t *testing.T) {
func TestNewContentFromDir(t *testing.T) { func TestNewContentFromDir(t *testing.T) {
mm := afero.NewMemMapFs() mm := afero.NewMemMapFs()
assert := require.New(t) c := qt.New(t)
archetypeDir := filepath.Join("archetypes", "my-bundle") archetypeDir := filepath.Join("archetypes", "my-bundle")
assert.NoError(mm.MkdirAll(archetypeDir, 0755)) c.Assert(mm.MkdirAll(archetypeDir, 0755), qt.IsNil)
archetypeThemeDir := filepath.Join("themes", "mytheme", "archetypes", "my-theme-bundle") archetypeThemeDir := filepath.Join("themes", "mytheme", "archetypes", "my-theme-bundle")
assert.NoError(mm.MkdirAll(archetypeThemeDir, 0755)) c.Assert(mm.MkdirAll(archetypeThemeDir, 0755), qt.IsNil)
contentFile := ` contentFile := `
File: %s File: %s
@ -108,38 +108,38 @@ Name: {{ replace .Name "-" " " | title }}
i18n: {{ T "hugo" }} i18n: {{ T "hugo" }}
` `
assert.NoError(afero.WriteFile(mm, filepath.Join(archetypeDir, "index.md"), []byte(fmt.Sprintf(contentFile, "index.md")), 0755)) c.Assert(afero.WriteFile(mm, filepath.Join(archetypeDir, "index.md"), []byte(fmt.Sprintf(contentFile, "index.md")), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, filepath.Join(archetypeDir, "index.nn.md"), []byte(fmt.Sprintf(contentFile, "index.nn.md")), 0755)) c.Assert(afero.WriteFile(mm, filepath.Join(archetypeDir, "index.nn.md"), []byte(fmt.Sprintf(contentFile, "index.nn.md")), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, filepath.Join(archetypeDir, "pages", "bio.md"), []byte(fmt.Sprintf(contentFile, "bio.md")), 0755)) c.Assert(afero.WriteFile(mm, filepath.Join(archetypeDir, "pages", "bio.md"), []byte(fmt.Sprintf(contentFile, "bio.md")), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, filepath.Join(archetypeDir, "resources", "hugo1.json"), []byte(`hugo1: {{ printf "no template handling in here" }}`), 0755)) c.Assert(afero.WriteFile(mm, filepath.Join(archetypeDir, "resources", "hugo1.json"), []byte(`hugo1: {{ printf "no template handling in here" }}`), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, filepath.Join(archetypeDir, "resources", "hugo2.xml"), []byte(`hugo2: {{ printf "no template handling in here" }}`), 0755)) c.Assert(afero.WriteFile(mm, filepath.Join(archetypeDir, "resources", "hugo2.xml"), []byte(`hugo2: {{ printf "no template handling in here" }}`), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, filepath.Join(archetypeThemeDir, "index.md"), []byte(fmt.Sprintf(contentFile, "index.md")), 0755)) c.Assert(afero.WriteFile(mm, filepath.Join(archetypeThemeDir, "index.md"), []byte(fmt.Sprintf(contentFile, "index.md")), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, filepath.Join(archetypeThemeDir, "resources", "hugo1.json"), []byte(`hugo1: {{ printf "no template handling in here" }}`), 0755)) c.Assert(afero.WriteFile(mm, filepath.Join(archetypeThemeDir, "resources", "hugo1.json"), []byte(`hugo1: {{ printf "no template handling in here" }}`), 0755), qt.IsNil)
assert.NoError(initFs(mm)) c.Assert(initFs(mm), qt.IsNil)
cfg, fs := newTestCfg(assert, mm) cfg, fs := newTestCfg(c, mm)
h, err := hugolib.NewHugoSites(deps.DepsCfg{Cfg: cfg, Fs: fs}) h, err := hugolib.NewHugoSites(deps.DepsCfg{Cfg: cfg, Fs: fs})
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(2, len(h.Sites)) c.Assert(len(h.Sites), qt.Equals, 2)
assert.NoError(create.NewContent(h, "my-bundle", "post/my-post")) c.Assert(create.NewContent(h, "my-bundle", "post/my-post"), qt.IsNil)
assertContains(assert, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/resources/hugo1.json")), `hugo1: {{ printf "no template handling in here" }}`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/resources/hugo1.json")), `hugo1: {{ printf "no template handling in here" }}`)
assertContains(assert, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/resources/hugo2.xml")), `hugo2: {{ printf "no template handling in here" }}`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/resources/hugo2.xml")), `hugo2: {{ printf "no template handling in here" }}`)
// Content files should get the correct site context. // Content files should get the correct site context.
// TODO(bep) archetype check i18n // TODO(bep) archetype check i18n
assertContains(assert, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/index.md")), `File: index.md`, `Site Lang: en`, `Name: My Post`, `i18n: Hugo Rocks!`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/index.md")), `File: index.md`, `Site Lang: en`, `Name: My Post`, `i18n: Hugo Rocks!`)
assertContains(assert, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/index.nn.md")), `File: index.nn.md`, `Site Lang: nn`, `Name: My Post`, `i18n: Hugo Rokkar!`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/index.nn.md")), `File: index.nn.md`, `Site Lang: nn`, `Name: My Post`, `i18n: Hugo Rokkar!`)
assertContains(assert, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/pages/bio.md")), `File: bio.md`, `Site Lang: en`, `Name: My Post`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-post/pages/bio.md")), `File: bio.md`, `Site Lang: en`, `Name: My Post`)
assert.NoError(create.NewContent(h, "my-theme-bundle", "post/my-theme-post")) c.Assert(create.NewContent(h, "my-theme-bundle", "post/my-theme-post"), qt.IsNil)
assertContains(assert, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/index.md")), `File: index.md`, `Site Lang: en`, `Name: My Theme Post`, `i18n: Hugo Rocks!`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/index.md")), `File: index.md`, `Site Lang: en`, `Name: My Theme Post`, `i18n: Hugo Rocks!`)
assertContains(assert, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/resources/hugo1.json")), `hugo1: {{ printf "no template handling in here" }}`) cContains(c, readFileFromFs(t, fs.Source, filepath.Join("content", "post/my-theme-post/resources/hugo1.json")), `hugo1: {{ printf "no template handling in here" }}`)
} }
@ -221,9 +221,9 @@ Some text.
return nil return nil
} }
func assertContains(assert *require.Assertions, v interface{}, matches ...string) { func cContains(c *qt.C, v interface{}, matches ...string) {
for _, m := range matches { for _, m := range matches {
assert.Contains(v, m) c.Assert(v, qt.Contains, m)
} }
} }
@ -247,7 +247,7 @@ func readFileFromFs(t *testing.T, fs afero.Fs, filename string) string {
return string(b) return string(b)
} }
func newTestCfg(assert *require.Assertions, mm afero.Fs) (*viper.Viper, *hugofs.Fs) { func newTestCfg(c *qt.C, mm afero.Fs) (*viper.Viper, *hugofs.Fs) {
cfg := ` cfg := `
@ -270,15 +270,15 @@ contentDir = "content_nn"
mm.MkdirAll(filepath.FromSlash("themes/mytheme"), 0777) mm.MkdirAll(filepath.FromSlash("themes/mytheme"), 0777)
assert.NoError(afero.WriteFile(mm, filepath.Join("i18n", "en.toml"), []byte(`[hugo] c.Assert(afero.WriteFile(mm, filepath.Join("i18n", "en.toml"), []byte(`[hugo]
other = "Hugo Rocks!"`), 0755)) other = "Hugo Rocks!"`), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, filepath.Join("i18n", "nn.toml"), []byte(`[hugo] c.Assert(afero.WriteFile(mm, filepath.Join("i18n", "nn.toml"), []byte(`[hugo]
other = "Hugo Rokkar!"`), 0755)) other = "Hugo Rokkar!"`), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(mm, "config.toml", []byte(cfg), 0755)) c.Assert(afero.WriteFile(mm, "config.toml", []byte(cfg), 0755), qt.IsNil)
v, _, err := hugolib.LoadConfig(hugolib.ConfigSourceDescriptor{Fs: mm, Filename: "config.toml"}) v, _, err := hugolib.LoadConfig(hugolib.ConfigSourceDescriptor{Fs: mm, Filename: "config.toml"})
assert.NoError(err) c.Assert(err, qt.IsNil)
return v, hugofs.NewFrom(mm, v) return v, hugofs.NewFrom(mm, v)

View file

@ -17,13 +17,13 @@ import (
"fmt" "fmt"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestDecodeConfigFromTOML(t *testing.T) { func TestDecodeConfigFromTOML(t *testing.T) {
assert := require.New(t) c := qt.New(t)
tomlConfig := ` tomlConfig := `
@ -77,42 +77,42 @@ gzip = true
force = true force = true
` `
cfg, err := config.FromConfigString(tomlConfig, "toml") cfg, err := config.FromConfigString(tomlConfig, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
dcfg, err := decodeConfig(cfg) dcfg, err := decodeConfig(cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
// Order. // Order.
assert.Equal(2, len(dcfg.Order)) c.Assert(len(dcfg.Order), qt.Equals, 2)
assert.Equal("o1", dcfg.Order[0]) c.Assert(dcfg.Order[0], qt.Equals, "o1")
assert.Equal("o2", dcfg.Order[1]) c.Assert(dcfg.Order[1], qt.Equals, "o2")
assert.Equal(2, len(dcfg.ordering)) c.Assert(len(dcfg.ordering), qt.Equals, 2)
// Targets. // Targets.
assert.Equal(3, len(dcfg.Targets)) c.Assert(len(dcfg.Targets), qt.Equals, 3)
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
tgt := dcfg.Targets[i] tgt := dcfg.Targets[i]
assert.Equal(fmt.Sprintf("name%d", i), tgt.Name) c.Assert(tgt.Name, qt.Equals, fmt.Sprintf("name%d", i))
assert.Equal(fmt.Sprintf("url%d", i), tgt.URL) c.Assert(tgt.URL, qt.Equals, fmt.Sprintf("url%d", i))
assert.Equal(fmt.Sprintf("cdn%d", i), tgt.CloudFrontDistributionID) c.Assert(tgt.CloudFrontDistributionID, qt.Equals, fmt.Sprintf("cdn%d", i))
} }
// Matchers. // Matchers.
assert.Equal(3, len(dcfg.Matchers)) c.Assert(len(dcfg.Matchers), qt.Equals, 3)
for i := 0; i < 3; i++ { for i := 0; i < 3; i++ {
m := dcfg.Matchers[i] m := dcfg.Matchers[i]
assert.Equal(fmt.Sprintf("^pattern%d$", i), m.Pattern) c.Assert(m.Pattern, qt.Equals, fmt.Sprintf("^pattern%d$", i))
assert.NotNil(m.re) c.Assert(m.re, qt.Not(qt.IsNil))
assert.Equal(fmt.Sprintf("cachecontrol%d", i), m.CacheControl) c.Assert(m.CacheControl, qt.Equals, fmt.Sprintf("cachecontrol%d", i))
assert.Equal(fmt.Sprintf("contentencoding%d", i), m.ContentEncoding) c.Assert(m.ContentEncoding, qt.Equals, fmt.Sprintf("contentencoding%d", i))
assert.Equal(fmt.Sprintf("contenttype%d", i), m.ContentType) c.Assert(m.ContentType, qt.Equals, fmt.Sprintf("contenttype%d", i))
assert.Equal(i != 0, m.Gzip) c.Assert(m.Gzip, qt.Equals, i != 0)
assert.Equal(i != 0, m.Force) c.Assert(m.Force, qt.Equals, i != 0)
} }
} }
func TestInvalidOrderingPattern(t *testing.T) { func TestInvalidOrderingPattern(t *testing.T) {
assert := require.New(t) c := qt.New(t)
tomlConfig := ` tomlConfig := `
@ -122,14 +122,14 @@ someOtherValue = "foo"
order = ["["] # invalid regular expression order = ["["] # invalid regular expression
` `
cfg, err := config.FromConfigString(tomlConfig, "toml") cfg, err := config.FromConfigString(tomlConfig, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
_, err = decodeConfig(cfg) _, err = decodeConfig(cfg)
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
} }
func TestInvalidMatcherPattern(t *testing.T) { func TestInvalidMatcherPattern(t *testing.T) {
assert := require.New(t) c := qt.New(t)
tomlConfig := ` tomlConfig := `
@ -140,17 +140,17 @@ someOtherValue = "foo"
Pattern = "[" # invalid regular expression Pattern = "[" # invalid regular expression
` `
cfg, err := config.FromConfigString(tomlConfig, "toml") cfg, err := config.FromConfigString(tomlConfig, "toml")
assert.NoError(err) c.Assert(err, qt.IsNil)
_, err = decodeConfig(cfg) _, err = decodeConfig(cfg)
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
} }
func TestDecodeConfigDefault(t *testing.T) { func TestDecodeConfigDefault(t *testing.T) {
assert := require.New(t) c := qt.New(t)
dcfg, err := decodeConfig(viper.New()) dcfg, err := decodeConfig(viper.New())
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(0, len(dcfg.Targets)) c.Assert(len(dcfg.Targets), qt.Equals, 0)
assert.Equal(0, len(dcfg.Matchers)) c.Assert(len(dcfg.Matchers), qt.Equals, 0)
} }

5
go.mod
View file

@ -5,7 +5,6 @@ require (
github.com/BurntSushi/toml v0.3.1 github.com/BurntSushi/toml v0.3.1
github.com/PuerkitoBio/purell v1.1.0 github.com/PuerkitoBio/purell v1.1.0
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
github.com/alecthomas/assert v0.0.0-20170929043011-405dbfeb8e38
github.com/alecthomas/chroma v0.6.4 github.com/alecthomas/chroma v0.6.4
github.com/alecthomas/repr v0.0.0-20181024024818-d37bc2a10ba1 // indirect github.com/alecthomas/repr v0.0.0-20181024024818-d37bc2a10ba1 // indirect
github.com/armon/go-radix v1.0.0 github.com/armon/go-radix v1.0.0
@ -17,6 +16,7 @@ require (
github.com/dustin/go-humanize v1.0.0 github.com/dustin/go-humanize v1.0.0
github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385 github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385
github.com/fortytw2/leaktest v1.3.0 github.com/fortytw2/leaktest v1.3.0
github.com/frankban/quicktest v1.4.1
github.com/fsnotify/fsnotify v1.4.7 github.com/fsnotify/fsnotify v1.4.7
github.com/gobwas/glob v0.2.3 github.com/gobwas/glob v0.2.3
github.com/gohugoio/testmodBuilder/mods v0.0.0-20190520184928-c56af20f2e95 github.com/gohugoio/testmodBuilder/mods v0.0.0-20190520184928-c56af20f2e95
@ -49,7 +49,6 @@ require (
github.com/spf13/jwalterweatherman v1.1.0 github.com/spf13/jwalterweatherman v1.1.0
github.com/spf13/pflag v1.0.3 github.com/spf13/pflag v1.0.3
github.com/spf13/viper v1.4.0 github.com/spf13/viper v1.4.0
github.com/stretchr/testify v1.3.0
github.com/tdewolff/minify/v2 v2.3.7 github.com/tdewolff/minify/v2 v2.3.7
github.com/yosssi/ace v0.0.5 github.com/yosssi/ace v0.0.5
go.opencensus.io v0.22.0 // indirect go.opencensus.io v0.22.0 // indirect
@ -68,4 +67,4 @@ require (
replace github.com/markbates/inflect => github.com/markbates/inflect v0.0.0-20171215194931-a12c3aec81a6 replace github.com/markbates/inflect => github.com/markbates/inflect v0.0.0-20171215194931-a12c3aec81a6
go 1.13 go 1.12

2
go.sum
View file

@ -103,6 +103,8 @@ github.com/fortytw2/leaktest v1.2.0 h1:cj6GCiwJDH7l3tMHLjZDo0QqPtrXJiWSI9JgpeQKw
github.com/fortytw2/leaktest v1.2.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/fortytw2/leaktest v1.2.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
github.com/frankban/quicktest v1.4.1 h1:Wv2VwvNn73pAdFIVUQRXYDFp31lXKbqblIXo/Q5GPSg=
github.com/frankban/quicktest v1.4.1/go.mod h1:36zfPVQyHxymz4cH7wlDmVwDrJuljRB60qkgn7rorfQ=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=

View file

@ -18,8 +18,8 @@ import (
"regexp" "regexp"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
// Renders a codeblock using Blackfriday // Renders a codeblock using Blackfriday
@ -43,7 +43,7 @@ func (c ContentSpec) renderWithMmark(input string) string {
} }
func TestCodeFence(t *testing.T) { func TestCodeFence(t *testing.T) {
assert := require.New(t) c := qt.New(t)
type test struct { type test struct {
enabled bool enabled bool
@ -64,10 +64,10 @@ func TestCodeFence(t *testing.T) {
v.Set("pygmentsCodeFences", d.enabled) v.Set("pygmentsCodeFences", d.enabled)
v.Set("pygmentsUseClassic", useClassic) v.Set("pygmentsUseClassic", useClassic)
c, err := NewContentSpec(v) cs, err := NewContentSpec(v)
assert.NoError(err) c.Assert(err, qt.IsNil)
result := c.render(d.input) result := cs.render(d.input)
expectedRe, err := regexp.Compile(d.expected) expectedRe, err := regexp.Compile(d.expected)
@ -80,7 +80,7 @@ func TestCodeFence(t *testing.T) {
t.Errorf("Test %d failed. BlackFriday enabled:%t, Expected:\n%q got:\n%q", i, d.enabled, d.expected, result) t.Errorf("Test %d failed. BlackFriday enabled:%t, Expected:\n%q got:\n%q", i, d.enabled, d.expected, result)
} }
result = c.renderWithMmark(d.input) result = cs.renderWithMmark(d.input)
matched = expectedRe.MatchString(result) matched = expectedRe.MatchString(result)
if !matched { if !matched {
t.Errorf("Test %d failed. Mmark enabled:%t, Expected:\n%q got:\n%q", i, d.enabled, d.expected, result) t.Errorf("Test %d failed. Mmark enabled:%t, Expected:\n%q got:\n%q", i, d.enabled, d.expected, result)

View file

@ -21,10 +21,9 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
qt "github.com/frankban/quicktest"
"github.com/miekg/mmark" "github.com/miekg/mmark"
"github.com/russross/blackfriday" "github.com/russross/blackfriday"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
const tstHTMLContent = "<!DOCTYPE html><html><head><script src=\"http://two/foobar.js\"></script></head><body><nav><ul><li hugo-nav=\"section_0\"></li><li hugo-nav=\"section_1\"></li></ul></nav><article>content <a href=\"http://two/foobar\">foobar</a>. Follow up</article><p>This is some text.<br>And some more.</p></body></html>" const tstHTMLContent = "<!DOCTYPE html><html><head><script src=\"http://two/foobar.js\"></script></head><body><nav><ul><li hugo-nav=\"section_0\"></li><li hugo-nav=\"section_1\"></li></ul></nav><article>content <a href=\"http://two/foobar\">foobar</a>. Follow up</article><p>This is some text.<br>And some more.</p></body></html>"
@ -90,17 +89,19 @@ func BenchmarkStripHTML(b *testing.B) {
} }
func TestStripEmptyNav(t *testing.T) { func TestStripEmptyNav(t *testing.T) {
c := qt.New(t)
cleaned := stripEmptyNav([]byte("do<nav>\n</nav>\n\nbedobedo")) cleaned := stripEmptyNav([]byte("do<nav>\n</nav>\n\nbedobedo"))
assert.Equal(t, []byte("dobedobedo"), cleaned) c.Assert(cleaned, qt.DeepEquals, []byte("dobedobedo"))
} }
func TestBytesToHTML(t *testing.T) { func TestBytesToHTML(t *testing.T) {
assert.Equal(t, template.HTML("dobedobedo"), BytesToHTML([]byte("dobedobedo"))) c := qt.New(t)
c.Assert(BytesToHTML([]byte("dobedobedo")), qt.Equals, template.HTML("dobedobedo"))
} }
func TestNewContentSpec(t *testing.T) { func TestNewContentSpec(t *testing.T) {
cfg := viper.New() cfg := viper.New()
assert := require.New(t) c := qt.New(t)
cfg.Set("summaryLength", 32) cfg.Set("summaryLength", 32)
cfg.Set("buildFuture", true) cfg.Set("buildFuture", true)
@ -109,11 +110,11 @@ func TestNewContentSpec(t *testing.T) {
spec, err := NewContentSpec(cfg) spec, err := NewContentSpec(cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(32, spec.summaryLength) c.Assert(spec.summaryLength, qt.Equals, 32)
assert.True(spec.BuildFuture) c.Assert(spec.BuildFuture, qt.Equals, true)
assert.True(spec.BuildExpired) c.Assert(spec.BuildExpired, qt.Equals, true)
assert.True(spec.BuildDrafts) c.Assert(spec.BuildDrafts, qt.Equals, true)
} }

View file

@ -19,9 +19,8 @@ import (
"strings" "strings"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGuessType(t *testing.T) { func TestGuessType(t *testing.T) {
@ -188,6 +187,7 @@ func TestSliceToLower(t *testing.T) {
} }
func TestReaderContains(t *testing.T) { func TestReaderContains(t *testing.T) {
c := qt.New(t)
for i, this := range append(containsBenchTestData, containsAdditionalTestData...) { for i, this := range append(containsBenchTestData, containsAdditionalTestData...) {
result := ReaderContains(strings.NewReader(this.v1), this.v2) result := ReaderContains(strings.NewReader(this.v1), this.v2)
if result != this.expect { if result != this.expect {
@ -195,21 +195,21 @@ func TestReaderContains(t *testing.T) {
} }
} }
assert.False(t, ReaderContains(nil, []byte("a"))) c.Assert(ReaderContains(nil, []byte("a")), qt.Equals, false)
assert.False(t, ReaderContains(nil, nil)) c.Assert(ReaderContains(nil, nil), qt.Equals, false)
} }
func TestGetTitleFunc(t *testing.T) { func TestGetTitleFunc(t *testing.T) {
title := "somewhere over the rainbow" title := "somewhere over the rainbow"
assert := require.New(t) c := qt.New(t)
assert.Equal("Somewhere Over The Rainbow", GetTitleFunc("go")(title)) c.Assert(GetTitleFunc("go")(title), qt.Equals, "Somewhere Over The Rainbow")
assert.Equal("Somewhere over the Rainbow", GetTitleFunc("chicago")(title), "Chicago style") c.Assert(GetTitleFunc("chicago")(title), qt.Equals, "Somewhere over the Rainbow")
assert.Equal("Somewhere over the Rainbow", GetTitleFunc("Chicago")(title), "Chicago style") c.Assert(GetTitleFunc("Chicago")(title), qt.Equals, "Somewhere over the Rainbow")
assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("ap")(title), "AP style") c.Assert(GetTitleFunc("ap")(title), qt.Equals, "Somewhere Over the Rainbow")
assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("ap")(title), "AP style") c.Assert(GetTitleFunc("ap")(title), qt.Equals, "Somewhere Over the Rainbow")
assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("")(title), "AP style") c.Assert(GetTitleFunc("")(title), qt.Equals, "Somewhere Over the Rainbow")
assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("unknown")(title), "AP style") c.Assert(GetTitleFunc("unknown")(title), qt.Equals, "Somewhere Over the Rainbow")
} }
@ -244,19 +244,20 @@ func TestUniqueStringsReuse(t *testing.T) {
} }
func TestUniqueStringsSorted(t *testing.T) { func TestUniqueStringsSorted(t *testing.T) {
assert := require.New(t) c := qt.New(t)
in := []string{"a", "a", "b", "c", "b", "", "a", "", "d"} in := []string{"a", "a", "b", "c", "b", "", "a", "", "d"}
output := UniqueStringsSorted(in) output := UniqueStringsSorted(in)
expected := []string{"", "a", "b", "c", "d"} expected := []string{"", "a", "b", "c", "d"}
assert.Equal(expected, output) c.Assert(output, qt.DeepEquals, expected)
assert.Nil(UniqueStringsSorted(nil)) c.Assert(UniqueStringsSorted(nil), qt.IsNil)
} }
func TestFindAvailablePort(t *testing.T) { func TestFindAvailablePort(t *testing.T) {
c := qt.New(t)
addr, err := FindAvailablePort() addr, err := FindAvailablePort()
assert.Nil(t, err) c.Assert(err, qt.IsNil)
assert.NotNil(t, addr) c.Assert(addr, qt.Not(qt.IsNil))
assert.True(t, addr.Port > 0) c.Assert(addr.Port > 0, qt.Equals, true)
} }
func TestFastMD5FromFile(t *testing.T) { func TestFastMD5FromFile(t *testing.T) {
@ -278,17 +279,17 @@ func TestFastMD5FromFile(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
req := require.New(t) c := qt.New(t)
sf1, err := fs.Open("small.txt") sf1, err := fs.Open("small.txt")
req.NoError(err) c.Assert(err, qt.IsNil)
sf2, err := fs.Open("small2.txt") sf2, err := fs.Open("small2.txt")
req.NoError(err) c.Assert(err, qt.IsNil)
bf1, err := fs.Open("bigger.txt") bf1, err := fs.Open("bigger.txt")
req.NoError(err) c.Assert(err, qt.IsNil)
bf2, err := fs.Open("bigger2.txt") bf2, err := fs.Open("bigger2.txt")
req.NoError(err) c.Assert(err, qt.IsNil)
defer sf1.Close() defer sf1.Close()
defer sf2.Close() defer sf2.Close()
@ -296,24 +297,24 @@ func TestFastMD5FromFile(t *testing.T) {
defer bf2.Close() defer bf2.Close()
m1, err := MD5FromFileFast(sf1) m1, err := MD5FromFileFast(sf1)
req.NoError(err) c.Assert(err, qt.IsNil)
req.Equal("e9c8989b64b71a88b4efb66ad05eea96", m1) c.Assert(m1, qt.Equals, "e9c8989b64b71a88b4efb66ad05eea96")
m2, err := MD5FromFileFast(sf2) m2, err := MD5FromFileFast(sf2)
req.NoError(err) c.Assert(err, qt.IsNil)
req.NotEqual(m1, m2) c.Assert(m2, qt.Not(qt.Equals), m1)
m3, err := MD5FromFileFast(bf1) m3, err := MD5FromFileFast(bf1)
req.NoError(err) c.Assert(err, qt.IsNil)
req.NotEqual(m2, m3) c.Assert(m3, qt.Not(qt.Equals), m2)
m4, err := MD5FromFileFast(bf2) m4, err := MD5FromFileFast(bf2)
req.NoError(err) c.Assert(err, qt.IsNil)
req.NotEqual(m3, m4) c.Assert(m4, qt.Not(qt.Equals), m3)
m5, err := MD5FromReader(bf2) m5, err := MD5FromReader(bf2)
req.NoError(err) c.Assert(err, qt.IsNil)
req.NotEqual(m4, m5) c.Assert(m5, qt.Not(qt.Equals), m4)
} }
func BenchmarkMD5FromFileFast(b *testing.B) { func BenchmarkMD5FromFileFast(b *testing.B) {

View file

@ -27,7 +27,7 @@ import (
"github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/langs"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/spf13/afero" "github.com/spf13/afero"
@ -35,6 +35,7 @@ import (
) )
func TestMakePath(t *testing.T) { func TestMakePath(t *testing.T) {
c := qt.New(t)
tests := []struct { tests := []struct {
input string input string
expected string expected string
@ -61,7 +62,7 @@ func TestMakePath(t *testing.T) {
l := langs.NewDefaultLanguage(v) l := langs.NewDefaultLanguage(v)
p, err := NewPathSpec(hugofs.NewMem(v), l, nil) p, err := NewPathSpec(hugofs.NewMem(v), l, nil)
require.NoError(t, err) c.Assert(err, qt.IsNil)
output := p.MakePath(test.input) output := p.MakePath(test.input)
if output != test.expected { if output != test.expected {
@ -547,8 +548,8 @@ func TestAbsPathify(t *testing.T) {
} }
func TestExtNoDelimiter(t *testing.T) { func TestExtNoDelimiter(t *testing.T) {
assert := require.New(t) c := qt.New(t)
assert.Equal("json", ExtNoDelimiter(filepath.FromSlash("/my/data.json"))) c.Assert(ExtNoDelimiter(filepath.FromSlash("/my/data.json")), qt.Equals, "json")
} }
func TestFilename(t *testing.T) { func TestFilename(t *testing.T) {
@ -636,11 +637,11 @@ func TestExtractAndGroupRootPaths(t *testing.T) {
result := ExtractAndGroupRootPaths(in) result := ExtractAndGroupRootPaths(in)
assert := require.New(t) c := qt.New(t)
assert.Equal(filepath.FromSlash("[/a/b/{c,e} /c/d/e]"), fmt.Sprint(result)) c.Assert(fmt.Sprint(result), qt.Equals, filepath.FromSlash("[/a/b/{c,e} /c/d/e]"))
// Make sure the original is preserved // Make sure the original is preserved
assert.Equal(inCopy, in) c.Assert(in, qt.DeepEquals, inCopy)
} }

View file

@ -17,13 +17,14 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/langs"
"github.com/stretchr/testify/require"
) )
func TestNewPathSpecFromConfig(t *testing.T) { func TestNewPathSpecFromConfig(t *testing.T) {
c := qt.New(t)
v := newTestCfg() v := newTestCfg()
l := langs.NewLanguage("no", v) l := langs.NewLanguage("no", v)
v.Set("disablePathToLower", true) v.Set("disablePathToLower", true)
@ -44,16 +45,16 @@ func TestNewPathSpecFromConfig(t *testing.T) {
p, err := NewPathSpec(fs, l, nil) p, err := NewPathSpec(fs, l, nil)
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.True(t, p.CanonifyURLs) c.Assert(p.CanonifyURLs, qt.Equals, true)
require.True(t, p.DisablePathToLower) c.Assert(p.DisablePathToLower, qt.Equals, true)
require.True(t, p.RemovePathAccents) c.Assert(p.RemovePathAccents, qt.Equals, true)
require.True(t, p.UglyURLs) c.Assert(p.UglyURLs, qt.Equals, true)
require.Equal(t, "no", p.Language.Lang) c.Assert(p.Language.Lang, qt.Equals, "no")
require.Equal(t, "side", p.PaginatePath) c.Assert(p.PaginatePath, qt.Equals, "side")
require.Equal(t, "http://base.com", p.BaseURL.String()) c.Assert(p.BaseURL.String(), qt.Equals, "http://base.com")
require.Equal(t, "thethemes", p.ThemesDir) c.Assert(p.ThemesDir, qt.Equals, "thethemes")
require.Equal(t, "thework", p.WorkingDir) c.Assert(p.WorkingDir, qt.Equals, "thework")
} }

View file

@ -20,12 +20,12 @@ import (
"github.com/alecthomas/chroma/formatters/html" "github.com/alecthomas/chroma/formatters/html"
qt "github.com/frankban/quicktest"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestParsePygmentsArgs(t *testing.T) { func TestParsePygmentsArgs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
for i, this := range []struct { for i, this := range []struct {
in string in string
@ -46,7 +46,7 @@ func TestParsePygmentsArgs(t *testing.T) {
v.Set("pygmentsStyle", this.pygmentsStyle) v.Set("pygmentsStyle", this.pygmentsStyle)
v.Set("pygmentsUseClasses", this.pygmentsUseClasses) v.Set("pygmentsUseClasses", this.pygmentsUseClasses)
spec, err := NewContentSpec(v) spec, err := NewContentSpec(v)
assert.NoError(err) c.Assert(err, qt.IsNil)
result1, err := spec.createPygmentsOptionsString(this.in) result1, err := spec.createPygmentsOptionsString(this.in)
if b, ok := this.expect1.(bool); ok && !b { if b, ok := this.expect1.(bool); ok && !b {
@ -67,7 +67,7 @@ func TestParsePygmentsArgs(t *testing.T) {
} }
func TestParseDefaultPygmentsArgs(t *testing.T) { func TestParseDefaultPygmentsArgs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
expect := "encoding=utf8,noclasses=false,style=foo" expect := "encoding=utf8,noclasses=false,style=foo"
@ -95,7 +95,7 @@ func TestParseDefaultPygmentsArgs(t *testing.T) {
} }
spec, err := NewContentSpec(v) spec, err := NewContentSpec(v)
assert.NoError(err) c.Assert(err, qt.IsNil)
result, err := spec.createPygmentsOptionsString(this.in) result, err := spec.createPygmentsOptionsString(this.in)
if err != nil { if err != nil {
@ -134,22 +134,22 @@ func formatterChromaInfo(f *html.Formatter) chromaInfo {
} }
func TestChromaHTMLHighlight(t *testing.T) { func TestChromaHTMLHighlight(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := viper.New() v := viper.New()
v.Set("pygmentsUseClasses", true) v.Set("pygmentsUseClasses", true)
spec, err := NewContentSpec(v) spec, err := NewContentSpec(v)
assert.NoError(err) c.Assert(err, qt.IsNil)
result, err := spec.Highlight(`echo "Hello"`, "bash", "") result, err := spec.Highlight(`echo "Hello"`, "bash", "")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Contains(result, `<div class="highlight"><pre class="chroma"><code class="language-bash" data-lang="bash"><span class="nb">echo</span> <span class="s2">&#34;Hello&#34;</span></code></pre></div>`) c.Assert(result, qt.Contains, `<div class="highlight"><pre class="chroma"><code class="language-bash" data-lang="bash"><span class="nb">echo</span> <span class="s2">&#34;Hello&#34;</span></code></pre></div>`)
} }
func TestChromaHTMLFormatterFromOptions(t *testing.T) { func TestChromaHTMLFormatterFromOptions(t *testing.T) {
assert := require.New(t) c := qt.New(t)
for i, this := range []struct { for i, this := range []struct {
in string in string
@ -158,40 +158,40 @@ func TestChromaHTMLFormatterFromOptions(t *testing.T) {
pygmentsOptions string pygmentsOptions string
assert func(c chromaInfo) assert func(c chromaInfo)
}{ }{
{"", "monokai", true, "style=manni,noclasses=true", func(c chromaInfo) { {"", "monokai", true, "style=manni,noclasses=true", func(ci chromaInfo) {
assert.True(c.classes) c.Assert(ci.classes, qt.Equals, true)
assert.False(c.lineNumbers) c.Assert(ci.lineNumbers, qt.Equals, false)
assert.Equal(0, c.highlightRangesLen) c.Assert(ci.highlightRangesLen, qt.Equals, 0)
}}, }},
{"", nil, nil, "style=monokai,noclasses=false", func(c chromaInfo) { {"", nil, nil, "style=monokai,noclasses=false", func(ci chromaInfo) {
assert.True(c.classes) c.Assert(ci.classes, qt.Equals, true)
}}, }},
{"linenos=sure,hl_lines=1 2 3", nil, nil, "style=monokai,noclasses=false", func(c chromaInfo) { {"linenos=sure,hl_lines=1 2 3", nil, nil, "style=monokai,noclasses=false", func(ci chromaInfo) {
assert.True(c.classes) c.Assert(ci.classes, qt.Equals, true)
assert.True(c.lineNumbers) c.Assert(ci.lineNumbers, qt.Equals, true)
assert.Equal(3, c.highlightRangesLen) c.Assert(ci.highlightRangesLen, qt.Equals, 3)
assert.Equal("[[1 1] [2 2] [3 3]]", c.highlightRangesStr) c.Assert(ci.highlightRangesStr, qt.Equals, "[[1 1] [2 2] [3 3]]")
assert.Equal(1, c.baseLineNumber) c.Assert(ci.baseLineNumber, qt.Equals, 1)
}}, }},
{"linenos=inline,hl_lines=1,linenostart=4", nil, nil, "style=monokai,noclasses=false", func(c chromaInfo) { {"linenos=inline,hl_lines=1,linenostart=4", nil, nil, "style=monokai,noclasses=false", func(ci chromaInfo) {
assert.True(c.classes) c.Assert(ci.classes, qt.Equals, true)
assert.True(c.lineNumbers) c.Assert(ci.lineNumbers, qt.Equals, true)
assert.False(c.lineNumbersInTable) c.Assert(ci.lineNumbersInTable, qt.Equals, false)
assert.Equal(1, c.highlightRangesLen) c.Assert(ci.highlightRangesLen, qt.Equals, 1)
// This compansates for https://github.com/alecthomas/chroma/issues/30 // This compansates for https://github.com/alecthomas/chroma/issues/30
assert.Equal("[[4 4]]", c.highlightRangesStr) c.Assert(ci.highlightRangesStr, qt.Equals, "[[4 4]]")
assert.Equal(4, c.baseLineNumber) c.Assert(ci.baseLineNumber, qt.Equals, 4)
}}, }},
{"linenos=table", nil, nil, "style=monokai", func(c chromaInfo) { {"linenos=table", nil, nil, "style=monokai", func(ci chromaInfo) {
assert.True(c.lineNumbers) c.Assert(ci.lineNumbers, qt.Equals, true)
assert.True(c.lineNumbersInTable) c.Assert(ci.lineNumbersInTable, qt.Equals, true)
}}, }},
{"style=monokai,noclasses=false", nil, nil, "style=manni,noclasses=true", func(c chromaInfo) { {"style=monokai,noclasses=false", nil, nil, "style=manni,noclasses=true", func(ci chromaInfo) {
assert.True(c.classes) c.Assert(ci.classes, qt.Equals, true)
}}, }},
{"style=monokai,noclasses=true", "friendly", false, "style=manni,noclasses=false", func(c chromaInfo) { {"style=monokai,noclasses=true", "friendly", false, "style=manni,noclasses=false", func(ci chromaInfo) {
assert.False(c.classes) c.Assert(ci.classes, qt.Equals, false)
}}, }},
} { } {
v := viper.New() v := viper.New()
@ -207,7 +207,7 @@ func TestChromaHTMLFormatterFromOptions(t *testing.T) {
} }
spec, err := NewContentSpec(v) spec, err := NewContentSpec(v)
assert.NoError(err) c.Assert(err, qt.IsNil)
opts, err := spec.parsePygmentsOpts(this.in) opts, err := spec.parsePygmentsOpts(this.in)
if err != nil { if err != nil {
@ -257,7 +257,7 @@ func TestHlLinesToRanges(t *testing.T) {
} }
func BenchmarkChromaHighlight(b *testing.B) { func BenchmarkChromaHighlight(b *testing.B) {
assert := require.New(b) c := qt.New(b)
v := viper.New() v := viper.New()
v.Set("pygmentsstyle", "trac") v.Set("pygmentsstyle", "trac")
@ -289,7 +289,7 @@ func GetTitleFunc(style string) func(s string) string {
` `
spec, err := NewContentSpec(v) spec, err := NewContentSpec(v)
assert.NoError(err) c.Assert(err, qt.IsNil)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_, err := spec.Highlight(code, "go", "linenos=inline,hl_lines=8 15-17") _, err := spec.Highlight(code, "go", "linenos=inline,hl_lines=8 15-17")

View file

@ -14,14 +14,12 @@
package helpers package helpers
import ( import (
"fmt"
"strings" "strings"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/langs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestURLize(t *testing.T) { func TestURLize(t *testing.T) {
@ -111,7 +109,9 @@ func doTestAbsURL(t *testing.T, defaultInSubDir, addLanguage, multilingual bool,
} }
func TestIsAbsURL(t *testing.T) { func TestIsAbsURL(t *testing.T) {
for i, this := range []struct { c := qt.New(t)
for _, this := range []struct {
a string a string
b bool b bool
}{ }{
@ -122,7 +122,7 @@ func TestIsAbsURL(t *testing.T) {
{"/content", false}, {"/content", false},
{"content", false}, {"content", false},
} { } {
require.True(t, IsAbsURL(this.a) == this.b, fmt.Sprintf("Test %d", i)) c.Assert(IsAbsURL(this.a) == this.b, qt.Equals, true)
} }
} }
@ -292,31 +292,33 @@ func TestAddContextRoot(t *testing.T) {
} }
func TestPretty(t *testing.T) { func TestPretty(t *testing.T) {
assert.Equal(t, PrettifyURLPath("/section/name.html"), "/section/name/index.html") c := qt.New(t)
assert.Equal(t, PrettifyURLPath("/section/sub/name.html"), "/section/sub/name/index.html") c.Assert("/section/name/index.html", qt.Equals, PrettifyURLPath("/section/name.html"))
assert.Equal(t, PrettifyURLPath("/section/name/"), "/section/name/index.html") c.Assert("/section/sub/name/index.html", qt.Equals, PrettifyURLPath("/section/sub/name.html"))
assert.Equal(t, PrettifyURLPath("/section/name/index.html"), "/section/name/index.html") c.Assert("/section/name/index.html", qt.Equals, PrettifyURLPath("/section/name/"))
assert.Equal(t, PrettifyURLPath("/index.html"), "/index.html") c.Assert("/section/name/index.html", qt.Equals, PrettifyURLPath("/section/name/index.html"))
assert.Equal(t, PrettifyURLPath("/name.xml"), "/name/index.xml") c.Assert("/index.html", qt.Equals, PrettifyURLPath("/index.html"))
assert.Equal(t, PrettifyURLPath("/"), "/") c.Assert("/name/index.xml", qt.Equals, PrettifyURLPath("/name.xml"))
assert.Equal(t, PrettifyURLPath(""), "/") c.Assert("/", qt.Equals, PrettifyURLPath("/"))
assert.Equal(t, PrettifyURL("/section/name.html"), "/section/name") c.Assert("/", qt.Equals, PrettifyURLPath(""))
assert.Equal(t, PrettifyURL("/section/sub/name.html"), "/section/sub/name") c.Assert("/section/name", qt.Equals, PrettifyURL("/section/name.html"))
assert.Equal(t, PrettifyURL("/section/name/"), "/section/name") c.Assert("/section/sub/name", qt.Equals, PrettifyURL("/section/sub/name.html"))
assert.Equal(t, PrettifyURL("/section/name/index.html"), "/section/name") c.Assert("/section/name", qt.Equals, PrettifyURL("/section/name/"))
assert.Equal(t, PrettifyURL("/index.html"), "/") c.Assert("/section/name", qt.Equals, PrettifyURL("/section/name/index.html"))
assert.Equal(t, PrettifyURL("/name.xml"), "/name/index.xml") c.Assert("/", qt.Equals, PrettifyURL("/index.html"))
assert.Equal(t, PrettifyURL("/"), "/") c.Assert("/name/index.xml", qt.Equals, PrettifyURL("/name.xml"))
assert.Equal(t, PrettifyURL(""), "/") c.Assert("/", qt.Equals, PrettifyURL("/"))
c.Assert("/", qt.Equals, PrettifyURL(""))
} }
func TestUgly(t *testing.T) { func TestUgly(t *testing.T) {
assert.Equal(t, Uglify("/section/name.html"), "/section/name.html") c := qt.New(t)
assert.Equal(t, Uglify("/section/sub/name.html"), "/section/sub/name.html") c.Assert("/section/name.html", qt.Equals, Uglify("/section/name.html"))
assert.Equal(t, Uglify("/section/name/"), "/section/name.html") c.Assert("/section/sub/name.html", qt.Equals, Uglify("/section/sub/name.html"))
assert.Equal(t, Uglify("/section/name/index.html"), "/section/name.html") c.Assert("/section/name.html", qt.Equals, Uglify("/section/name/"))
assert.Equal(t, Uglify("/index.html"), "/index.html") c.Assert("/section/name.html", qt.Equals, Uglify("/section/name/index.html"))
assert.Equal(t, Uglify("/name.xml"), "/name.xml") c.Assert("/index.html", qt.Equals, Uglify("/index.html"))
assert.Equal(t, Uglify("/"), "/") c.Assert("/name.xml", qt.Equals, Uglify("/name.xml"))
assert.Equal(t, Uglify(""), "/") c.Assert("/", qt.Equals, Uglify("/"))
c.Assert("/", qt.Equals, Uglify(""))
} }

92
htesting/hqt/checkers.go Normal file
View file

@ -0,0 +1,92 @@
// Copyright 2019 The Hugo Authors. All rights reserved.
//
// 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 hqt
import (
"errors"
"reflect"
qt "github.com/frankban/quicktest"
"github.com/google/go-cmp/cmp"
)
// IsSameType asserts that got is the same type as want.
var IsSameType qt.Checker = &typeChecker{
argNames: []string{"got", "want"},
}
type argNames []string
func (a argNames) ArgNames() []string {
return a
}
type typeChecker struct {
argNames
}
// Check implements Checker.Check by checking that got and args[0] is of the same type.
func (c *typeChecker) Check(got interface{}, args []interface{}, note func(key string, value interface{})) (err error) {
if want := args[0]; reflect.TypeOf(got) != reflect.TypeOf(want) {
if _, ok := got.(error); ok && want == nil {
return errors.New("got non-nil error")
}
return errors.New("values are not of same type")
}
return nil
}
// DeepAllowUnexported creates an option to allow compare of unexported types
// in the given list of types.
// see https://github.com/google/go-cmp/issues/40#issuecomment-328615283
func DeepAllowUnexported(vs ...interface{}) cmp.Option {
m := make(map[reflect.Type]struct{})
for _, v := range vs {
structTypes(reflect.ValueOf(v), m)
}
var typs []interface{}
for t := range m {
typs = append(typs, reflect.New(t).Elem().Interface())
}
return cmp.AllowUnexported(typs...)
}
func structTypes(v reflect.Value, m map[reflect.Type]struct{}) {
if !v.IsValid() {
return
}
switch v.Kind() {
case reflect.Ptr:
if !v.IsNil() {
structTypes(v.Elem(), m)
}
case reflect.Interface:
if !v.IsNil() {
structTypes(v.Elem(), m)
}
case reflect.Slice, reflect.Array:
for i := 0; i < v.Len(); i++ {
structTypes(v.Index(i), m)
}
case reflect.Map:
for _, k := range v.MapKeys() {
structTypes(v.MapIndex(k), m)
}
case reflect.Struct:
m[v.Type()] = struct{}{}
for i := 0; i < v.NumField(); i++ {
structTypes(v.Field(i), m)
}
}
}

View file

@ -17,33 +17,33 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestIsContentFile(t *testing.T) { func TestIsContentFile(t *testing.T) {
assert := require.New(t) c := qt.New(t)
assert.True(IsContentFile(filepath.FromSlash("my/file.md"))) c.Assert(IsContentFile(filepath.FromSlash("my/file.md")), qt.Equals, true)
assert.True(IsContentFile(filepath.FromSlash("my/file.ad"))) c.Assert(IsContentFile(filepath.FromSlash("my/file.ad")), qt.Equals, true)
assert.False(IsContentFile(filepath.FromSlash("textfile.txt"))) c.Assert(IsContentFile(filepath.FromSlash("textfile.txt")), qt.Equals, false)
assert.True(IsContentExt("md")) c.Assert(IsContentExt("md"), qt.Equals, true)
assert.False(IsContentExt("json")) c.Assert(IsContentExt("json"), qt.Equals, false)
} }
func TestComponentFolders(t *testing.T) { func TestComponentFolders(t *testing.T) {
assert := require.New(t) c := qt.New(t)
// It's important that these are absolutely right and not changed. // It's important that these are absolutely right and not changed.
assert.Equal(len(ComponentFolders), len(componentFoldersSet)) c.Assert(len(componentFoldersSet), qt.Equals, len(ComponentFolders))
assert.True(IsComponentFolder("archetypes")) c.Assert(IsComponentFolder("archetypes"), qt.Equals, true)
assert.True(IsComponentFolder("layouts")) c.Assert(IsComponentFolder("layouts"), qt.Equals, true)
assert.True(IsComponentFolder("data")) c.Assert(IsComponentFolder("data"), qt.Equals, true)
assert.True(IsComponentFolder("i18n")) c.Assert(IsComponentFolder("i18n"), qt.Equals, true)
assert.True(IsComponentFolder("assets")) c.Assert(IsComponentFolder("assets"), qt.Equals, true)
assert.False(IsComponentFolder("resources")) c.Assert(IsComponentFolder("resources"), qt.Equals, false)
assert.True(IsComponentFolder("static")) c.Assert(IsComponentFolder("static"), qt.Equals, true)
assert.True(IsComponentFolder("content")) c.Assert(IsComponentFolder("content"), qt.Equals, true)
assert.False(IsComponentFolder("foo")) c.Assert(IsComponentFolder("foo"), qt.Equals, false)
assert.False(IsComponentFolder("")) c.Assert(IsComponentFolder(""), qt.Equals, false)
} }

View file

@ -17,7 +17,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestLangInfoFrom(t *testing.T) { func TestLangInfoFrom(t *testing.T) {
@ -27,7 +27,7 @@ func TestLangInfoFrom(t *testing.T) {
"en": 20, "en": 20,
} }
assert := require.New(t) c := qt.New(t)
tests := []struct { tests := []struct {
input string input string
@ -42,7 +42,7 @@ func TestLangInfoFrom(t *testing.T) {
for _, test := range tests { for _, test := range tests {
v1, v2, v3 := langInfoFrom(langs, test.input) v1, v2, v3 := langInfoFrom(langs, test.input)
assert.Equal(test.expected, []string{v1, v2, v3}) c.Assert([]string{v1, v2, v3}, qt.DeepEquals, test.expected)
} }
} }

View file

@ -16,45 +16,46 @@ package hugofs
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/htesting/hqt"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/assert"
) )
func TestNewDefault(t *testing.T) { func TestNewDefault(t *testing.T) {
c := qt.New(t)
v := viper.New() v := viper.New()
f := NewDefault(v) f := NewDefault(v)
assert.NotNil(t, f.Source) c.Assert(f.Source, qt.Not(qt.IsNil))
assert.IsType(t, new(afero.OsFs), f.Source) c.Assert(f.Source, hqt.IsSameType, new(afero.OsFs))
assert.NotNil(t, f.Destination) c.Assert(f.Os, qt.Not(qt.IsNil))
assert.IsType(t, new(afero.OsFs), f.Destination) c.Assert(f.WorkingDir, qt.IsNil)
assert.NotNil(t, f.Os)
assert.IsType(t, new(afero.OsFs), f.Os)
assert.Nil(t, f.WorkingDir)
assert.IsType(t, new(afero.OsFs), Os)
} }
func TestNewMem(t *testing.T) { func TestNewMem(t *testing.T) {
c := qt.New(t)
v := viper.New() v := viper.New()
f := NewMem(v) f := NewMem(v)
assert.NotNil(t, f.Source) c.Assert(f.Source, qt.Not(qt.IsNil))
assert.IsType(t, new(afero.MemMapFs), f.Source) c.Assert(f.Source, hqt.IsSameType, new(afero.MemMapFs))
assert.NotNil(t, f.Destination) c.Assert(f.Destination, qt.Not(qt.IsNil))
assert.IsType(t, new(afero.MemMapFs), f.Destination) c.Assert(f.Destination, hqt.IsSameType, new(afero.MemMapFs))
assert.IsType(t, new(afero.OsFs), f.Os) c.Assert(f.Os, hqt.IsSameType, new(afero.OsFs))
assert.Nil(t, f.WorkingDir) c.Assert(f.WorkingDir, qt.IsNil)
} }
func TestWorkingDir(t *testing.T) { func TestWorkingDir(t *testing.T) {
c := qt.New(t)
v := viper.New() v := viper.New()
v.Set("workingDir", "/a/b/") v.Set("workingDir", "/a/b/")
f := NewMem(v) f := NewMem(v)
assert.NotNil(t, f.WorkingDir) c.Assert(f.WorkingDir, qt.Not(qt.IsNil))
assert.IsType(t, new(afero.BasePathFs), f.WorkingDir) c.Assert(f.WorkingDir, hqt.IsSameType, new(afero.BasePathFs))
} }

View file

@ -16,8 +16,8 @@ package hugofs
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require"
) )
type testHashReceiver struct { type testHashReceiver struct {
@ -31,23 +31,23 @@ func (t *testHashReceiver) OnFileClose(name, md5hash string) {
} }
func TestHashingFs(t *testing.T) { func TestHashingFs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
observer := &testHashReceiver{} observer := &testHashReceiver{}
ofs := NewHashingFs(fs, observer) ofs := NewHashingFs(fs, observer)
f, err := ofs.Create("hashme") f, err := ofs.Create("hashme")
assert.NoError(err) c.Assert(err, qt.IsNil)
_, err = f.Write([]byte("content")) _, err = f.Write([]byte("content"))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NoError(f.Close()) c.Assert(f.Close(), qt.IsNil)
assert.Equal("9a0364b9e99bb480dd25e1f0284c8555", observer.sum) c.Assert(observer.sum, qt.Equals, "9a0364b9e99bb480dd25e1f0284c8555")
assert.Equal("hashme", observer.name) c.Assert(observer.name, qt.Equals, "hashme")
f, err = ofs.Create("nowrites") f, err = ofs.Create("nowrites")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NoError(f.Close()) c.Assert(f.Close(), qt.IsNil)
assert.Equal("d41d8cd98f00b204e9800998ecf8427e", observer.sum) c.Assert(observer.sum, qt.Equals, "d41d8cd98f00b204e9800998ecf8427e")
} }

View file

@ -24,28 +24,28 @@ import (
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func prepareSymlinks(t *testing.T) (string, func()) { func prepareSymlinks(t *testing.T) (string, func()) {
assert := require.New(t) c := qt.New(t)
workDir, clean, err := htesting.CreateTempDir(Os, "hugo-symlink-test") workDir, clean, err := htesting.CreateTempDir(Os, "hugo-symlink-test")
assert.NoError(err) c.Assert(err, qt.IsNil)
wd, _ := os.Getwd() wd, _ := os.Getwd()
blogDir := filepath.Join(workDir, "blog") blogDir := filepath.Join(workDir, "blog")
blogSubDir := filepath.Join(blogDir, "sub") blogSubDir := filepath.Join(blogDir, "sub")
assert.NoError(os.MkdirAll(blogSubDir, 0777)) c.Assert(os.MkdirAll(blogSubDir, 0777), qt.IsNil)
blogFile1 := filepath.Join(blogDir, "a.txt") blogFile1 := filepath.Join(blogDir, "a.txt")
blogFile2 := filepath.Join(blogSubDir, "b.txt") blogFile2 := filepath.Join(blogSubDir, "b.txt")
afero.WriteFile(Os, filepath.Join(blogFile1), []byte("content1"), 0777) afero.WriteFile(Os, filepath.Join(blogFile1), []byte("content1"), 0777)
afero.WriteFile(Os, filepath.Join(blogFile2), []byte("content2"), 0777) afero.WriteFile(Os, filepath.Join(blogFile2), []byte("content2"), 0777)
os.Chdir(workDir) os.Chdir(workDir)
assert.NoError(os.Symlink("blog", "symlinkdedir")) c.Assert(os.Symlink("blog", "symlinkdedir"), qt.IsNil)
os.Chdir(blogDir) os.Chdir(blogDir)
assert.NoError(os.Symlink("sub", "symsub")) c.Assert(os.Symlink("sub", "symsub"), qt.IsNil)
assert.NoError(os.Symlink("a.txt", "symlinkdedfile.txt")) c.Assert(os.Symlink("a.txt", "symlinkdedfile.txt"), qt.IsNil)
return workDir, func() { return workDir, func() {
clean() clean()
@ -57,7 +57,7 @@ func TestNoSymlinkFs(t *testing.T) {
if skipSymlink() { if skipSymlink() {
t.Skip("Skip; os.Symlink needs administrator rights on Windows") t.Skip("Skip; os.Symlink needs administrator rights on Windows")
} }
assert := require.New(t) c := qt.New(t)
workDir, clean := prepareSymlinks(t) workDir, clean := prepareSymlinks(t)
defer clean() defer clean()
@ -77,9 +77,9 @@ func TestNoSymlinkFs(t *testing.T) {
assertFileErr := func(err error) { assertFileErr := func(err error) {
if allowFiles { if allowFiles {
assert.NoError(err) c.Assert(err, qt.IsNil)
} else { } else {
assert.Equal(ErrPermissionSymlink, err) c.Assert(err, qt.Equals, ErrPermissionSymlink)
} }
} }
@ -87,8 +87,8 @@ func TestNoSymlinkFs(t *testing.T) {
t.Helper() t.Helper()
assertFileErr(err) assertFileErr(err)
if err == nil { if err == nil {
assert.NotNil(fi) c.Assert(fi, qt.Not(qt.IsNil))
assert.Equal(name, fi.Name()) c.Assert(fi.Name(), qt.Equals, name)
} }
} }
@ -103,42 +103,42 @@ func TestNoSymlinkFs(t *testing.T) {
}, },
} { } {
_, err := stat(symlinkedDir) _, err := stat(symlinkedDir)
assert.Equal(ErrPermissionSymlink, err) c.Assert(err, qt.Equals, ErrPermissionSymlink)
fi, err := stat(symlinkedFile) fi, err := stat(symlinkedFile)
assertFileStat(symlinkedFilename, fi, err) assertFileStat(symlinkedFilename, fi, err)
fi, err = stat(filepath.Join(workDir, "blog")) fi, err = stat(filepath.Join(workDir, "blog"))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(fi) c.Assert(fi, qt.Not(qt.IsNil))
fi, err = stat(blogFile1) fi, err = stat(blogFile1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(fi) c.Assert(fi, qt.Not(qt.IsNil))
} }
// Check Open // Check Open
_, err := fs.Open(symlinkedDir) _, err := fs.Open(symlinkedDir)
assert.Equal(ErrPermissionSymlink, err) c.Assert(err, qt.Equals, ErrPermissionSymlink)
_, err = fs.OpenFile(symlinkedDir, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) _, err = fs.OpenFile(symlinkedDir, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
assert.Equal(ErrPermissionSymlink, err) c.Assert(err, qt.Equals, ErrPermissionSymlink)
_, err = fs.OpenFile(symlinkedFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666) _, err = fs.OpenFile(symlinkedFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
assertFileErr(err) assertFileErr(err)
_, err = fs.Open(symlinkedFile) _, err = fs.Open(symlinkedFile)
assertFileErr(err) assertFileErr(err)
f, err := fs.Open(blogDir) f, err := fs.Open(blogDir)
assert.NoError(err) c.Assert(err, qt.IsNil)
f.Close() f.Close()
f, err = fs.Open(blogFile1) f, err = fs.Open(blogFile1)
assert.NoError(err) c.Assert(err, qt.IsNil)
f.Close() f.Close()
// Check readdir // Check readdir
f, err = fs.Open(workDir) f, err = fs.Open(workDir)
assert.NoError(err) c.Assert(err, qt.IsNil)
// There is at least one unsported symlink inside workDir // There is at least one unsported symlink inside workDir
_, err = f.Readdir(-1) _, err = f.Readdir(-1)
f.Close() f.Close()
assert.Equal(uint64(1), logger.WarnCounter.Count()) c.Assert(logger.WarnCounter.Count(), qt.Equals, uint64(1))
} }
} }

View file

@ -21,24 +21,24 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/htesting"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require"
) )
func TestLanguageRootMapping(t *testing.T) { func TestLanguageRootMapping(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := viper.New() v := viper.New()
v.Set("contentDir", "content") v.Set("contentDir", "content")
fs := NewBaseFileDecorator(afero.NewMemMapFs()) fs := NewBaseFileDecorator(afero.NewMemMapFs())
assert.NoError(afero.WriteFile(fs, filepath.Join("content/sv/svdir", "main.txt"), []byte("main sv"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("content/sv/svdir", "main.txt"), []byte("main sv"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", "sv-f.txt"), []byte("some sv blog content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", "sv-f.txt"), []byte("some sv blog content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/myenblogcontent", "en-f.txt"), []byte("some en blog content in a"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/myenblogcontent", "en-f.txt"), []byte("some en blog content in a"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/myotherenblogcontent", "en-f2.txt"), []byte("some en content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/myotherenblogcontent", "en-f2.txt"), []byte("some en content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/mysvdocs", "sv-docs.txt"), []byte("some sv docs content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvdocs", "sv-docs.txt"), []byte("some sv docs content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/b/myenblogcontent", "en-b-f.txt"), []byte("some en content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/b/myenblogcontent", "en-b-f.txt"), []byte("some en content"), 0755), qt.IsNil)
rfs, err := NewRootMappingFs(fs, rfs, err := NewRootMappingFs(fs,
RootMapping{ RootMapping{
@ -68,38 +68,38 @@ func TestLanguageRootMapping(t *testing.T) {
}, },
) )
assert.NoError(err) c.Assert(err, qt.IsNil)
collected, err := collectFilenames(rfs, "content", "content") collected, err := collectFilenames(rfs, "content", "content")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"blog/en-f.txt", "blog/en-f2.txt", "blog/sv-f.txt", "blog/svdir/main.txt", "docs/sv-docs.txt"}, collected) c.Assert(collected, qt.DeepEquals, []string{"blog/en-f.txt", "blog/en-f2.txt", "blog/sv-f.txt", "blog/svdir/main.txt", "docs/sv-docs.txt"})
bfs := afero.NewBasePathFs(rfs, "content") bfs := afero.NewBasePathFs(rfs, "content")
collected, err = collectFilenames(bfs, "", "") collected, err = collectFilenames(bfs, "", "")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"blog/en-f.txt", "blog/en-f2.txt", "blog/sv-f.txt", "blog/svdir/main.txt", "docs/sv-docs.txt"}, collected) c.Assert(collected, qt.DeepEquals, []string{"blog/en-f.txt", "blog/en-f2.txt", "blog/sv-f.txt", "blog/svdir/main.txt", "docs/sv-docs.txt"})
dirs, err := rfs.Dirs(filepath.FromSlash("content/blog")) dirs, err := rfs.Dirs(filepath.FromSlash("content/blog"))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(4, len(dirs)) c.Assert(len(dirs), qt.Equals, 4)
getDirnames := func(name string, rfs *RootMappingFs) []string { getDirnames := func(name string, rfs *RootMappingFs) []string {
filename := filepath.FromSlash(name) filename := filepath.FromSlash(name)
f, err := rfs.Open(filename) f, err := rfs.Open(filename)
assert.NoError(err) c.Assert(err, qt.IsNil)
names, err := f.Readdirnames(-1) names, err := f.Readdirnames(-1)
f.Close() f.Close()
assert.NoError(err) c.Assert(err, qt.IsNil)
info, err := rfs.Stat(filename) info, err := rfs.Stat(filename)
assert.NoError(err) c.Assert(err, qt.IsNil)
f2, err := info.(FileMetaInfo).Meta().Open() f2, err := info.(FileMetaInfo).Meta().Open()
assert.NoError(err) c.Assert(err, qt.IsNil)
names2, err := f2.Readdirnames(-1) names2, err := f2.Readdirnames(-1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(names, names2) c.Assert(names2, qt.DeepEquals, names)
f2.Close() f2.Close()
return names return names
@ -109,83 +109,83 @@ func TestLanguageRootMapping(t *testing.T) {
return rm.Meta.Lang() == "en" return rm.Meta.Lang() == "en"
}) })
assert.Equal([]string{"en-f.txt", "en-f2.txt"}, getDirnames("content/blog", rfsEn)) c.Assert(getDirnames("content/blog", rfsEn), qt.DeepEquals, []string{"en-f.txt", "en-f2.txt"})
rfsSv := rfs.Filter(func(rm RootMapping) bool { rfsSv := rfs.Filter(func(rm RootMapping) bool {
return rm.Meta.Lang() == "sv" return rm.Meta.Lang() == "sv"
}) })
assert.Equal([]string{"sv-f.txt", "svdir"}, getDirnames("content/blog", rfsSv)) c.Assert(getDirnames("content/blog", rfsSv), qt.DeepEquals, []string{"sv-f.txt", "svdir"})
// Make sure we have not messed with the original // Make sure we have not messed with the original
assert.Equal([]string{"sv-f.txt", "en-f.txt", "svdir", "en-f2.txt"}, getDirnames("content/blog", rfs)) c.Assert(getDirnames("content/blog", rfs), qt.DeepEquals, []string{"sv-f.txt", "en-f.txt", "svdir", "en-f2.txt"})
assert.Equal([]string{"blog", "docs"}, getDirnames("content", rfsSv)) c.Assert(getDirnames("content", rfsSv), qt.DeepEquals, []string{"blog", "docs"})
assert.Equal([]string{"blog", "docs"}, getDirnames("content", rfs)) c.Assert(getDirnames("content", rfs), qt.DeepEquals, []string{"blog", "docs"})
} }
func TestRootMappingFsDirnames(t *testing.T) { func TestRootMappingFsDirnames(t *testing.T) {
assert := require.New(t) c := qt.New(t)
fs := NewBaseFileDecorator(afero.NewMemMapFs()) fs := NewBaseFileDecorator(afero.NewMemMapFs())
testfile := "myfile.txt" testfile := "myfile.txt"
assert.NoError(fs.Mkdir("f1t", 0755)) c.Assert(fs.Mkdir("f1t", 0755), qt.IsNil)
assert.NoError(fs.Mkdir("f2t", 0755)) c.Assert(fs.Mkdir("f2t", 0755), qt.IsNil)
assert.NoError(fs.Mkdir("f3t", 0755)) c.Assert(fs.Mkdir("f3t", 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("f2t", testfile), []byte("some content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("f2t", testfile), []byte("some content"), 0755), qt.IsNil)
rfs, err := NewRootMappingFsFromFromTo(fs, "static/bf1", "f1t", "static/cf2", "f2t", "static/af3", "f3t") rfs, err := NewRootMappingFsFromFromTo(fs, "static/bf1", "f1t", "static/cf2", "f2t", "static/af3", "f3t")
assert.NoError(err) c.Assert(err, qt.IsNil)
fif, err := rfs.Stat(filepath.Join("static/cf2", testfile)) fif, err := rfs.Stat(filepath.Join("static/cf2", testfile))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("myfile.txt", fif.Name()) c.Assert(fif.Name(), qt.Equals, "myfile.txt")
fifm := fif.(FileMetaInfo).Meta() fifm := fif.(FileMetaInfo).Meta()
assert.Equal(filepath.FromSlash("f2t/myfile.txt"), fifm.Filename()) c.Assert(fifm.Filename(), qt.Equals, filepath.FromSlash("f2t/myfile.txt"))
root, err := rfs.Open(filepathSeparator) root, err := rfs.Open(filepathSeparator)
assert.NoError(err) c.Assert(err, qt.IsNil)
dirnames, err := root.Readdirnames(-1) dirnames, err := root.Readdirnames(-1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"bf1", "cf2", "af3"}, dirnames) c.Assert(dirnames, qt.DeepEquals, []string{"bf1", "cf2", "af3"})
} }
func TestRootMappingFsFilename(t *testing.T) { func TestRootMappingFsFilename(t *testing.T) {
assert := require.New(t) c := qt.New(t)
workDir, clean, err := htesting.CreateTempDir(Os, "hugo-root-filename") workDir, clean, err := htesting.CreateTempDir(Os, "hugo-root-filename")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer clean() defer clean()
fs := NewBaseFileDecorator(Os) fs := NewBaseFileDecorator(Os)
testfilename := filepath.Join(workDir, "f1t/foo/file.txt") testfilename := filepath.Join(workDir, "f1t/foo/file.txt")
assert.NoError(fs.MkdirAll(filepath.Join(workDir, "f1t/foo"), 0777)) c.Assert(fs.MkdirAll(filepath.Join(workDir, "f1t/foo"), 0777), qt.IsNil)
assert.NoError(afero.WriteFile(fs, testfilename, []byte("content"), 0666)) c.Assert(afero.WriteFile(fs, testfilename, []byte("content"), 0666), qt.IsNil)
rfs, err := NewRootMappingFsFromFromTo(fs, "static/f1", filepath.Join(workDir, "f1t"), "static/f2", filepath.Join(workDir, "f2t")) rfs, err := NewRootMappingFsFromFromTo(fs, "static/f1", filepath.Join(workDir, "f1t"), "static/f2", filepath.Join(workDir, "f2t"))
assert.NoError(err) c.Assert(err, qt.IsNil)
fi, err := rfs.Stat(filepath.FromSlash("static/f1/foo/file.txt")) fi, err := rfs.Stat(filepath.FromSlash("static/f1/foo/file.txt"))
assert.NoError(err) c.Assert(err, qt.IsNil)
fim := fi.(FileMetaInfo) fim := fi.(FileMetaInfo)
assert.Equal(testfilename, fim.Meta().Filename()) c.Assert(fim.Meta().Filename(), qt.Equals, testfilename)
_, err = rfs.Stat(filepath.FromSlash("static/f1")) _, err = rfs.Stat(filepath.FromSlash("static/f1"))
assert.NoError(err) c.Assert(err, qt.IsNil)
} }
func TestRootMappingFsMount(t *testing.T) { func TestRootMappingFsMount(t *testing.T) {
assert := require.New(t) c := qt.New(t)
fs := NewBaseFileDecorator(afero.NewMemMapFs()) fs := NewBaseFileDecorator(afero.NewMemMapFs())
testfile := "test.txt" testfile := "test.txt"
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/mynoblogcontent", testfile), []byte("some no content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mynoblogcontent", testfile), []byte("some no content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/myenblogcontent", testfile), []byte("some en content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/myenblogcontent", testfile), []byte("some en content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", testfile), []byte("some sv content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", testfile), []byte("some sv content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", "other.txt"), []byte("some sv content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("themes/a/mysvblogcontent", "other.txt"), []byte("some sv content"), 0755), qt.IsNil)
bfs := afero.NewBasePathFs(fs, "themes/a").(*afero.BasePathFs) bfs := afero.NewBasePathFs(fs, "themes/a").(*afero.BasePathFs)
rm := []RootMapping{ rm := []RootMapping{
@ -204,48 +204,48 @@ func TestRootMappingFsMount(t *testing.T) {
} }
rfs, err := NewRootMappingFs(bfs, rm...) rfs, err := NewRootMappingFs(bfs, rm...)
assert.NoError(err) c.Assert(err, qt.IsNil)
blog, err := rfs.Stat(filepath.FromSlash("content/blog")) blog, err := rfs.Stat(filepath.FromSlash("content/blog"))
assert.NoError(err) c.Assert(err, qt.IsNil)
blogm := blog.(FileMetaInfo).Meta() blogm := blog.(FileMetaInfo).Meta()
assert.Equal("sv", blogm.Lang()) // Last match c.Assert(blogm.Lang(), qt.Equals, "sv") // Last match
f, err := blogm.Open() f, err := blogm.Open()
assert.NoError(err) c.Assert(err, qt.IsNil)
defer f.Close() defer f.Close()
dirs1, err := f.Readdirnames(-1) dirs1, err := f.Readdirnames(-1)
assert.NoError(err) c.Assert(err, qt.IsNil)
// Union with duplicate dir names filtered. // Union with duplicate dir names filtered.
assert.Equal([]string{"test.txt", "test.txt", "other.txt", "test.txt"}, dirs1) c.Assert(dirs1, qt.DeepEquals, []string{"test.txt", "test.txt", "other.txt", "test.txt"})
files, err := afero.ReadDir(rfs, filepath.FromSlash("content/blog")) files, err := afero.ReadDir(rfs, filepath.FromSlash("content/blog"))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(4, len(files)) c.Assert(len(files), qt.Equals, 4)
testfilefi := files[1] testfilefi := files[1]
assert.Equal(testfile, testfilefi.Name()) c.Assert(testfilefi.Name(), qt.Equals, testfile)
testfilem := testfilefi.(FileMetaInfo).Meta() testfilem := testfilefi.(FileMetaInfo).Meta()
assert.Equal(filepath.FromSlash("themes/a/mynoblogcontent/test.txt"), testfilem.Filename()) c.Assert(testfilem.Filename(), qt.Equals, filepath.FromSlash("themes/a/mynoblogcontent/test.txt"))
tf, err := testfilem.Open() tf, err := testfilem.Open()
assert.NoError(err) c.Assert(err, qt.IsNil)
defer tf.Close() defer tf.Close()
c, err := ioutil.ReadAll(tf) b, err := ioutil.ReadAll(tf)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("some no content", string(c)) c.Assert(string(b), qt.Equals, "some no content")
} }
func TestRootMappingFsMountOverlap(t *testing.T) { func TestRootMappingFsMountOverlap(t *testing.T) {
assert := require.New(t) c := qt.New(t)
fs := NewBaseFileDecorator(afero.NewMemMapFs()) fs := NewBaseFileDecorator(afero.NewMemMapFs())
assert.NoError(afero.WriteFile(fs, filepath.FromSlash("da/a.txt"), []byte("some no content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.FromSlash("da/a.txt"), []byte("some no content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.FromSlash("db/b.txt"), []byte("some no content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.FromSlash("db/b.txt"), []byte("some no content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.FromSlash("dc/c.txt"), []byte("some no content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.FromSlash("dc/c.txt"), []byte("some no content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.FromSlash("de/e.txt"), []byte("some no content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.FromSlash("de/e.txt"), []byte("some no content"), 0755), qt.IsNil)
rm := []RootMapping{ rm := []RootMapping{
RootMapping{ RootMapping{
@ -267,56 +267,56 @@ func TestRootMappingFsMountOverlap(t *testing.T) {
} }
rfs, err := NewRootMappingFs(fs, rm...) rfs, err := NewRootMappingFs(fs, rm...)
assert.NoError(err) c.Assert(err, qt.IsNil)
getDirnames := func(name string) []string { getDirnames := func(name string) []string {
name = filepath.FromSlash(name) name = filepath.FromSlash(name)
f, err := rfs.Open(name) f, err := rfs.Open(name)
assert.NoError(err) c.Assert(err, qt.IsNil)
defer f.Close() defer f.Close()
names, err := f.Readdirnames(-1) names, err := f.Readdirnames(-1)
assert.NoError(err) c.Assert(err, qt.IsNil)
return names return names
} }
assert.Equal([]string{"a.txt", "b", "e"}, getDirnames("static")) c.Assert(getDirnames("static"), qt.DeepEquals, []string{"a.txt", "b", "e"})
assert.Equal([]string{"b.txt", "c"}, getDirnames("static/b")) c.Assert(getDirnames("static/b"), qt.DeepEquals, []string{"b.txt", "c"})
assert.Equal([]string{"c.txt"}, getDirnames("static/b/c")) c.Assert(getDirnames("static/b/c"), qt.DeepEquals, []string{"c.txt"})
fi, err := rfs.Stat(filepath.FromSlash("static/b/b.txt")) fi, err := rfs.Stat(filepath.FromSlash("static/b/b.txt"))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("b.txt", fi.Name()) c.Assert(fi.Name(), qt.Equals, "b.txt")
} }
func TestRootMappingFsOs(t *testing.T) { func TestRootMappingFsOs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
fs := afero.NewOsFs() fs := afero.NewOsFs()
d, err := ioutil.TempDir("", "hugo-root-mapping") d, err := ioutil.TempDir("", "hugo-root-mapping")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer func() { defer func() {
os.RemoveAll(d) os.RemoveAll(d)
}() }()
testfile := "myfile.txt" testfile := "myfile.txt"
assert.NoError(fs.Mkdir(filepath.Join(d, "f1t"), 0755)) c.Assert(fs.Mkdir(filepath.Join(d, "f1t"), 0755), qt.IsNil)
assert.NoError(fs.Mkdir(filepath.Join(d, "f2t"), 0755)) c.Assert(fs.Mkdir(filepath.Join(d, "f2t"), 0755), qt.IsNil)
assert.NoError(fs.Mkdir(filepath.Join(d, "f3t"), 0755)) c.Assert(fs.Mkdir(filepath.Join(d, "f3t"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join(d, "f2t", testfile), []byte("some content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join(d, "f2t", testfile), []byte("some content"), 0755), qt.IsNil)
rfs, err := NewRootMappingFsFromFromTo(fs, "static/bf1", filepath.Join(d, "f1t"), "static/cf2", filepath.Join(d, "f2t"), "static/af3", filepath.Join(d, "f3t")) rfs, err := NewRootMappingFsFromFromTo(fs, "static/bf1", filepath.Join(d, "f1t"), "static/cf2", filepath.Join(d, "f2t"), "static/af3", filepath.Join(d, "f3t"))
assert.NoError(err) c.Assert(err, qt.IsNil)
fif, err := rfs.Stat(filepath.Join("static/cf2", testfile)) fif, err := rfs.Stat(filepath.Join("static/cf2", testfile))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("myfile.txt", fif.Name()) c.Assert(fif.Name(), qt.Equals, "myfile.txt")
root, err := rfs.Open(filepathSeparator) root, err := rfs.Open(filepathSeparator)
assert.NoError(err) c.Assert(err, qt.IsNil)
dirnames, err := root.Readdirnames(-1) dirnames, err := root.Readdirnames(-1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"bf1", "cf2", "af3"}, dirnames) c.Assert(dirnames, qt.DeepEquals, []string{"bf1", "cf2", "af3"})
} }

View file

@ -29,11 +29,11 @@ import (
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestWalk(t *testing.T) { func TestWalk(t *testing.T) {
assert := require.New(t) c := qt.New(t)
fs := NewBaseFileDecorator(afero.NewMemMapFs()) fs := NewBaseFileDecorator(afero.NewMemMapFs())
@ -43,19 +43,19 @@ func TestWalk(t *testing.T) {
names, err := collectFilenames(fs, "", "") names, err := collectFilenames(fs, "", "")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"a.txt", "b.txt", "c.txt"}, names) c.Assert(names, qt.DeepEquals, []string{"a.txt", "b.txt", "c.txt"})
} }
func TestWalkRootMappingFs(t *testing.T) { func TestWalkRootMappingFs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
fs := NewBaseFileDecorator(afero.NewMemMapFs()) fs := NewBaseFileDecorator(afero.NewMemMapFs())
testfile := "test.txt" testfile := "test.txt"
assert.NoError(afero.WriteFile(fs, filepath.Join("a/b", testfile), []byte("some content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("a/b", testfile), []byte("some content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("c/d", testfile), []byte("some content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("c/d", testfile), []byte("some content"), 0755), qt.IsNil)
assert.NoError(afero.WriteFile(fs, filepath.Join("e/f", testfile), []byte("some content"), 0755)) c.Assert(afero.WriteFile(fs, filepath.Join("e/f", testfile), []byte("some content"), 0755), qt.IsNil)
rm := []RootMapping{ rm := []RootMapping{
RootMapping{ RootMapping{
@ -74,13 +74,13 @@ func TestWalkRootMappingFs(t *testing.T) {
} }
rfs, err := NewRootMappingFs(fs, rm...) rfs, err := NewRootMappingFs(fs, rm...)
assert.NoError(err) c.Assert(err, qt.IsNil)
bfs := afero.NewBasePathFs(rfs, "static") bfs := afero.NewBasePathFs(rfs, "static")
names, err := collectFilenames(bfs, "", "") names, err := collectFilenames(bfs, "", "")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"a/test.txt", "b/test.txt", "c/test.txt"}, names) c.Assert(names, qt.DeepEquals, []string{"a/test.txt", "b/test.txt", "c/test.txt"})
} }
@ -92,9 +92,9 @@ func TestWalkSymbolicLink(t *testing.T) {
if skipSymlink() { if skipSymlink() {
t.Skip("Skip; os.Symlink needs administrator rights on Windows") t.Skip("Skip; os.Symlink needs administrator rights on Windows")
} }
assert := require.New(t) c := qt.New(t)
workDir, clean, err := htesting.CreateTempDir(Os, "hugo-walk-sym") workDir, clean, err := htesting.CreateTempDir(Os, "hugo-walk-sym")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer clean() defer clean()
wd, _ := os.Getwd() wd, _ := os.Getwd()
defer func() { defer func() {
@ -107,25 +107,25 @@ func TestWalkSymbolicLink(t *testing.T) {
docsDir := filepath.Join(workDir, "docs") docsDir := filepath.Join(workDir, "docs")
blogReal := filepath.Join(blogDir, "real") blogReal := filepath.Join(blogDir, "real")
blogRealSub := filepath.Join(blogReal, "sub") blogRealSub := filepath.Join(blogReal, "sub")
assert.NoError(os.MkdirAll(blogRealSub, 0777)) c.Assert(os.MkdirAll(blogRealSub, 0777), qt.IsNil)
assert.NoError(os.MkdirAll(docsDir, 0777)) c.Assert(os.MkdirAll(docsDir, 0777), qt.IsNil)
afero.WriteFile(fs, filepath.Join(blogRealSub, "a.txt"), []byte("content"), 0777) afero.WriteFile(fs, filepath.Join(blogRealSub, "a.txt"), []byte("content"), 0777)
afero.WriteFile(fs, filepath.Join(docsDir, "b.txt"), []byte("content"), 0777) afero.WriteFile(fs, filepath.Join(docsDir, "b.txt"), []byte("content"), 0777)
os.Chdir(blogDir) os.Chdir(blogDir)
assert.NoError(os.Symlink("real", "symlinked")) c.Assert(os.Symlink("real", "symlinked"), qt.IsNil)
os.Chdir(blogReal) os.Chdir(blogReal)
assert.NoError(os.Symlink("../real", "cyclic")) c.Assert(os.Symlink("../real", "cyclic"), qt.IsNil)
os.Chdir(docsDir) os.Chdir(docsDir)
assert.NoError(os.Symlink("../blog/real/cyclic", "docsreal")) c.Assert(os.Symlink("../blog/real/cyclic", "docsreal"), qt.IsNil)
t.Run("OS Fs", func(t *testing.T) { t.Run("OS Fs", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
names, err := collectFilenames(fs, workDir, workDir) names, err := collectFilenames(fs, workDir, workDir)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"blog/real/sub/a.txt", "docs/b.txt"}, names) c.Assert(names, qt.DeepEquals, []string{"blog/real/sub/a.txt", "docs/b.txt"})
}) })
t.Run("BasePath Fs", func(t *testing.T) { t.Run("BasePath Fs", func(t *testing.T) {
@ -135,15 +135,15 @@ func TestWalkSymbolicLink(t *testing.T) {
t.Skip("skip this for Go <= 1.11 due to a bug in Go's stdlib") t.Skip("skip this for Go <= 1.11 due to a bug in Go's stdlib")
} }
assert := require.New(t) c := qt.New(t)
docsFs := afero.NewBasePathFs(fs, docsDir) docsFs := afero.NewBasePathFs(fs, docsDir)
names, err := collectFilenames(docsFs, "", "") names, err := collectFilenames(docsFs, "", "")
assert.NoError(err) c.Assert(err, qt.IsNil)
// Note: the docsreal folder is considered cyclic when walking from the root, but this works. // Note: the docsreal folder is considered cyclic when walking from the root, but this works.
assert.Equal([]string{"b.txt", "docsreal/sub/a.txt"}, names) c.Assert(names, qt.DeepEquals, []string{"b.txt", "docsreal/sub/a.txt"})
}) })
} }
@ -177,13 +177,13 @@ func collectFilenames(fs afero.Fs, base, root string) ([]string, error) {
} }
func BenchmarkWalk(b *testing.B) { func BenchmarkWalk(b *testing.B) {
assert := require.New(b) c := qt.New(b)
fs := NewBaseFileDecorator(afero.NewMemMapFs()) fs := NewBaseFileDecorator(afero.NewMemMapFs())
writeFiles := func(dir string, numfiles int) { writeFiles := func(dir string, numfiles int) {
for i := 0; i < numfiles; i++ { for i := 0; i < numfiles; i++ {
filename := filepath.Join(dir, fmt.Sprintf("file%d.txt", i)) filename := filepath.Join(dir, fmt.Sprintf("file%d.txt", i))
assert.NoError(afero.WriteFile(fs, filename, []byte("content"), 0777)) c.Assert(afero.WriteFile(fs, filename, []byte("content"), 0777), qt.IsNil)
} }
} }

View file

@ -20,7 +20,7 @@ import (
"github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/loggers"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
const pageWithAlias = `--- const pageWithAlias = `---
@ -43,14 +43,14 @@ const aliasTemplate = "<html><body>ALIASTEMPLATE</body></html>"
func TestAlias(t *testing.T) { func TestAlias(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
b := newTestSitesBuilder(t) b := newTestSitesBuilder(t)
b.WithSimpleConfigFile().WithContent("blog/page.md", pageWithAlias) b.WithSimpleConfigFile().WithContent("blog/page.md", pageWithAlias)
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 1)
require.Len(t, b.H.Sites[0].RegularPages(), 1) c.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 1)
// the real page // the real page
b.AssertFileContent("public/blog/page/index.html", "For some moments the old man") b.AssertFileContent("public/blog/page/index.html", "For some moments the old man")
@ -62,7 +62,7 @@ func TestAlias(t *testing.T) {
func TestAliasMultipleOutputFormats(t *testing.T) { func TestAliasMultipleOutputFormats(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
b := newTestSitesBuilder(t) b := newTestSitesBuilder(t)
b.WithSimpleConfigFile().WithContent("blog/page.md", pageWithAliasMultipleOutputs) b.WithSimpleConfigFile().WithContent("blog/page.md", pageWithAliasMultipleOutputs)
@ -82,7 +82,7 @@ func TestAliasMultipleOutputFormats(t *testing.T) {
// the alias redirectors // the alias redirectors
b.AssertFileContent("public/foo/bar/index.html", "<meta http-equiv=\"refresh\" content=\"0; ") b.AssertFileContent("public/foo/bar/index.html", "<meta http-equiv=\"refresh\" content=\"0; ")
b.AssertFileContent("public/amp/foo/bar/index.html", "<meta http-equiv=\"refresh\" content=\"0; ") b.AssertFileContent("public/amp/foo/bar/index.html", "<meta http-equiv=\"refresh\" content=\"0; ")
assert.False(b.CheckExists("public/foo/bar/index.json")) c.Assert(b.CheckExists("public/foo/bar/index.json"), qt.Equals, false)
} }
func TestAliasTemplate(t *testing.T) { func TestAliasTemplate(t *testing.T) {

View file

@ -19,10 +19,9 @@ import (
"path" "path"
"testing" "testing"
"github.com/alecthomas/assert" qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser"
"github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/metadecoders"
"github.com/stretchr/testify/require"
) )
func BenchmarkCascade(b *testing.B) { func BenchmarkCascade(b *testing.B) {
@ -31,7 +30,7 @@ func BenchmarkCascade(b *testing.B) {
for i := 1; i <= len(allLangs); i += 2 { for i := 1; i <= len(allLangs); i += 2 {
langs := allLangs[0:i] langs := allLangs[0:i]
b.Run(fmt.Sprintf("langs-%d", len(langs)), func(b *testing.B) { b.Run(fmt.Sprintf("langs-%d", len(langs)), func(b *testing.B) {
assert := require.New(b) c := qt.New(b)
b.StopTimer() b.StopTimer()
builders := make([]*sitesBuilder, b.N) builders := make([]*sitesBuilder, b.N)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
@ -42,16 +41,15 @@ func BenchmarkCascade(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
builder := builders[i] builder := builders[i]
err := builder.BuildE(BuildCfg{}) err := builder.BuildE(BuildCfg{})
assert.NoError(err) c.Assert(err, qt.IsNil)
first := builder.H.Sites[0] first := builder.H.Sites[0]
assert.NotNil(first) c.Assert(first, qt.Not(qt.IsNil))
} }
}) })
} }
} }
func TestCascade(t *testing.T) { func TestCascade(t *testing.T) {
assert := assert.New(t)
allLangs := []string{"en", "nn", "nb", "sv"} allLangs := []string{"en", "nn", "nb", "sv"}
@ -93,7 +91,7 @@ func TestCascade(t *testing.T) {
// Check output formats set in cascade // Check output formats set in cascade
b.AssertFileContent("public/sect4/index.xml", `<link>https://example.org/sect4/index.xml</link>`) b.AssertFileContent("public/sect4/index.xml", `<link>https://example.org/sect4/index.xml</link>`)
b.AssertFileContent("public/sect4/p1/index.xml", `<link>https://example.org/sect4/p1/index.xml</link>`) b.AssertFileContent("public/sect4/p1/index.xml", `<link>https://example.org/sect4/p1/index.xml</link>`)
assert.False(b.CheckExists("public/sect2/index.xml")) b.C.Assert(b.CheckExists("public/sect2/index.xml"), qt.Equals, false)
// Check cascade into bundled page // Check cascade into bundled page
b.AssertFileContent("public/bundle1/index.html", `Resources: bp1.md|home.png|`) b.AssertFileContent("public/bundle1/index.html", `Resources: bp1.md|home.png|`)

View file

@ -21,9 +21,9 @@ import (
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require"
) )
var ( var (
@ -135,6 +135,8 @@ Partial Site Global: {{ site.Params.COLOR }}|{{ site.Params.COLORS.YELLOW }}
func TestCaseInsensitiveConfigurationVariations(t *testing.T) { func TestCaseInsensitiveConfigurationVariations(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
// See issues 2615, 1129, 2590 and maybe some others // See issues 2615, 1129, 2590 and maybe some others
// Also see 2598 // Also see 2598
// //
@ -152,11 +154,11 @@ func TestCaseInsensitiveConfigurationVariations(t *testing.T) {
caseMixingTestsWriteCommonSources(t, mm) caseMixingTestsWriteCommonSources(t, mm)
cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "config.toml"}) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "config.toml"})
require.NoError(t, err) c.Assert(err, qt.IsNil)
fs := hugofs.NewFrom(mm, cfg) fs := hugofs.NewFrom(mm, cfg)
th := testHelper{cfg, fs, t} th := newTestHelper(cfg, fs, t)
writeSource(t, fs, filepath.Join("layouts", "_default", "baseof.html"), ` writeSource(t, fs, filepath.Join("layouts", "_default", "baseof.html"), `
Block Page Colors: {{ .Params.COLOR }}|{{ .Params.Colors.Blue }} Block Page Colors: {{ .Params.COLOR }}|{{ .Params.Colors.Blue }}
@ -258,17 +260,17 @@ func TestCaseInsensitiveConfigurationForAllTemplateEngines(t *testing.T) {
} }
func doTestCaseInsensitiveConfigurationForTemplateEngine(t *testing.T, suffix string, templateFixer func(s string) string) { func doTestCaseInsensitiveConfigurationForTemplateEngine(t *testing.T, suffix string, templateFixer func(s string) string) {
c := qt.New(t)
mm := afero.NewMemMapFs() mm := afero.NewMemMapFs()
caseMixingTestsWriteCommonSources(t, mm) caseMixingTestsWriteCommonSources(t, mm)
cfg, err := LoadConfigDefault(mm) cfg, err := LoadConfigDefault(mm)
require.NoError(t, err) c.Assert(err, qt.IsNil)
fs := hugofs.NewFrom(mm, cfg) fs := hugofs.NewFrom(mm, cfg)
th := testHelper{cfg, fs, t} th := newTestHelper(cfg, fs, t)
t.Log("Testing", suffix) t.Log("Testing", suffix)

View file

@ -17,11 +17,11 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestGroupFunc(t *testing.T) { func TestGroupFunc(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pageContent := ` pageContent := `
--- ---
@ -39,14 +39,14 @@ title: "Page"
`) `)
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 1)
require.Len(t, b.H.Sites[0].RegularPages(), 2) c.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 2)
b.AssertFileContent("public/index.html", "cool: 2") b.AssertFileContent("public/index.html", "cool: 2")
} }
func TestSliceFunc(t *testing.T) { func TestSliceFunc(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pageContent := ` pageContent := `
--- ---
@ -78,8 +78,8 @@ tags_weight: %d
`) `)
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 1)
require.Len(t, b.H.Sites[0].RegularPages(), 2) c.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 2)
b.AssertFileContent("public/index.html", b.AssertFileContent("public/index.html",
"pages:2:page.Pages:Page(/page1.md)/Page(/page2.md)", "pages:2:page.Pages:Page(/page1.md)/Page(/page2.md)",
@ -88,7 +88,7 @@ tags_weight: %d
} }
func TestUnionFunc(t *testing.T) { func TestUnionFunc(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pageContent := ` pageContent := `
--- ---
@ -110,8 +110,8 @@ tags_weight: %d
`) `)
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 1)
require.Len(t, b.H.Sites[0].RegularPages(), 3) c.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 3)
b.AssertFileContent("public/index.html", b.AssertFileContent("public/index.html",
"unionPages: page.Pages 3", "unionPages: page.Pages 3",
@ -119,7 +119,7 @@ tags_weight: %d
} }
func TestCollectionsFuncs(t *testing.T) { func TestCollectionsFuncs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pageContent := ` pageContent := `
--- ---
@ -151,8 +151,8 @@ Symdiff: {{ range $symdiff }}{{ .RelPermalink }}|{{ end }}
`) `)
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 1)
require.Len(t, b.H.Sites[0].RegularPages(), 3) c.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 3)
b.AssertFileContent("public/index.html", b.AssertFileContent("public/index.html",
"uniqPages: page.Pages 3", "uniqPages: page.Pages 3",
@ -164,7 +164,7 @@ Symdiff: {{ range $symdiff }}{{ .RelPermalink }}|{{ end }}
} }
func TestAppendFunc(t *testing.T) { func TestAppendFunc(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pageContent := ` pageContent := `
--- ---
@ -203,8 +203,8 @@ tags_weight: %d
`) `)
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 1)
assert.Len(b.H.Sites[0].RegularPages(), 2) c.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 2)
b.AssertFileContent("public/index.html", b.AssertFileContent("public/index.html",
"pages:2:page.Pages:Page(/page2.md)/Page(/page1.md)", "pages:2:page.Pages:Page(/page2.md)/Page(/page1.md)",

View file

@ -19,15 +19,15 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestLoadConfig(t *testing.T) { func TestLoadConfig(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
// Add a random config variable for testing. // Add a random config variable for testing.
// side = page in Norwegian. // side = page in Norwegian.
@ -40,16 +40,16 @@ func TestLoadConfig(t *testing.T) {
writeToFs(t, mm, "hugo.toml", configContent) writeToFs(t, mm, "hugo.toml", configContent)
cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "hugo.toml"}) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "hugo.toml"})
require.NoError(t, err) c.Assert(err, qt.IsNil)
assert.Equal("side", cfg.GetString("paginatePath")) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "side")
} }
func TestLoadMultiConfig(t *testing.T) { func TestLoadMultiConfig(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
// Add a random config variable for testing. // Add a random config variable for testing.
// side = page in Norwegian. // side = page in Norwegian.
@ -67,16 +67,16 @@ func TestLoadMultiConfig(t *testing.T) {
writeToFs(t, mm, "override.toml", configContentSub) writeToFs(t, mm, "override.toml", configContentSub)
cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"}) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Filename: "base.toml,override.toml"})
require.NoError(t, err) c.Assert(err, qt.IsNil)
assert.Equal("top", cfg.GetString("paginatePath")) c.Assert(cfg.GetString("paginatePath"), qt.Equals, "top")
assert.Equal("same", cfg.GetString("DontChange")) c.Assert(cfg.GetString("DontChange"), qt.Equals, "same")
} }
func TestLoadConfigFromTheme(t *testing.T) { func TestLoadConfigFromTheme(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
mainConfigBasic := ` mainConfigBasic := `
theme = "test-theme" theme = "test-theme"
@ -291,7 +291,7 @@ map[string]interface {}{
} }
`, got["menus"]) `, got["menus"])
assert.Equal("https://example.com/", got["baseurl"]) c.Assert(got["baseurl"], qt.Equals, "https://example.com/")
if true { if true {
return return
@ -314,7 +314,7 @@ map[string]interface {}{
}, },
}`, got["params"]) }`, got["params"])
assert.Nil(got["languages"]) c.Assert(got["languages"], qt.IsNil)
b.AssertObject(` b.AssertObject(`
map[string]interface {}{ map[string]interface {}{
"text/m1": map[string]interface {}{ "text/m1": map[string]interface {}{
@ -365,7 +365,7 @@ map[string]interface {}{
func TestPrivacyConfig(t *testing.T) { func TestPrivacyConfig(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
tomlConfig := ` tomlConfig := `
@ -380,14 +380,14 @@ privacyEnhanced = true
b.WithConfigFile("toml", tomlConfig) b.WithConfigFile("toml", tomlConfig)
b.Build(BuildCfg{SkipRender: true}) b.Build(BuildCfg{SkipRender: true})
assert.True(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced) c.Assert(b.H.Sites[0].Info.Config().Privacy.YouTube.PrivacyEnhanced, qt.Equals, true)
} }
func TestLoadConfigModules(t *testing.T) { func TestLoadConfigModules(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
// https://github.com/gohugoio/hugoThemes#themetoml // https://github.com/gohugoio/hugoThemes#themetoml
@ -469,18 +469,20 @@ path="n4"
var graphb bytes.Buffer var graphb bytes.Buffer
modulesClient.Graph(&graphb) modulesClient.Graph(&graphb)
assert.Equal(`project n1 expected := `project n1
n1 o1 n1 o1
o1 n2 o1 n2
n1 n3 n1 n3
project n4 project n4
`, graphb.String()) `
c.Assert(graphb.String(), qt.Equals, expected)
} }
func TestLoadConfigWithOsEnvOverrides(t *testing.T) { func TestLoadConfigWithOsEnvOverrides(t *testing.T) {
assert := require.New(t) c := qt.New(t)
baseConfig := ` baseConfig := `
@ -512,13 +514,13 @@ resamplefilter = "CatmullRom"
cfg := b.H.Cfg cfg := b.H.Cfg
assert.Equal("test", cfg.Get("environment")) c.Assert(cfg.Get("environment"), qt.Equals, "test")
assert.Equal(false, cfg.GetBool("enablegitinfo")) c.Assert(cfg.GetBool("enablegitinfo"), qt.Equals, false)
assert.Equal("new", cfg.Get("new")) c.Assert(cfg.Get("new"), qt.Equals, "new")
assert.Equal("top", cfg.Get("imaging.anchor")) c.Assert(cfg.Get("imaging.anchor"), qt.Equals, "top")
assert.Equal(int64(75), cfg.Get("imaging.quality")) c.Assert(cfg.Get("imaging.quality"), qt.Equals, int64(75))
assert.Equal([]interface{}{"c", "d"}, cfg.Get("stringSlice")) c.Assert(cfg.Get("stringSlice"), qt.DeepEquals, []interface{}{"c", "d"})
assert.Equal([]interface{}{5.32}, cfg.Get("floatSlice")) c.Assert(cfg.Get("floatSlice"), qt.DeepEquals, []interface{}{5.32})
assert.Equal([]interface{}{5, 8, 9}, cfg.Get("intSlice")) c.Assert(cfg.Get("intSlice"), qt.DeepEquals, []interface{}{5, 8, 9})
} }

View file

@ -19,15 +19,15 @@ import (
"github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/herrors"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/htesting"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require"
) )
func TestLoadConfigDir(t *testing.T) { func TestLoadConfigDir(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
configContent := ` configContent := `
baseURL = "https://example.org" baseURL = "https://example.org"
@ -107,29 +107,29 @@ p3 = "p3params_no_production"
fb.Build() fb.Build()
cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Environment: "development", Filename: "hugo.toml", AbsConfigDir: "config"}) cfg, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Environment: "development", Filename: "hugo.toml", AbsConfigDir: "config"})
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("pag_development", cfg.GetString("paginatePath")) // /config/development/config.toml c.Assert(cfg.GetString("paginatePath"), qt.Equals, "pag_development") // /config/development/config.toml
assert.Equal(10, cfg.GetInt("languages.no.weight")) // /config.toml c.Assert(cfg.GetInt("languages.no.weight"), qt.Equals, 10) // /config.toml
assert.Equal("Norsk_no_default", cfg.GetString("languages.no.languageName")) // /config/_default/languages.no.toml c.Assert(cfg.GetString("languages.no.languageName"), qt.Equals, "Norsk_no_default") // /config/_default/languages.no.toml
assert.Equal("p1_base", cfg.GetString("params.p1")) c.Assert(cfg.GetString("params.p1"), qt.Equals, "p1_base")
assert.Equal("p2params_default", cfg.GetString("params.p2")) // Is in both _default and production c.Assert(cfg.GetString("params.p2"), qt.Equals, "p2params_default") // Is in both _default and production
assert.Equal("p3params_development", cfg.GetString("params.p3")) c.Assert(cfg.GetString("params.p3"), qt.Equals, "p3params_development")
assert.Equal("p3params_no_development", cfg.GetString("languages.no.params.p3")) c.Assert(cfg.GetString("languages.no.params.p3"), qt.Equals, "p3params_no_development")
assert.Equal(2, len(cfg.Get("menus.docs").(([]map[string]interface{})))) c.Assert(len(cfg.Get("menus.docs").(([]map[string]interface{}))), qt.Equals, 2)
noMenus := cfg.Get("languages.no.menus.docs") noMenus := cfg.Get("languages.no.menus.docs")
assert.NotNil(noMenus) c.Assert(noMenus, qt.Not(qt.IsNil))
assert.Equal(1, len(noMenus.(([]map[string]interface{})))) c.Assert(len(noMenus.(([]map[string]interface{}))), qt.Equals, 1)
} }
func TestLoadConfigDirError(t *testing.T) { func TestLoadConfigDirError(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
configContent := ` configContent := `
baseURL = "https://example.org" baseURL = "https://example.org"
@ -145,10 +145,10 @@ baseURL = "https://example.org"
fb.Add("config.toml", `invalid & syntax`).Build() fb.Add("config.toml", `invalid & syntax`).Build()
_, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Environment: "development", Filename: "hugo.toml", AbsConfigDir: "config"}) _, _, err := LoadConfig(ConfigSourceDescriptor{Fs: mm, Environment: "development", Filename: "hugo.toml", AbsConfigDir: "config"})
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
fe := herrors.UnwrapErrorWithFileContext(err) fe := herrors.UnwrapErrorWithFileContext(err)
assert.NotNil(fe) c.Assert(fe, qt.Not(qt.IsNil))
assert.Equal(filepath.FromSlash("config/development/config.toml"), fe.Position().Filename) c.Assert(fe.Position().Filename, qt.Equals, filepath.FromSlash("config/development/config.toml"))
} }

View file

@ -16,7 +16,6 @@ package hugolib
import ( import (
"path/filepath" "path/filepath"
"reflect" "reflect"
"strings"
"testing" "testing"
"github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/loggers"
@ -26,7 +25,7 @@ import (
"fmt" "fmt"
"runtime" "runtime"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestDataDir(t *testing.T) { func TestDataDir(t *testing.T) {
@ -377,6 +376,7 @@ func TestDataFromShortcode(t *testing.T) {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
c = qt.New(t)
) )
writeSource(t, fs, "data/hugo.toml", "slogan = \"Hugo Rocks!\"") writeSource(t, fs, "data/hugo.toml", "slogan = \"Hugo Rocks!\"")
@ -392,7 +392,7 @@ Slogan from shortcode: {{< d >}}
buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
content := readSource(t, fs, "public/c/index.html") content := readSource(t, fs, "public/c/index.html")
require.True(t, strings.Contains(content, "Slogan from template: Hugo Rocks!"), content)
require.True(t, strings.Contains(content, "Slogan from shortcode: Hugo Rocks!"), content)
c.Assert(content, qt.Contains, "Slogan from template: Hugo Rocks!")
c.Assert(content, qt.Contains, "Slogan from shortcode: Hugo Rocks!")
} }

View file

@ -18,10 +18,10 @@ import (
"fmt" "fmt"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
"github.com/stretchr/testify/require"
) )
func TestDisableKindsNoneDisabled(t *testing.T) { func TestDisableKindsNoneDisabled(t *testing.T) {
@ -104,8 +104,6 @@ categories:
b.Build(BuildCfg{}) b.Build(BuildCfg{})
h := b.H h := b.H
require.Len(t, h.Sites, 1)
assertDisabledKinds(b, h.Sites[0], disabled...) assertDisabledKinds(b, h.Sites[0], disabled...)
} }
@ -181,7 +179,7 @@ func assertDisabledKinds(b *sitesBuilder, s *Site, disabled ...string) {
func assertDisabledKind(b *sitesBuilder, kindAssert func(bool) bool, disabled []string, kind, path, matcher string) { func assertDisabledKind(b *sitesBuilder, kindAssert func(bool) bool, disabled []string, kind, path, matcher string) {
isDisabled := stringSliceContains(kind, disabled...) isDisabled := stringSliceContains(kind, disabled...)
require.True(b.T, kindAssert(isDisabled), fmt.Sprintf("%s: %t", kind, isDisabled)) b.Assert(kindAssert(isDisabled), qt.Equals, true)
if kind == kindRSS && !isDisabled { if kind == kindRSS && !isDisabled {
// If the home page is also disabled, there is not RSS to look for. // If the home page is also disabled, there is not RSS to look for.
@ -193,8 +191,8 @@ func assertDisabledKind(b *sitesBuilder, kindAssert func(bool) bool, disabled []
if isDisabled { if isDisabled {
// Path should not exist // Path should not exist
fileExists, err := helpers.Exists(path, b.Fs.Destination) fileExists, err := helpers.Exists(path, b.Fs.Destination)
require.False(b.T, fileExists) b.Assert(err, qt.IsNil)
require.NoError(b.T, err) b.Assert(fileExists, qt.Equals, false)
} else { } else {
b.AssertFileContent(path, matcher) b.AssertFileContent(path, matcher)

View file

@ -26,8 +26,8 @@ import (
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/tpl"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -45,6 +45,7 @@ func TestShortcodeCrossrefs(t *testing.T) {
func doTestShortcodeCrossrefs(t *testing.T, relative bool) { func doTestShortcodeCrossrefs(t *testing.T, relative bool) {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
c = qt.New(t)
) )
cfg.Set("baseURL", testBaseURL) cfg.Set("baseURL", testBaseURL)
@ -69,10 +70,10 @@ func doTestShortcodeCrossrefs(t *testing.T, relative bool) {
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
content, err := s.RegularPages()[0].Content() content, err := s.RegularPages()[0].Content()
require.NoError(t, err) c.Assert(err, qt.IsNil)
output := cast.ToString(content) output := cast.ToString(content)
if !strings.Contains(output, expected) { if !strings.Contains(output, expected) {
@ -100,7 +101,7 @@ void do();
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
cfg.Set("pygmentsStyle", "bw") cfg.Set("pygmentsStyle", "bw")
@ -148,7 +149,7 @@ func TestShortcodeFigure(t *testing.T) {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`--- writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`---
@ -187,7 +188,7 @@ func TestShortcodeYoutube(t *testing.T) {
} { } {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`--- writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`---
@ -226,7 +227,7 @@ func TestShortcodeVimeo(t *testing.T) {
} { } {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`--- writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`---
@ -259,7 +260,7 @@ func TestShortcodeGist(t *testing.T) {
} { } {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`--- writeSource(t, fs, filepath.Join("content", "simple.md"), fmt.Sprintf(`---
@ -302,7 +303,7 @@ func TestShortcodeTweet(t *testing.T) {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
withTemplate := func(templ tpl.TemplateHandler) error { withTemplate := func(templ tpl.TemplateHandler) error {
@ -357,7 +358,7 @@ func TestShortcodeInstagram(t *testing.T) {
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
withTemplate := func(templ tpl.TemplateHandler) error { withTemplate := func(templ tpl.TemplateHandler) error {

View file

@ -16,7 +16,7 @@ package hugolib
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
// Just some simple test of the embedded templates to avoid // Just some simple test of the embedded templates to avoid
@ -25,8 +25,8 @@ import (
func _TestEmbeddedTemplates(t *testing.T) { func _TestEmbeddedTemplates(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
assert.True(true) c.Assert(true, qt.Equals, true)
home := []string{"index.html", ` home := []string{"index.html", `
GA: GA:

View file

@ -16,16 +16,16 @@ package hugolib
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/cast" "github.com/spf13/cast"
"github.com/stretchr/testify/require"
) )
func TestFileInfo(t *testing.T) { func TestFileInfo(t *testing.T) {
t.Run("String", func(t *testing.T) { t.Run("String", func(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
fi := &fileInfo{} fi := &fileInfo{}
_, err := cast.ToStringE(fi) _, err := cast.ToStringE(fi)
assert.NoError(err) c.Assert(err, qt.IsNil)
}) })
} }

View file

@ -27,11 +27,11 @@ import (
"github.com/spf13/afero" "github.com/spf13/afero"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/gohugoio/hugo/hugolib/paths" "github.com/gohugoio/hugo/hugolib/paths"
"github.com/gohugoio/hugo/modules" "github.com/gohugoio/hugo/modules"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func initConfig(fs afero.Fs, cfg config.Provider) error { func initConfig(fs afero.Fs, cfg config.Provider) error {
@ -72,7 +72,7 @@ func initConfig(fs afero.Fs, cfg config.Provider) error {
} }
func TestNewBaseFs(t *testing.T) { func TestNewBaseFs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := viper.New() v := viper.New()
fs := hugofs.NewMem(v) fs := hugofs.NewMem(v)
@ -119,54 +119,52 @@ theme = ["atheme"]
setConfigAndWriteSomeFilesTo(fs.Source, v, "resourceDir", "myrsesource", 10) setConfigAndWriteSomeFilesTo(fs.Source, v, "resourceDir", "myrsesource", 10)
v.Set("publishDir", "public") v.Set("publishDir", "public")
assert.NoError(initConfig(fs.Source, v)) c.Assert(initConfig(fs.Source, v), qt.IsNil)
p, err := paths.New(fs, v) p, err := paths.New(fs, v)
assert.NoError(err) c.Assert(err, qt.IsNil)
bfs, err := NewBase(p, nil) bfs, err := NewBase(p, nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(bfs) c.Assert(bfs, qt.Not(qt.IsNil))
root, err := bfs.I18n.Fs.Open("") root, err := bfs.I18n.Fs.Open("")
assert.NoError(err) c.Assert(err, qt.IsNil)
dirnames, err := root.Readdirnames(-1) dirnames, err := root.Readdirnames(-1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f3.txt", "theme-file-btheme.txt", "f3.txt", "theme-file-atheme.txt"}, dirnames) c.Assert(dirnames, qt.DeepEquals, []string{"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f3.txt", "theme-file-btheme.txt", "f3.txt", "theme-file-atheme.txt"})
root, err = bfs.Data.Fs.Open("") root, err = bfs.Data.Fs.Open("")
assert.NoError(err) c.Assert(err, qt.IsNil)
dirnames, err = root.Readdirnames(-1) dirnames, err = root.Readdirnames(-1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal([]string{"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f5.txt", "f6.txt", "f7.txt", "f3.txt", "theme-file-btheme.txt", "f3.txt", "theme-file-atheme.txt"}, dirnames) c.Assert(dirnames, qt.DeepEquals, []string{"f1.txt", "f2.txt", "f3.txt", "f4.txt", "f5.txt", "f6.txt", "f7.txt", "f3.txt", "theme-file-btheme.txt", "f3.txt", "theme-file-atheme.txt"})
//printFs(bfs.Work, "", os.Stdout) checkFileCount(bfs.Layouts.Fs, "", c, 7)
checkFileCount(bfs.Layouts.Fs, "", assert, 7) checkFileCount(bfs.Content.Fs, "", c, 3)
checkFileCount(bfs.I18n.Fs, "", c, 8) // 4 + 4 themes
checkFileCount(bfs.Content.Fs, "", assert, 3) checkFileCount(bfs.Static[""].Fs, "", c, 6)
checkFileCount(bfs.I18n.Fs, "", assert, 8) // 4 + 4 themes checkFileCount(bfs.Data.Fs, "", c, 11) // 7 + 4 themes
checkFileCount(bfs.Archetypes.Fs, "", c, 10) // 8 + 2 themes
checkFileCount(bfs.Assets.Fs, "", c, 9)
checkFileCount(bfs.Work, "", c, 82)
checkFileCount(bfs.Static[""].Fs, "", assert, 6) c.Assert(bfs.IsData(filepath.Join(workingDir, "mydata", "file1.txt")), qt.Equals, true)
checkFileCount(bfs.Data.Fs, "", assert, 11) // 7 + 4 themes c.Assert(bfs.IsI18n(filepath.Join(workingDir, "myi18n", "file1.txt")), qt.Equals, true)
checkFileCount(bfs.Archetypes.Fs, "", assert, 10) // 8 + 2 themes c.Assert(bfs.IsLayout(filepath.Join(workingDir, "mylayouts", "file1.txt")), qt.Equals, true)
checkFileCount(bfs.Assets.Fs, "", assert, 9) c.Assert(bfs.IsStatic(filepath.Join(workingDir, "mystatic", "file1.txt")), qt.Equals, true)
checkFileCount(bfs.Work, "", assert, 82) c.Assert(bfs.IsAsset(filepath.Join(workingDir, "myassets", "file1.txt")), qt.Equals, true)
assert.True(bfs.IsData(filepath.Join(workingDir, "mydata", "file1.txt")))
assert.True(bfs.IsI18n(filepath.Join(workingDir, "myi18n", "file1.txt")))
assert.True(bfs.IsLayout(filepath.Join(workingDir, "mylayouts", "file1.txt")))
assert.True(bfs.IsStatic(filepath.Join(workingDir, "mystatic", "file1.txt")))
assert.True(bfs.IsAsset(filepath.Join(workingDir, "myassets", "file1.txt")))
contentFilename := filepath.Join(workingDir, "mycontent", "file1.txt") contentFilename := filepath.Join(workingDir, "mycontent", "file1.txt")
assert.True(bfs.IsContent(contentFilename)) c.Assert(bfs.IsContent(contentFilename), qt.Equals, true)
rel := bfs.RelContentDir(contentFilename) rel := bfs.RelContentDir(contentFilename)
assert.Equal("file1.txt", rel) c.Assert(rel, qt.Equals, "file1.txt")
// Check Work fs vs theme // Check Work fs vs theme
checkFileContent(bfs.Work, "file-root.txt", assert, "content-project") checkFileContent(bfs.Work, "file-root.txt", c, "content-project")
checkFileContent(bfs.Work, "theme-root-atheme.txt", assert, "content:atheme") checkFileContent(bfs.Work, "theme-root-atheme.txt", c, "content:atheme")
// https://github.com/gohugoio/hugo/issues/5318 // https://github.com/gohugoio/hugo/issues/5318
// Check both project and theme. // Check both project and theme.
@ -174,10 +172,10 @@ theme = ["atheme"]
for _, filename := range []string{"/f1.txt", "/theme-file-atheme.txt"} { for _, filename := range []string{"/f1.txt", "/theme-file-atheme.txt"} {
filename = filepath.FromSlash(filename) filename = filepath.FromSlash(filename)
f, err := fs.Open(filename) f, err := fs.Open(filename)
assert.NoError(err) c.Assert(err, qt.IsNil)
name := f.Name() name := f.Name()
f.Close() f.Close()
assert.Equal(filename, name) c.Assert(name, qt.Equals, filename)
} }
} }
} }
@ -199,35 +197,35 @@ func createConfig() *viper.Viper {
} }
func TestNewBaseFsEmpty(t *testing.T) { func TestNewBaseFsEmpty(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := createConfig() v := createConfig()
fs := hugofs.NewMem(v) fs := hugofs.NewMem(v)
assert.NoError(initConfig(fs.Source, v)) c.Assert(initConfig(fs.Source, v), qt.IsNil)
p, err := paths.New(fs, v) p, err := paths.New(fs, v)
assert.NoError(err) c.Assert(err, qt.IsNil)
bfs, err := NewBase(p, nil) bfs, err := NewBase(p, nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(bfs) c.Assert(bfs, qt.Not(qt.IsNil))
assert.NotNil(bfs.Archetypes.Fs) c.Assert(bfs.Archetypes.Fs, qt.Not(qt.IsNil))
assert.NotNil(bfs.Layouts.Fs) c.Assert(bfs.Layouts.Fs, qt.Not(qt.IsNil))
assert.NotNil(bfs.Data.Fs) c.Assert(bfs.Data.Fs, qt.Not(qt.IsNil))
assert.NotNil(bfs.I18n.Fs) c.Assert(bfs.I18n.Fs, qt.Not(qt.IsNil))
assert.NotNil(bfs.Work) c.Assert(bfs.Work, qt.Not(qt.IsNil))
assert.NotNil(bfs.Content.Fs) c.Assert(bfs.Content.Fs, qt.Not(qt.IsNil))
assert.NotNil(bfs.Static) c.Assert(bfs.Static, qt.Not(qt.IsNil))
} }
func TestRealDirs(t *testing.T) { func TestRealDirs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := createConfig() v := createConfig()
fs := hugofs.NewDefault(v) fs := hugofs.NewDefault(v)
sfs := fs.Source sfs := fs.Source
root, err := afero.TempDir(sfs, "", "realdir") root, err := afero.TempDir(sfs, "", "realdir")
assert.NoError(err) c.Assert(err, qt.IsNil)
themesDir, err := afero.TempDir(sfs, "", "themesDir") themesDir, err := afero.TempDir(sfs, "", "themesDir")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer func() { defer func() {
os.RemoveAll(root) os.RemoveAll(root)
os.RemoveAll(themesDir) os.RemoveAll(themesDir)
@ -237,14 +235,14 @@ func TestRealDirs(t *testing.T) {
v.Set("themesDir", themesDir) v.Set("themesDir", themesDir)
v.Set("theme", "mytheme") v.Set("theme", "mytheme")
assert.NoError(sfs.MkdirAll(filepath.Join(root, "myassets", "scss", "sf1"), 0755)) c.Assert(sfs.MkdirAll(filepath.Join(root, "myassets", "scss", "sf1"), 0755), qt.IsNil)
assert.NoError(sfs.MkdirAll(filepath.Join(root, "myassets", "scss", "sf2"), 0755)) c.Assert(sfs.MkdirAll(filepath.Join(root, "myassets", "scss", "sf2"), 0755), qt.IsNil)
assert.NoError(sfs.MkdirAll(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf2"), 0755)) c.Assert(sfs.MkdirAll(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf2"), 0755), qt.IsNil)
assert.NoError(sfs.MkdirAll(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf3"), 0755)) c.Assert(sfs.MkdirAll(filepath.Join(themesDir, "mytheme", "assets", "scss", "sf3"), 0755), qt.IsNil)
assert.NoError(sfs.MkdirAll(filepath.Join(root, "resources"), 0755)) c.Assert(sfs.MkdirAll(filepath.Join(root, "resources"), 0755), qt.IsNil)
assert.NoError(sfs.MkdirAll(filepath.Join(themesDir, "mytheme", "resources"), 0755)) c.Assert(sfs.MkdirAll(filepath.Join(themesDir, "mytheme", "resources"), 0755), qt.IsNil)
assert.NoError(sfs.MkdirAll(filepath.Join(root, "myassets", "js", "f2"), 0755)) c.Assert(sfs.MkdirAll(filepath.Join(root, "myassets", "js", "f2"), 0755), qt.IsNil)
afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "scss", "sf1", "a1.scss")), []byte("content"), 0755) afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "scss", "sf1", "a1.scss")), []byte("content"), 0755)
afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "scss", "sf2", "a3.scss")), []byte("content"), 0755) afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "scss", "sf2", "a3.scss")), []byte("content"), 0755)
@ -259,27 +257,27 @@ func TestRealDirs(t *testing.T) {
afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "js", "f2", "a1.js")), []byte("content"), 0755) afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "js", "f2", "a1.js")), []byte("content"), 0755)
afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "js", "a2.js")), []byte("content"), 0755) afero.WriteFile(sfs, filepath.Join(filepath.Join(root, "myassets", "js", "a2.js")), []byte("content"), 0755)
assert.NoError(initConfig(fs.Source, v)) c.Assert(initConfig(fs.Source, v), qt.IsNil)
p, err := paths.New(fs, v) p, err := paths.New(fs, v)
assert.NoError(err) c.Assert(err, qt.IsNil)
bfs, err := NewBase(p, nil) bfs, err := NewBase(p, nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NotNil(bfs) c.Assert(bfs, qt.Not(qt.IsNil))
checkFileCount(bfs.Assets.Fs, "", assert, 6) checkFileCount(bfs.Assets.Fs, "", c, 6)
realDirs := bfs.Assets.RealDirs("scss") realDirs := bfs.Assets.RealDirs("scss")
assert.Equal(2, len(realDirs)) c.Assert(len(realDirs), qt.Equals, 2)
assert.Equal(filepath.Join(root, "myassets/scss"), realDirs[0]) c.Assert(realDirs[0], qt.Equals, filepath.Join(root, "myassets/scss"))
assert.Equal(filepath.Join(themesDir, "mytheme/assets/scss"), realDirs[len(realDirs)-1]) c.Assert(realDirs[len(realDirs)-1], qt.Equals, filepath.Join(themesDir, "mytheme/assets/scss"))
assert.NotNil(bfs.theBigFs) c.Assert(bfs.theBigFs, qt.Not(qt.IsNil))
} }
func TestStaticFs(t *testing.T) { func TestStaticFs(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := createConfig() v := createConfig()
workDir := "mywork" workDir := "mywork"
v.Set("workingDir", workDir) v.Set("workingDir", workDir)
@ -296,21 +294,21 @@ func TestStaticFs(t *testing.T) {
afero.WriteFile(fs.Source, filepath.Join(themeStaticDir, "f2.txt"), []byte("Hugo Themes Still Rocks!"), 0755) afero.WriteFile(fs.Source, filepath.Join(themeStaticDir, "f2.txt"), []byte("Hugo Themes Still Rocks!"), 0755)
afero.WriteFile(fs.Source, filepath.Join(themeStaticDir2, "f2.txt"), []byte("Hugo Themes Rocks in t2!"), 0755) afero.WriteFile(fs.Source, filepath.Join(themeStaticDir2, "f2.txt"), []byte("Hugo Themes Rocks in t2!"), 0755)
assert.NoError(initConfig(fs.Source, v)) c.Assert(initConfig(fs.Source, v), qt.IsNil)
p, err := paths.New(fs, v) p, err := paths.New(fs, v)
assert.NoError(err) c.Assert(err, qt.IsNil)
bfs, err := NewBase(p, nil) bfs, err := NewBase(p, nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
sfs := bfs.StaticFs("en") sfs := bfs.StaticFs("en")
checkFileContent(sfs, "f1.txt", assert, "Hugo Rocks!") checkFileContent(sfs, "f1.txt", c, "Hugo Rocks!")
checkFileContent(sfs, "f2.txt", assert, "Hugo Themes Still Rocks!") checkFileContent(sfs, "f2.txt", c, "Hugo Themes Still Rocks!")
} }
func TestStaticFsMultiHost(t *testing.T) { func TestStaticFsMultiHost(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := createConfig() v := createConfig()
workDir := "mywork" workDir := "mywork"
v.Set("workingDir", workDir) v.Set("workingDir", workDir)
@ -340,30 +338,30 @@ func TestStaticFsMultiHost(t *testing.T) {
afero.WriteFile(fs.Source, filepath.Join(themeStaticDir, "f1.txt"), []byte("Hugo Themes Rocks!"), 0755) afero.WriteFile(fs.Source, filepath.Join(themeStaticDir, "f1.txt"), []byte("Hugo Themes Rocks!"), 0755)
afero.WriteFile(fs.Source, filepath.Join(themeStaticDir, "f2.txt"), []byte("Hugo Themes Still Rocks!"), 0755) afero.WriteFile(fs.Source, filepath.Join(themeStaticDir, "f2.txt"), []byte("Hugo Themes Still Rocks!"), 0755)
assert.NoError(initConfig(fs.Source, v)) c.Assert(initConfig(fs.Source, v), qt.IsNil)
p, err := paths.New(fs, v) p, err := paths.New(fs, v)
assert.NoError(err) c.Assert(err, qt.IsNil)
bfs, err := NewBase(p, nil) bfs, err := NewBase(p, nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
enFs := bfs.StaticFs("en") enFs := bfs.StaticFs("en")
checkFileContent(enFs, "f1.txt", assert, "Hugo Rocks!") checkFileContent(enFs, "f1.txt", c, "Hugo Rocks!")
checkFileContent(enFs, "f2.txt", assert, "Hugo Themes Still Rocks!") checkFileContent(enFs, "f2.txt", c, "Hugo Themes Still Rocks!")
noFs := bfs.StaticFs("no") noFs := bfs.StaticFs("no")
checkFileContent(noFs, "f1.txt", assert, "Hugo Rocks in Norway!") checkFileContent(noFs, "f1.txt", c, "Hugo Rocks in Norway!")
checkFileContent(noFs, "f2.txt", assert, "Hugo Themes Still Rocks!") checkFileContent(noFs, "f2.txt", c, "Hugo Themes Still Rocks!")
} }
func TestMakePathRelative(t *testing.T) { func TestMakePathRelative(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := createConfig() v := createConfig()
fs := hugofs.NewMem(v) fs := hugofs.NewMem(v)
workDir := "mywork" workDir := "mywork"
v.Set("workingDir", workDir) v.Set("workingDir", workDir)
assert.NoError(fs.Source.MkdirAll(filepath.Join(workDir, "dist"), 0777)) c.Assert(fs.Source.MkdirAll(filepath.Join(workDir, "dist"), 0777), qt.IsNil)
assert.NoError(fs.Source.MkdirAll(filepath.Join(workDir, "static"), 0777)) c.Assert(fs.Source.MkdirAll(filepath.Join(workDir, "static"), 0777), qt.IsNil)
moduleCfg := map[string]interface{}{ moduleCfg := map[string]interface{}{
"mounts": []interface{}{ "mounts": []interface{}{
@ -380,35 +378,35 @@ func TestMakePathRelative(t *testing.T) {
v.Set("module", moduleCfg) v.Set("module", moduleCfg)
assert.NoError(initConfig(fs.Source, v)) c.Assert(initConfig(fs.Source, v), qt.IsNil)
p, err := paths.New(fs, v) p, err := paths.New(fs, v)
assert.NoError(err) c.Assert(err, qt.IsNil)
bfs, err := NewBase(p, nil) bfs, err := NewBase(p, nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
sfs := bfs.Static[""] sfs := bfs.Static[""]
assert.NotNil(sfs) c.Assert(sfs, qt.Not(qt.IsNil))
assert.Equal(filepath.FromSlash("/foo.txt"), sfs.MakePathRelative(filepath.Join(workDir, "static", "foo.txt"))) c.Assert(sfs.MakePathRelative(filepath.Join(workDir, "static", "foo.txt")), qt.Equals, filepath.FromSlash("/foo.txt"))
assert.Equal(filepath.FromSlash("/dist/foo.txt"), sfs.MakePathRelative(filepath.Join(workDir, "dist", "foo.txt"))) c.Assert(sfs.MakePathRelative(filepath.Join(workDir, "dist", "foo.txt")), qt.Equals, filepath.FromSlash("/dist/foo.txt"))
} }
func checkFileCount(fs afero.Fs, dirname string, assert *require.Assertions, expected int) { func checkFileCount(fs afero.Fs, dirname string, c *qt.C, expected int) {
count, fnames, err := countFileaAndGetFilenames(fs, dirname) count, _, err := countFileaAndGetFilenames(fs, dirname)
assert.NoError(err, fnames) c.Assert(err, qt.IsNil)
assert.Equal(expected, count, fnames) c.Assert(count, qt.Equals, expected)
} }
func checkFileContent(fs afero.Fs, filename string, assert *require.Assertions, expected ...string) { func checkFileContent(fs afero.Fs, filename string, c *qt.C, expected ...string) {
b, err := afero.ReadFile(fs, filename) b, err := afero.ReadFile(fs, filename)
assert.NoError(err) c.Assert(err, qt.IsNil)
content := string(b) content := string(b)
for _, e := range expected { for _, e := range expected {
assert.Contains(content, e) c.Assert(content, qt.Contains, e)
} }
} }

View file

@ -33,9 +33,9 @@ import (
"github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/htesting"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/testmodBuilder/mods" "github.com/gohugoio/testmodBuilder/mods"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
// TODO(bep) this fails when testmodBuilder is also building ... // TODO(bep) this fails when testmodBuilder is also building ...
@ -60,12 +60,12 @@ func TestHugoModules(t *testing.T) {
rnd.Shuffle(len(testmods), func(i, j int) { testmods[i], testmods[j] = testmods[j], testmods[i] }) rnd.Shuffle(len(testmods), func(i, j int) { testmods[i], testmods[j] = testmods[j], testmods[i] })
for _, m := range testmods[:2] { for _, m := range testmods[:2] {
assert := require.New(t) c := qt.New(t)
v := viper.New() v := viper.New()
workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-test") workingDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-modules-test")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer clean() defer clean()
configTemplate := ` configTemplate := `
@ -375,9 +375,9 @@ min_version = "5.0.0"
b.Build(BuildCfg{}) b.Build(BuildCfg{})
assert := require.New(t) c := qt.New(t)
assert.Equal(uint64(2), logger.WarnCounter.Count()) c.Assert(logger.WarnCounter.Count(), qt.Equals, uint64(2))
} }
@ -389,13 +389,13 @@ func TestModulesSymlinks(t *testing.T) {
os.Chdir(wd) os.Chdir(wd)
}() }()
assert := require.New(t) c := qt.New(t)
// We need to use the OS fs for this. // We need to use the OS fs for this.
cfg := viper.New() cfg := viper.New()
fs := hugofs.NewFrom(hugofs.Os, cfg) fs := hugofs.NewFrom(hugofs.Os, cfg)
workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mod-sym") workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-mod-sym")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer clean() defer clean()
@ -406,11 +406,11 @@ Data: {{ .Site.Data }}
createDirsAndFiles := func(baseDir string) { createDirsAndFiles := func(baseDir string) {
for _, dir := range files.ComponentFolders { for _, dir := range files.ComponentFolders {
realDir := filepath.Join(baseDir, dir, "real") realDir := filepath.Join(baseDir, dir, "real")
assert.NoError(os.MkdirAll(realDir, 0777)) c.Assert(os.MkdirAll(realDir, 0777), qt.IsNil)
assert.NoError(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0777)) c.Assert(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0777), qt.IsNil)
} }
assert.NoError(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0777)) c.Assert(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0777), qt.IsNil)
} }
// Create project dirs and files. // Create project dirs and files.
@ -421,10 +421,10 @@ Data: {{ .Site.Data }}
createSymlinks := func(baseDir, id string) { createSymlinks := func(baseDir, id string) {
for _, dir := range files.ComponentFolders { for _, dir := range files.ComponentFolders {
assert.NoError(os.Chdir(filepath.Join(baseDir, dir))) c.Assert(os.Chdir(filepath.Join(baseDir, dir)), qt.IsNil)
assert.NoError(os.Symlink("real", fmt.Sprintf("realsym%s", id))) c.Assert(os.Symlink("real", fmt.Sprintf("realsym%s", id)), qt.IsNil)
assert.NoError(os.Chdir(filepath.Join(baseDir, dir, "real"))) c.Assert(os.Chdir(filepath.Join(baseDir, dir, "real")), qt.IsNil)
assert.NoError(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id))) c.Assert(os.Symlink("data.toml", fmt.Sprintf(filepath.FromSlash("datasym%s.toml"), id)), qt.IsNil)
} }
} }
@ -451,7 +451,7 @@ weight = 2
b.Fs = fs b.Fs = fs
b.WithConfigFile("toml", config) b.WithConfigFile("toml", config)
assert.NoError(os.Chdir(workDir)) c.Assert(os.Chdir(workDir), qt.IsNil)
b.Build(BuildCfg{}) b.Build(BuildCfg{})
@ -493,10 +493,10 @@ weight = 2
} }
if shouldFail { if shouldFail {
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
assert.Equal(hugofs.ErrPermissionSymlink, err, filename) c.Assert(err, qt.Equals, hugofs.ErrPermissionSymlink)
} else { } else {
assert.NoError(err, filename) c.Assert(err, qt.IsNil)
} }
} }

View file

@ -11,31 +11,31 @@ import (
"github.com/fortytw2/leaktest" "github.com/fortytw2/leaktest"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/herrors"
"github.com/stretchr/testify/require"
) )
type testSiteBuildErrorAsserter struct { type testSiteBuildErrorAsserter struct {
name string name string
assert *require.Assertions c *qt.C
} }
func (t testSiteBuildErrorAsserter) getFileError(err error) *herrors.ErrorWithFileContext { func (t testSiteBuildErrorAsserter) getFileError(err error) *herrors.ErrorWithFileContext {
t.assert.NotNil(err, t.name) t.c.Assert(err, qt.Not(qt.IsNil), qt.Commentf(t.name))
ferr := herrors.UnwrapErrorWithFileContext(err) ferr := herrors.UnwrapErrorWithFileContext(err)
t.assert.NotNil(ferr, fmt.Sprintf("[%s] got %T: %+v\n%s", t.name, err, err, stackTrace())) t.c.Assert(ferr, qt.Not(qt.IsNil))
return ferr return ferr
} }
func (t testSiteBuildErrorAsserter) assertLineNumber(lineNumber int, err error) { func (t testSiteBuildErrorAsserter) assertLineNumber(lineNumber int, err error) {
fe := t.getFileError(err) fe := t.getFileError(err)
t.assert.Equal(lineNumber, fe.Position().LineNumber, fmt.Sprintf("[%s] got => %s\n%s", t.name, fe, stackTrace())) t.c.Assert(fe.Position().LineNumber, qt.Equals, lineNumber)
} }
func (t testSiteBuildErrorAsserter) assertErrorMessage(e1, e2 string) { func (t testSiteBuildErrorAsserter) assertErrorMessage(e1, e2 string) {
// The error message will contain filenames with OS slashes. Normalize before compare. // The error message will contain filenames with OS slashes. Normalize before compare.
e1, e2 = filepath.ToSlash(e1), filepath.ToSlash(e2) e1, e2 = filepath.ToSlash(e1), filepath.ToSlash(e2)
t.assert.Contains(e2, e1, stackTrace()) t.c.Assert(e2, qt.Contains, e1)
} }
@ -89,9 +89,9 @@ func TestSiteBuildErrors(t *testing.T) {
}, },
assertCreateError: func(a testSiteBuildErrorAsserter, err error) { assertCreateError: func(a testSiteBuildErrorAsserter, err error) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(5, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5)
a.assert.Equal(1, fe.Position().ColumnNumber) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 1)
a.assert.Equal("go-html-template", fe.ChromaLexer) a.c.Assert(fe.ChromaLexer, qt.Equals, "go-html-template")
a.assertErrorMessage("\"layouts/_default/single.html:5:1\": parse failed: template: _default/single.html:5: unexpected \"}\" in operand", fe.Error()) a.assertErrorMessage("\"layouts/_default/single.html:5:1\": parse failed: template: _default/single.html:5: unexpected \"}\" in operand", fe.Error())
}, },
@ -104,9 +104,9 @@ func TestSiteBuildErrors(t *testing.T) {
}, },
assertBuildError: func(a testSiteBuildErrorAsserter, err error) { assertBuildError: func(a testSiteBuildErrorAsserter, err error) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(5, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5)
a.assert.Equal(14, fe.Position().ColumnNumber) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 14)
a.assert.Equal("go-html-template", fe.ChromaLexer) a.c.Assert(fe.ChromaLexer, qt.Equals, "go-html-template")
a.assertErrorMessage("\"layouts/_default/single.html:5:14\": execute of template failed", fe.Error()) a.assertErrorMessage("\"layouts/_default/single.html:5:14\": execute of template failed", fe.Error())
}, },
@ -119,9 +119,9 @@ func TestSiteBuildErrors(t *testing.T) {
}, },
assertBuildError: func(a testSiteBuildErrorAsserter, err error) { assertBuildError: func(a testSiteBuildErrorAsserter, err error) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(5, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5)
a.assert.Equal(14, fe.Position().ColumnNumber) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 14)
a.assert.Equal("go-html-template", fe.ChromaLexer) a.c.Assert(fe.ChromaLexer, qt.Equals, "go-html-template")
a.assertErrorMessage("\"layouts/_default/single.html:5:14\": execute of template failed", fe.Error()) a.assertErrorMessage("\"layouts/_default/single.html:5:14\": execute of template failed", fe.Error())
}, },
@ -144,8 +144,8 @@ func TestSiteBuildErrors(t *testing.T) {
}, },
assertBuildError: func(a testSiteBuildErrorAsserter, err error) { assertBuildError: func(a testSiteBuildErrorAsserter, err error) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(7, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 7)
a.assert.Equal("md", fe.ChromaLexer) a.c.Assert(fe.ChromaLexer, qt.Equals, "md")
// Make sure that it contains both the content file and template // Make sure that it contains both the content file and template
a.assertErrorMessage(`content/myyaml.md:7:10": failed to render shortcode "sc"`, fe.Error()) a.assertErrorMessage(`content/myyaml.md:7:10": failed to render shortcode "sc"`, fe.Error())
a.assertErrorMessage(`shortcodes/sc.html:4:22: executing "shortcodes/sc.html" at <.Page.Titles>: can't evaluate`, fe.Error()) a.assertErrorMessage(`shortcodes/sc.html:4:22: executing "shortcodes/sc.html" at <.Page.Titles>: can't evaluate`, fe.Error())
@ -159,9 +159,9 @@ func TestSiteBuildErrors(t *testing.T) {
}, },
assertBuildError: func(a testSiteBuildErrorAsserter, err error) { assertBuildError: func(a testSiteBuildErrorAsserter, err error) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(7, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 7)
a.assert.Equal(10, fe.Position().ColumnNumber) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 10)
a.assert.Equal("md", fe.ChromaLexer) a.c.Assert(fe.ChromaLexer, qt.Equals, "md")
a.assertErrorMessage(`"content/myyaml.md:7:10": failed to extract shortcode: template for shortcode "nono" not found`, fe.Error()) a.assertErrorMessage(`"content/myyaml.md:7:10": failed to extract shortcode: template for shortcode "nono" not found`, fe.Error())
}, },
}, },
@ -183,8 +183,8 @@ func TestSiteBuildErrors(t *testing.T) {
}, },
assertBuildError: func(a testSiteBuildErrorAsserter, err error) { assertBuildError: func(a testSiteBuildErrorAsserter, err error) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(6, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 6)
a.assert.Equal("toml", fe.ErrorContext.ChromaLexer) a.c.Assert(fe.ErrorContext.ChromaLexer, qt.Equals, "toml")
}, },
}, },
@ -197,8 +197,8 @@ func TestSiteBuildErrors(t *testing.T) {
assertBuildError: func(a testSiteBuildErrorAsserter, err error) { assertBuildError: func(a testSiteBuildErrorAsserter, err error) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(3, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 3)
a.assert.Equal("json", fe.ErrorContext.ChromaLexer) a.c.Assert(fe.ErrorContext.ChromaLexer, qt.Equals, "json")
}, },
}, },
@ -211,14 +211,14 @@ func TestSiteBuildErrors(t *testing.T) {
}, },
assertBuildError: func(a testSiteBuildErrorAsserter, err error) { assertBuildError: func(a testSiteBuildErrorAsserter, err error) {
a.assert.Error(err) a.c.Assert(err, qt.Not(qt.IsNil))
// This is fixed in latest Go source // This is fixed in latest Go source
if regexp.MustCompile("devel|12").MatchString(runtime.Version()) { if regexp.MustCompile("devel|12").MatchString(runtime.Version()) {
fe := a.getFileError(err) fe := a.getFileError(err)
a.assert.Equal(5, fe.Position().LineNumber) a.c.Assert(fe.Position().LineNumber, qt.Equals, 5)
a.assert.Equal(21, fe.Position().ColumnNumber) a.c.Assert(fe.Position().ColumnNumber, qt.Equals, 21)
} else { } else {
a.assert.Contains(err.Error(), `execute of template failed: panic in Execute`) a.c.Assert(err.Error(), qt.Contains, `execute of template failed: panic in Execute`)
} }
}, },
}, },
@ -228,10 +228,10 @@ func TestSiteBuildErrors(t *testing.T) {
test := test test := test
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
errorAsserter := testSiteBuildErrorAsserter{ errorAsserter := testSiteBuildErrorAsserter{
assert: assert, c: c,
name: test.name, name: test.name,
} }
b := newTestSitesBuilder(t).WithSimpleConfigFile() b := newTestSitesBuilder(t).WithSimpleConfigFile()
@ -306,7 +306,7 @@ Some content.
if test.assertCreateError != nil { if test.assertCreateError != nil {
test.assertCreateError(errorAsserter, createErr) test.assertCreateError(errorAsserter, createErr)
} else { } else {
assert.NoError(createErr) c.Assert(createErr, qt.IsNil)
} }
if createErr == nil { if createErr == nil {
@ -314,7 +314,7 @@ Some content.
if test.assertBuildError != nil { if test.assertBuildError != nil {
test.assertBuildError(errorAsserter, buildErr) test.assertBuildError(errorAsserter, buildErr)
} else { } else {
assert.NoError(buildErr) c.Assert(buildErr, qt.IsNil)
} }
} }
}) })

View file

@ -8,6 +8,7 @@ import (
"path/filepath" "path/filepath"
"time" "time"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/fortytw2/leaktest" "github.com/fortytw2/leaktest"
@ -15,7 +16,6 @@ import (
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require"
) )
func TestMultiSitesMainLangInRoot(t *testing.T) { func TestMultiSitesMainLangInRoot(t *testing.T) {
@ -26,7 +26,7 @@ func TestMultiSitesMainLangInRoot(t *testing.T) {
} }
func doTestMultiSitesMainLangInRoot(t *testing.T, defaultInSubDir bool) { func doTestMultiSitesMainLangInRoot(t *testing.T, defaultInSubDir bool) {
assert := require.New(t) c := qt.New(t)
siteConfig := map[string]interface{}{ siteConfig := map[string]interface{}{
"DefaultContentLanguage": "fr", "DefaultContentLanguage": "fr",
@ -49,29 +49,28 @@ func doTestMultiSitesMainLangInRoot(t *testing.T, defaultInSubDir bool) {
b.Build(BuildCfg{}) b.Build(BuildCfg{})
sites := b.H.Sites sites := b.H.Sites
c.Assert(len(sites), qt.Equals, 4)
require.Len(t, sites, 4)
enSite := sites[0] enSite := sites[0]
frSite := sites[1] frSite := sites[1]
assert.Equal("/en", enSite.Info.LanguagePrefix) c.Assert(enSite.Info.LanguagePrefix, qt.Equals, "/en")
if defaultInSubDir { if defaultInSubDir {
assert.Equal("/fr", frSite.Info.LanguagePrefix) c.Assert(frSite.Info.LanguagePrefix, qt.Equals, "/fr")
} else { } else {
assert.Equal("", frSite.Info.LanguagePrefix) c.Assert(frSite.Info.LanguagePrefix, qt.Equals, "")
} }
assert.Equal("/blog/en/foo", enSite.PathSpec.RelURL("foo", true)) c.Assert(enSite.PathSpec.RelURL("foo", true), qt.Equals, "/blog/en/foo")
doc1en := enSite.RegularPages()[0] doc1en := enSite.RegularPages()[0]
doc1fr := frSite.RegularPages()[0] doc1fr := frSite.RegularPages()[0]
enPerm := doc1en.Permalink() enPerm := doc1en.Permalink()
enRelPerm := doc1en.RelPermalink() enRelPerm := doc1en.RelPermalink()
assert.Equal("http://example.com/blog/en/sect/doc1-slug/", enPerm) c.Assert(enPerm, qt.Equals, "http://example.com/blog/en/sect/doc1-slug/")
assert.Equal("/blog/en/sect/doc1-slug/", enRelPerm) c.Assert(enRelPerm, qt.Equals, "/blog/en/sect/doc1-slug/")
frPerm := doc1fr.Permalink() frPerm := doc1fr.Permalink()
frRelPerm := doc1fr.RelPermalink() frRelPerm := doc1fr.RelPermalink()
@ -80,15 +79,15 @@ func doTestMultiSitesMainLangInRoot(t *testing.T, defaultInSubDir bool) {
b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Single", "Hello") b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Single", "Hello")
if defaultInSubDir { if defaultInSubDir {
assert.Equal("http://example.com/blog/fr/sect/doc1/", frPerm) c.Assert(frPerm, qt.Equals, "http://example.com/blog/fr/sect/doc1/")
assert.Equal("/blog/fr/sect/doc1/", frRelPerm) c.Assert(frRelPerm, qt.Equals, "/blog/fr/sect/doc1/")
// should have a redirect on top level. // should have a redirect on top level.
b.AssertFileContent("public/index.html", `<meta http-equiv="refresh" content="0; url=http://example.com/blog/fr" />`) b.AssertFileContent("public/index.html", `<meta http-equiv="refresh" content="0; url=http://example.com/blog/fr" />`)
} else { } else {
// Main language in root // Main language in root
assert.Equal("http://example.com/blog/sect/doc1/", frPerm) c.Assert(frPerm, qt.Equals, "http://example.com/blog/sect/doc1/")
assert.Equal("/blog/sect/doc1/", frRelPerm) c.Assert(frRelPerm, qt.Equals, "/blog/sect/doc1/")
// should have redirect back to root // should have redirect back to root
b.AssertFileContent("public/fr/index.html", `<meta http-equiv="refresh" content="0; url=http://example.com/blog" />`) b.AssertFileContent("public/fr/index.html", `<meta http-equiv="refresh" content="0; url=http://example.com/blog" />`)
@ -154,7 +153,7 @@ func doTestMultiSitesMainLangInRoot(t *testing.T, defaultInSubDir bool) {
func TestMultiSitesWithTwoLanguages(t *testing.T) { func TestMultiSitesWithTwoLanguages(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
b := newTestSitesBuilder(t).WithConfigFile("toml", ` b := newTestSitesBuilder(t).WithConfigFile("toml", `
defaultContentLanguage = "nn" defaultContentLanguage = "nn"
@ -179,23 +178,23 @@ p1 = "p1en"
b.Build(BuildCfg{SkipRender: true}) b.Build(BuildCfg{SkipRender: true})
sites := b.H.Sites sites := b.H.Sites
assert.Len(sites, 2) c.Assert(len(sites), qt.Equals, 2)
nnSite := sites[0] nnSite := sites[0]
nnHome := nnSite.getPage(page.KindHome) nnHome := nnSite.getPage(page.KindHome)
assert.Len(nnHome.AllTranslations(), 2) c.Assert(len(nnHome.AllTranslations()), qt.Equals, 2)
assert.Len(nnHome.Translations(), 1) c.Assert(len(nnHome.Translations()), qt.Equals, 1)
assert.True(nnHome.IsTranslated()) c.Assert(nnHome.IsTranslated(), qt.Equals, true)
enHome := sites[1].getPage(page.KindHome) enHome := sites[1].getPage(page.KindHome)
p1, err := enHome.Param("p1") p1, err := enHome.Param("p1")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("p1en", p1) c.Assert(p1, qt.Equals, "p1en")
p1, err = nnHome.Param("p1") p1, err = nnHome.Param("p1")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("p1nn", p1) c.Assert(p1, qt.Equals, "p1nn")
} }
func TestMultiSitesBuild(t *testing.T) { func TestMultiSitesBuild(t *testing.T) {
@ -217,38 +216,38 @@ func TestMultiSitesBuild(t *testing.T) {
} }
func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) { func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) {
assert := require.New(t) c := qt.New(t)
b := newMultiSiteTestBuilder(t, configSuffix, configTemplate, nil) b := newMultiSiteTestBuilder(t, configSuffix, configTemplate, nil)
b.CreateSites() b.CreateSites()
sites := b.H.Sites sites := b.H.Sites
assert.Equal(4, len(sites)) c.Assert(len(sites), qt.Equals, 4)
b.Build(BuildCfg{}) b.Build(BuildCfg{})
// Check site config // Check site config
for _, s := range sites { for _, s := range sites {
require.True(t, s.Info.defaultContentLanguageInSubdir, s.Info.title) c.Assert(s.Info.defaultContentLanguageInSubdir, qt.Equals, true)
require.NotNil(t, s.disabledKinds) c.Assert(s.disabledKinds, qt.Not(qt.IsNil))
} }
gp1 := b.H.GetContentPage(filepath.FromSlash("content/sect/doc1.en.md")) gp1 := b.H.GetContentPage(filepath.FromSlash("content/sect/doc1.en.md"))
require.NotNil(t, gp1) c.Assert(gp1, qt.Not(qt.IsNil))
require.Equal(t, "doc1", gp1.Title()) c.Assert(gp1.Title(), qt.Equals, "doc1")
gp2 := b.H.GetContentPage(filepath.FromSlash("content/dummysect/notfound.md")) gp2 := b.H.GetContentPage(filepath.FromSlash("content/dummysect/notfound.md"))
require.Nil(t, gp2) c.Assert(gp2, qt.IsNil)
enSite := sites[0] enSite := sites[0]
enSiteHome := enSite.getPage(page.KindHome) enSiteHome := enSite.getPage(page.KindHome)
require.True(t, enSiteHome.IsTranslated()) c.Assert(enSiteHome.IsTranslated(), qt.Equals, true)
require.Equal(t, "en", enSite.language.Lang) c.Assert(enSite.language.Lang, qt.Equals, "en")
//dumpPages(enSite.RegularPages()...) //dumpPages(enSite.RegularPages()...)
assert.Equal(5, len(enSite.RegularPages())) c.Assert(len(enSite.RegularPages()), qt.Equals, 5)
assert.Equal(32, len(enSite.AllPages())) c.Assert(len(enSite.AllPages()), qt.Equals, 32)
// Check 404s // Check 404s
b.AssertFileContent("public/en/404.html", "404|en|404 Page not found") b.AssertFileContent("public/en/404.html", "404|en|404 Page not found")
@ -264,33 +263,33 @@ func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) {
doc2 := enSite.RegularPages()[1] doc2 := enSite.RegularPages()[1]
doc3 := enSite.RegularPages()[2] doc3 := enSite.RegularPages()[2]
require.Equal(t, doc2.Prev(), doc3, "doc3 should follow doc2, in .PrevPage") c.Assert(doc3, qt.Equals, doc2.Prev())
doc1en := enSite.RegularPages()[0] doc1en := enSite.RegularPages()[0]
doc1fr := doc1en.Translations()[0] doc1fr := doc1en.Translations()[0]
b.AssertFileContent("public/fr/sect/doc1/index.html", "Permalink: http://example.com/blog/fr/sect/doc1/") b.AssertFileContent("public/fr/sect/doc1/index.html", "Permalink: http://example.com/blog/fr/sect/doc1/")
require.Equal(t, doc1en.Translations()[0], doc1fr, "doc1-en should have doc1-fr as translation") c.Assert(doc1fr, qt.Equals, doc1en.Translations()[0])
require.Equal(t, doc1fr.Translations()[0], doc1en, "doc1-fr should have doc1-en as translation") c.Assert(doc1en, qt.Equals, doc1fr.Translations()[0])
require.Equal(t, "fr", doc1fr.Language().Lang) c.Assert(doc1fr.Language().Lang, qt.Equals, "fr")
doc4 := enSite.AllPages()[4] doc4 := enSite.AllPages()[4]
require.Len(t, doc4.Translations(), 0, "found translations for doc4") c.Assert(len(doc4.Translations()), qt.Equals, 0)
// Taxonomies and their URLs // Taxonomies and their URLs
require.Len(t, enSite.Taxonomies, 1, "should have 1 taxonomy") c.Assert(len(enSite.Taxonomies), qt.Equals, 1)
tags := enSite.Taxonomies["tags"] tags := enSite.Taxonomies["tags"]
require.Len(t, tags, 2, "should have 2 different tags") c.Assert(len(tags), qt.Equals, 2)
require.Equal(t, tags["tag1"][0].Page, doc1en, "first tag1 page should be doc1") c.Assert(doc1en, qt.Equals, tags["tag1"][0].Page)
frSite := sites[1] frSite := sites[1]
require.Equal(t, "fr", frSite.language.Lang) c.Assert(frSite.language.Lang, qt.Equals, "fr")
require.Len(t, frSite.RegularPages(), 4, "should have 3 pages") c.Assert(len(frSite.RegularPages()), qt.Equals, 4)
require.Len(t, frSite.AllPages(), 32, "should have 32 total pages (including translations and nodes)") c.Assert(len(frSite.AllPages()), qt.Equals, 32)
for _, frenchPage := range frSite.RegularPages() { for _, frenchPage := range frSite.RegularPages() {
p := frenchPage p := frenchPage
require.Equal(t, "fr", p.Language().Lang) c.Assert(p.Language().Lang, qt.Equals, "fr")
} }
// See https://github.com/gohugoio/hugo/issues/4285 // See https://github.com/gohugoio/hugo/issues/4285
@ -302,10 +301,10 @@ func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) {
getPageDoc1EnBase := enSite.getPage(page.KindPage, "sect/doc1") getPageDoc1EnBase := enSite.getPage(page.KindPage, "sect/doc1")
getPageDoc1Fr := frSite.getPage(page.KindPage, filepath.ToSlash(doc1fr.File().Path())) getPageDoc1Fr := frSite.getPage(page.KindPage, filepath.ToSlash(doc1fr.File().Path()))
getPageDoc1FrBase := frSite.getPage(page.KindPage, "sect/doc1") getPageDoc1FrBase := frSite.getPage(page.KindPage, "sect/doc1")
require.Equal(t, doc1en, getPageDoc1En) c.Assert(getPageDoc1En, qt.Equals, doc1en)
require.Equal(t, doc1fr, getPageDoc1Fr) c.Assert(getPageDoc1Fr, qt.Equals, doc1fr)
require.Equal(t, doc1en, getPageDoc1EnBase) c.Assert(getPageDoc1EnBase, qt.Equals, doc1en)
require.Equal(t, doc1fr, getPageDoc1FrBase) c.Assert(getPageDoc1FrBase, qt.Equals, doc1fr)
// Check redirect to main language, French // Check redirect to main language, French
b.AssertFileContent("public/index.html", "0; url=http://example.com/blog/fr") b.AssertFileContent("public/index.html", "0; url=http://example.com/blog/fr")
@ -320,35 +319,35 @@ func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) {
// Check node translations // Check node translations
homeEn := enSite.getPage(page.KindHome) homeEn := enSite.getPage(page.KindHome)
require.NotNil(t, homeEn) c.Assert(homeEn, qt.Not(qt.IsNil))
require.Len(t, homeEn.Translations(), 3) c.Assert(len(homeEn.Translations()), qt.Equals, 3)
require.Equal(t, "fr", homeEn.Translations()[0].Language().Lang) c.Assert(homeEn.Translations()[0].Language().Lang, qt.Equals, "fr")
require.Equal(t, "nn", homeEn.Translations()[1].Language().Lang) c.Assert(homeEn.Translations()[1].Language().Lang, qt.Equals, "nn")
require.Equal(t, "På nynorsk", homeEn.Translations()[1].Title()) c.Assert(homeEn.Translations()[1].Title(), qt.Equals, "På nynorsk")
require.Equal(t, "nb", homeEn.Translations()[2].Language().Lang) c.Assert(homeEn.Translations()[2].Language().Lang, qt.Equals, "nb")
require.Equal(t, "På bokmål", homeEn.Translations()[2].Title(), configSuffix) c.Assert(homeEn.Translations()[2].Title(), qt.Equals, "På bokmål")
require.Equal(t, "Bokmål", homeEn.Translations()[2].Language().LanguageName, configSuffix) c.Assert(homeEn.Translations()[2].Language().LanguageName, qt.Equals, "Bokmål")
sectFr := frSite.getPage(page.KindSection, "sect") sectFr := frSite.getPage(page.KindSection, "sect")
require.NotNil(t, sectFr) c.Assert(sectFr, qt.Not(qt.IsNil))
require.Equal(t, "fr", sectFr.Language().Lang) c.Assert(sectFr.Language().Lang, qt.Equals, "fr")
require.Len(t, sectFr.Translations(), 1) c.Assert(len(sectFr.Translations()), qt.Equals, 1)
require.Equal(t, "en", sectFr.Translations()[0].Language().Lang) c.Assert(sectFr.Translations()[0].Language().Lang, qt.Equals, "en")
require.Equal(t, "Sects", sectFr.Translations()[0].Title()) c.Assert(sectFr.Translations()[0].Title(), qt.Equals, "Sects")
nnSite := sites[2] nnSite := sites[2]
require.Equal(t, "nn", nnSite.language.Lang) c.Assert(nnSite.language.Lang, qt.Equals, "nn")
taxNn := nnSite.getPage(page.KindTaxonomyTerm, "lag") taxNn := nnSite.getPage(page.KindTaxonomyTerm, "lag")
require.NotNil(t, taxNn) c.Assert(taxNn, qt.Not(qt.IsNil))
require.Len(t, taxNn.Translations(), 1) c.Assert(len(taxNn.Translations()), qt.Equals, 1)
require.Equal(t, "nb", taxNn.Translations()[0].Language().Lang) c.Assert(taxNn.Translations()[0].Language().Lang, qt.Equals, "nb")
taxTermNn := nnSite.getPage(page.KindTaxonomy, "lag", "sogndal") taxTermNn := nnSite.getPage(page.KindTaxonomy, "lag", "sogndal")
require.NotNil(t, taxTermNn) c.Assert(taxTermNn, qt.Not(qt.IsNil))
require.Equal(t, taxTermNn, nnSite.getPage(page.KindTaxonomy, "LAG", "SOGNDAL")) c.Assert(nnSite.getPage(page.KindTaxonomy, "LAG", "SOGNDAL"), qt.Equals, taxTermNn)
require.Len(t, taxTermNn.Translations(), 1) c.Assert(len(taxTermNn.Translations()), qt.Equals, 1)
require.Equal(t, "nb", taxTermNn.Translations()[0].Language().Lang) c.Assert(taxTermNn.Translations()[0].Language().Lang, qt.Equals, "nb")
// Check sitemap(s) // Check sitemap(s)
b.AssertFileContent("public/sitemap.xml", b.AssertFileContent("public/sitemap.xml",
@ -360,54 +359,54 @@ func doTestMultiSitesBuild(t *testing.T, configTemplate, configSuffix string) {
// Check taxonomies // Check taxonomies
enTags := enSite.Taxonomies["tags"] enTags := enSite.Taxonomies["tags"]
frTags := frSite.Taxonomies["plaques"] frTags := frSite.Taxonomies["plaques"]
require.Len(t, enTags, 2, fmt.Sprintf("Tags in en: %v", enTags)) c.Assert(len(enTags), qt.Equals, 2, qt.Commentf("Tags in en: %v", enTags))
require.Len(t, frTags, 2, fmt.Sprintf("Tags in fr: %v", frTags)) c.Assert(len(frTags), qt.Equals, 2, qt.Commentf("Tags in fr: %v", frTags))
require.NotNil(t, enTags["tag1"]) c.Assert(enTags["tag1"], qt.Not(qt.IsNil))
require.NotNil(t, frTags["FRtag1"]) c.Assert(frTags["FRtag1"], qt.Not(qt.IsNil))
b.AssertFileContent("public/fr/plaques/FRtag1/index.html", "FRtag1|Bonjour|http://example.com/blog/fr/plaques/FRtag1/") b.AssertFileContent("public/fr/plaques/FRtag1/index.html", "FRtag1|Bonjour|http://example.com/blog/fr/plaques/FRtag1/")
// Check Blackfriday config // Check Blackfriday config
require.True(t, strings.Contains(content(doc1fr), "&laquo;"), content(doc1fr)) c.Assert(strings.Contains(content(doc1fr), "&laquo;"), qt.Equals, true)
require.False(t, strings.Contains(content(doc1en), "&laquo;"), content(doc1en)) c.Assert(strings.Contains(content(doc1en), "&laquo;"), qt.Equals, false)
require.True(t, strings.Contains(content(doc1en), "&ldquo;"), content(doc1en)) c.Assert(strings.Contains(content(doc1en), "&ldquo;"), qt.Equals, true)
// en and nn have custom site menus // en and nn have custom site menus
require.Len(t, frSite.Menus(), 0, "fr: "+configSuffix) c.Assert(len(frSite.Menus()), qt.Equals, 0)
require.Len(t, enSite.Menus(), 1, "en: "+configSuffix) c.Assert(len(enSite.Menus()), qt.Equals, 1)
require.Len(t, nnSite.Menus(), 1, "nn: "+configSuffix) c.Assert(len(nnSite.Menus()), qt.Equals, 1)
require.Equal(t, "Home", enSite.Menus()["main"].ByName()[0].Name) c.Assert(enSite.Menus()["main"].ByName()[0].Name, qt.Equals, "Home")
require.Equal(t, "Heim", nnSite.Menus()["main"].ByName()[0].Name) c.Assert(nnSite.Menus()["main"].ByName()[0].Name, qt.Equals, "Heim")
// Issue #3108 // Issue #3108
prevPage := enSite.RegularPages()[0].Prev() prevPage := enSite.RegularPages()[0].Prev()
require.NotNil(t, prevPage) c.Assert(prevPage, qt.Not(qt.IsNil))
require.Equal(t, page.KindPage, prevPage.Kind()) c.Assert(prevPage.Kind(), qt.Equals, page.KindPage)
for { for {
if prevPage == nil { if prevPage == nil {
break break
} }
require.Equal(t, page.KindPage, prevPage.Kind()) c.Assert(prevPage.Kind(), qt.Equals, page.KindPage)
prevPage = prevPage.Prev() prevPage = prevPage.Prev()
} }
// Check bundles // Check bundles
b.AssertFileContent("public/fr/bundles/b1/index.html", "RelPermalink: /blog/fr/bundles/b1/|") b.AssertFileContent("public/fr/bundles/b1/index.html", "RelPermalink: /blog/fr/bundles/b1/|")
bundleFr := frSite.getPage(page.KindPage, "bundles/b1/index.md") bundleFr := frSite.getPage(page.KindPage, "bundles/b1/index.md")
require.NotNil(t, bundleFr) c.Assert(bundleFr, qt.Not(qt.IsNil))
require.Equal(t, 1, len(bundleFr.Resources())) c.Assert(len(bundleFr.Resources()), qt.Equals, 1)
logoFr := bundleFr.Resources().GetMatch("logo*") logoFr := bundleFr.Resources().GetMatch("logo*")
require.NotNil(t, logoFr) c.Assert(logoFr, qt.Not(qt.IsNil))
b.AssertFileContent("public/fr/bundles/b1/index.html", "Resources: image/png: /blog/fr/bundles/b1/logo.png") b.AssertFileContent("public/fr/bundles/b1/index.html", "Resources: image/png: /blog/fr/bundles/b1/logo.png")
b.AssertFileContent("public/fr/bundles/b1/logo.png", "PNG Data") b.AssertFileContent("public/fr/bundles/b1/logo.png", "PNG Data")
bundleEn := enSite.getPage(page.KindPage, "bundles/b1/index.en.md") bundleEn := enSite.getPage(page.KindPage, "bundles/b1/index.en.md")
require.NotNil(t, bundleEn) c.Assert(bundleEn, qt.Not(qt.IsNil))
b.AssertFileContent("public/en/bundles/b1/index.html", "RelPermalink: /blog/en/bundles/b1/|") b.AssertFileContent("public/en/bundles/b1/index.html", "RelPermalink: /blog/en/bundles/b1/|")
require.Equal(t, 1, len(bundleEn.Resources())) c.Assert(len(bundleEn.Resources()), qt.Equals, 1)
logoEn := bundleEn.Resources().GetMatch("logo*") logoEn := bundleEn.Resources().GetMatch("logo*")
require.NotNil(t, logoEn) c.Assert(logoEn, qt.Not(qt.IsNil))
b.AssertFileContent("public/en/bundles/b1/index.html", "Resources: image/png: /blog/en/bundles/b1/logo.png") b.AssertFileContent("public/en/bundles/b1/index.html", "Resources: image/png: /blog/en/bundles/b1/logo.png")
b.AssertFileContent("public/en/bundles/b1/logo.png", "PNG Data") b.AssertFileContent("public/en/bundles/b1/logo.png", "PNG Data")
@ -420,7 +419,7 @@ func TestMultiSitesRebuild(t *testing.T) {
defer leaktest.CheckTimeout(t, 10*time.Second)() defer leaktest.CheckTimeout(t, 10*time.Second)()
} }
assert := require.New(t) c := qt.New(t)
b := newMultiSiteTestDefaultBuilder(t).Running().CreateSites().Build(BuildCfg{}) b := newMultiSiteTestDefaultBuilder(t).Running().CreateSites().Build(BuildCfg{})
@ -432,8 +431,8 @@ func TestMultiSitesRebuild(t *testing.T) {
enSite := sites[0] enSite := sites[0]
frSite := sites[1] frSite := sites[1]
assert.Len(enSite.RegularPages(), 5) c.Assert(len(enSite.RegularPages()), qt.Equals, 5)
assert.Len(frSite.RegularPages(), 4) c.Assert(len(frSite.RegularPages()), qt.Equals, 4)
// Verify translations // Verify translations
b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Hello") b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Hello")
@ -444,8 +443,8 @@ func TestMultiSitesRebuild(t *testing.T) {
b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Single", "Shortcode: Hello") b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Single", "Shortcode: Hello")
homeEn := enSite.getPage(page.KindHome) homeEn := enSite.getPage(page.KindHome)
require.NotNil(t, homeEn) c.Assert(homeEn, qt.Not(qt.IsNil))
assert.Len(homeEn.Translations(), 3) c.Assert(len(homeEn.Translations()), qt.Equals, 3)
contentFs := b.H.Fs.Source contentFs := b.H.Fs.Source
@ -467,7 +466,7 @@ func TestMultiSitesRebuild(t *testing.T) {
}, },
[]fsnotify.Event{{Name: filepath.FromSlash("content/sect/doc2.en.md"), Op: fsnotify.Remove}}, []fsnotify.Event{{Name: filepath.FromSlash("content/sect/doc2.en.md"), Op: fsnotify.Remove}},
func(t *testing.T) { func(t *testing.T) {
assert.Len(enSite.RegularPages(), 4, "1 en removed") c.Assert(len(enSite.RegularPages()), qt.Equals, 4, qt.Commentf("1 en removed"))
}, },
}, },
@ -483,15 +482,15 @@ func TestMultiSitesRebuild(t *testing.T) {
{Name: filepath.FromSlash("content/new1.fr.md"), Op: fsnotify.Create}, {Name: filepath.FromSlash("content/new1.fr.md"), Op: fsnotify.Create},
}, },
func(t *testing.T) { func(t *testing.T) {
assert.Len(enSite.RegularPages(), 6) c.Assert(len(enSite.RegularPages()), qt.Equals, 6)
assert.Len(enSite.AllPages(), 34) c.Assert(len(enSite.AllPages()), qt.Equals, 34)
assert.Len(frSite.RegularPages(), 5) c.Assert(len(frSite.RegularPages()), qt.Equals, 5)
require.Equal(t, "new_fr_1", frSite.RegularPages()[3].Title()) c.Assert(frSite.RegularPages()[3].Title(), qt.Equals, "new_fr_1")
require.Equal(t, "new_en_2", enSite.RegularPages()[0].Title()) c.Assert(enSite.RegularPages()[0].Title(), qt.Equals, "new_en_2")
require.Equal(t, "new_en_1", enSite.RegularPages()[1].Title()) c.Assert(enSite.RegularPages()[1].Title(), qt.Equals, "new_en_1")
rendered := readDestination(t, fs, "public/en/new1/index.html") rendered := readDestination(t, fs, "public/en/new1/index.html")
require.True(t, strings.Contains(rendered, "new_en_1"), rendered) c.Assert(strings.Contains(rendered, "new_en_1"), qt.Equals, true)
}, },
}, },
{ {
@ -503,9 +502,9 @@ func TestMultiSitesRebuild(t *testing.T) {
}, },
[]fsnotify.Event{{Name: filepath.FromSlash("content/sect/doc1.en.md"), Op: fsnotify.Write}}, []fsnotify.Event{{Name: filepath.FromSlash("content/sect/doc1.en.md"), Op: fsnotify.Write}},
func(t *testing.T) { func(t *testing.T) {
assert.Len(enSite.RegularPages(), 6) c.Assert(len(enSite.RegularPages()), qt.Equals, 6)
doc1 := readDestination(t, fs, "public/en/sect/doc1-slug/index.html") doc1 := readDestination(t, fs, "public/en/sect/doc1-slug/index.html")
require.True(t, strings.Contains(doc1, "CHANGED"), doc1) c.Assert(strings.Contains(doc1, "CHANGED"), qt.Equals, true)
}, },
}, },
@ -521,10 +520,10 @@ func TestMultiSitesRebuild(t *testing.T) {
{Name: filepath.FromSlash("content/new1.en.md"), Op: fsnotify.Rename}, {Name: filepath.FromSlash("content/new1.en.md"), Op: fsnotify.Rename},
}, },
func(t *testing.T) { func(t *testing.T) {
assert.Len(enSite.RegularPages(), 6, "Rename") c.Assert(len(enSite.RegularPages()), qt.Equals, 6, qt.Commentf("Rename"))
require.Equal(t, "new_en_1", enSite.RegularPages()[1].Title()) c.Assert(enSite.RegularPages()[1].Title(), qt.Equals, "new_en_1")
rendered := readDestination(t, fs, "public/en/new1renamed/index.html") rendered := readDestination(t, fs, "public/en/new1renamed/index.html")
require.True(t, strings.Contains(rendered, "new_en_1"), rendered) c.Assert(rendered, qt.Contains, "new_en_1")
}}, }},
{ {
// Change a template // Change a template
@ -536,11 +535,11 @@ func TestMultiSitesRebuild(t *testing.T) {
}, },
[]fsnotify.Event{{Name: filepath.FromSlash("layouts/_default/single.html"), Op: fsnotify.Write}}, []fsnotify.Event{{Name: filepath.FromSlash("layouts/_default/single.html"), Op: fsnotify.Write}},
func(t *testing.T) { func(t *testing.T) {
assert.Len(enSite.RegularPages(), 6) c.Assert(len(enSite.RegularPages()), qt.Equals, 6)
assert.Len(enSite.AllPages(), 34) c.Assert(len(enSite.AllPages()), qt.Equals, 34)
assert.Len(frSite.RegularPages(), 5) c.Assert(len(frSite.RegularPages()), qt.Equals, 5)
doc1 := readDestination(t, fs, "public/en/sect/doc1-slug/index.html") doc1 := readDestination(t, fs, "public/en/sect/doc1-slug/index.html")
require.True(t, strings.Contains(doc1, "Template Changed"), doc1) c.Assert(strings.Contains(doc1, "Template Changed"), qt.Equals, true)
}, },
}, },
{ {
@ -553,18 +552,18 @@ func TestMultiSitesRebuild(t *testing.T) {
}, },
[]fsnotify.Event{{Name: filepath.FromSlash("i18n/fr.yaml"), Op: fsnotify.Write}}, []fsnotify.Event{{Name: filepath.FromSlash("i18n/fr.yaml"), Op: fsnotify.Write}},
func(t *testing.T) { func(t *testing.T) {
assert.Len(enSite.RegularPages(), 6) c.Assert(len(enSite.RegularPages()), qt.Equals, 6)
assert.Len(enSite.AllPages(), 34) c.Assert(len(enSite.AllPages()), qt.Equals, 34)
assert.Len(frSite.RegularPages(), 5) c.Assert(len(frSite.RegularPages()), qt.Equals, 5)
docEn := readDestination(t, fs, "public/en/sect/doc1-slug/index.html") docEn := readDestination(t, fs, "public/en/sect/doc1-slug/index.html")
require.True(t, strings.Contains(docEn, "Hello"), "No Hello") c.Assert(strings.Contains(docEn, "Hello"), qt.Equals, true)
docFr := readDestination(t, fs, "public/fr/sect/doc1/index.html") docFr := readDestination(t, fs, "public/fr/sect/doc1/index.html")
require.True(t, strings.Contains(docFr, "Salut"), "No Salut") c.Assert(strings.Contains(docFr, "Salut"), qt.Equals, true)
homeEn := enSite.getPage(page.KindHome) homeEn := enSite.getPage(page.KindHome)
require.NotNil(t, homeEn) c.Assert(homeEn, qt.Not(qt.IsNil))
assert.Len(homeEn.Translations(), 3) c.Assert(len(homeEn.Translations()), qt.Equals, 3)
require.Equal(t, "fr", homeEn.Translations()[0].Language().Lang) c.Assert(homeEn.Translations()[0].Language().Lang, qt.Equals, "fr")
}, },
}, },
@ -577,9 +576,9 @@ func TestMultiSitesRebuild(t *testing.T) {
{Name: filepath.FromSlash("layouts/shortcodes/shortcode.html"), Op: fsnotify.Write}, {Name: filepath.FromSlash("layouts/shortcodes/shortcode.html"), Op: fsnotify.Write},
}, },
func(t *testing.T) { func(t *testing.T) {
assert.Len(enSite.RegularPages(), 6) c.Assert(len(enSite.RegularPages()), qt.Equals, 6)
assert.Len(enSite.AllPages(), 34) c.Assert(len(enSite.AllPages()), qt.Equals, 34)
assert.Len(frSite.RegularPages(), 5) c.Assert(len(frSite.RegularPages()), qt.Equals, 5)
b.AssertFileContent("public/fr/sect/doc1/index.html", "Single", "Modified Shortcode: Salut") b.AssertFileContent("public/fr/sect/doc1/index.html", "Single", "Modified Shortcode: Salut")
b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Single", "Modified Shortcode: Hello") b.AssertFileContent("public/en/sect/doc1-slug/index.html", "Single", "Modified Shortcode: Hello")
}, },
@ -781,24 +780,24 @@ categories: ["mycat"]
} { } {
t.Run(path, func(t *testing.T) { t.Run(path, func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
s1, _ := b.H.Sites[0].getPageNew(nil, path) s1, _ := b.H.Sites[0].getPageNew(nil, path)
s2, _ := b.H.Sites[1].getPageNew(nil, path) s2, _ := b.H.Sites[1].getPageNew(nil, path)
assert.NotNil(s1) c.Assert(s1, qt.Not(qt.IsNil))
assert.NotNil(s2) c.Assert(s2, qt.Not(qt.IsNil))
assert.Equal(1, len(s1.Translations())) c.Assert(len(s1.Translations()), qt.Equals, 1)
assert.Equal(1, len(s2.Translations())) c.Assert(len(s2.Translations()), qt.Equals, 1)
assert.Equal(s2, s1.Translations()[0]) c.Assert(s1.Translations()[0], qt.Equals, s2)
assert.Equal(s1, s2.Translations()[0]) c.Assert(s2.Translations()[0], qt.Equals, s1)
m1 := s1.Translations().MergeByLanguage(s2.Translations()) m1 := s1.Translations().MergeByLanguage(s2.Translations())
m2 := s2.Translations().MergeByLanguage(s1.Translations()) m2 := s2.Translations().MergeByLanguage(s1.Translations())
assert.Equal(1, len(m1)) c.Assert(len(m1), qt.Equals, 1)
assert.Equal(1, len(m2)) c.Assert(len(m2), qt.Equals, 1)
}) })
} }

View file

@ -5,13 +5,13 @@ import (
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestMultihosts(t *testing.T) { func TestMultihosts(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
var configTemplate = ` var configTemplate = `
paginate = 1 paginate = 1
@ -58,9 +58,9 @@ languageName = "Nynorsk"
s1 := b.H.Sites[0] s1 := b.H.Sites[0]
s1h := s1.getPage(page.KindHome) s1h := s1.getPage(page.KindHome)
assert.True(s1h.IsTranslated()) c.Assert(s1h.IsTranslated(), qt.Equals, true)
assert.Len(s1h.Translations(), 2) c.Assert(len(s1h.Translations()), qt.Equals, 2)
assert.Equal("https://example.com/docs/", s1h.Permalink()) c.Assert(s1h.Permalink(), qt.Equals, "https://example.com/docs/")
// For “regular multilingual” we kept the aliases pages with url in front matter // For “regular multilingual” we kept the aliases pages with url in front matter
// as a literal value that we use as is. // as a literal value that we use as is.
@ -69,8 +69,8 @@ languageName = "Nynorsk"
// //
// check url in front matter: // check url in front matter:
pageWithURLInFrontMatter := s1.getPage(page.KindPage, "sect/doc3.en.md") pageWithURLInFrontMatter := s1.getPage(page.KindPage, "sect/doc3.en.md")
assert.NotNil(pageWithURLInFrontMatter) c.Assert(pageWithURLInFrontMatter, qt.Not(qt.IsNil))
assert.Equal("/docs/superbob/", pageWithURLInFrontMatter.RelPermalink()) c.Assert(pageWithURLInFrontMatter.RelPermalink(), qt.Equals, "/docs/superbob/")
b.AssertFileContent("public/en/superbob/index.html", "doc3|Hello|en") b.AssertFileContent("public/en/superbob/index.html", "doc3|Hello|en")
// check alias: // check alias:
@ -80,7 +80,7 @@ languageName = "Nynorsk"
s2 := b.H.Sites[1] s2 := b.H.Sites[1]
s2h := s2.getPage(page.KindHome) s2h := s2.getPage(page.KindHome)
assert.Equal("https://example.fr/", s2h.Permalink()) c.Assert(s2h.Permalink(), qt.Equals, "https://example.fr/")
b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /docs/text/pipes.txt") b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /docs/text/pipes.txt")
b.AssertFileContent("public/fr/text/pipes.txt", "Hugo Pipes") b.AssertFileContent("public/fr/text/pipes.txt", "Hugo Pipes")
@ -96,17 +96,17 @@ languageName = "Nynorsk"
// Check bundles // Check bundles
bundleEn := s1.getPage(page.KindPage, "bundles/b1/index.en.md") bundleEn := s1.getPage(page.KindPage, "bundles/b1/index.en.md")
require.NotNil(t, bundleEn) c.Assert(bundleEn, qt.Not(qt.IsNil))
require.Equal(t, "/docs/bundles/b1/", bundleEn.RelPermalink()) c.Assert(bundleEn.RelPermalink(), qt.Equals, "/docs/bundles/b1/")
require.Equal(t, 1, len(bundleEn.Resources())) c.Assert(len(bundleEn.Resources()), qt.Equals, 1)
b.AssertFileContent("public/en/bundles/b1/logo.png", "PNG Data") b.AssertFileContent("public/en/bundles/b1/logo.png", "PNG Data")
b.AssertFileContent("public/en/bundles/b1/index.html", " image/png: /docs/bundles/b1/logo.png") b.AssertFileContent("public/en/bundles/b1/index.html", " image/png: /docs/bundles/b1/logo.png")
bundleFr := s2.getPage(page.KindPage, "bundles/b1/index.md") bundleFr := s2.getPage(page.KindPage, "bundles/b1/index.md")
require.NotNil(t, bundleFr) c.Assert(bundleFr, qt.Not(qt.IsNil))
require.Equal(t, "/bundles/b1/", bundleFr.RelPermalink()) c.Assert(bundleFr.RelPermalink(), qt.Equals, "/bundles/b1/")
require.Equal(t, 1, len(bundleFr.Resources())) c.Assert(len(bundleFr.Resources()), qt.Equals, 1)
b.AssertFileContent("public/fr/bundles/b1/logo.png", "PNG Data") b.AssertFileContent("public/fr/bundles/b1/logo.png", "PNG Data")
b.AssertFileContent("public/fr/bundles/b1/index.html", " image/png: /bundles/b1/logo.png") b.AssertFileContent("public/fr/bundles/b1/index.html", " image/png: /bundles/b1/logo.png")

View file

@ -18,13 +18,13 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestSmoke(t *testing.T) { func TestSmoke(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
const configFile = ` const configFile = `
baseURL = "https://example.com" baseURL = "https://example.com"
@ -203,8 +203,8 @@ Some **Markdown** in JSON shortcode.
// Check RSS // Check RSS
rssHome := b.FileContent("public/index.xml") rssHome := b.FileContent("public/index.xml")
assert.Contains(rssHome, `<atom:link href="https://example.com/index.xml" rel="self" type="application/rss+xml" />`) c.Assert(rssHome, qt.Contains, `<atom:link href="https://example.com/index.xml" rel="self" type="application/rss+xml" />`)
assert.Equal(3, strings.Count(rssHome, "<item>")) // rssLimit = 3 c.Assert(strings.Count(rssHome, "<item>"), qt.Equals, 3) // rssLimit = 3
// .Render should use template/content from the current output format // .Render should use template/content from the current output format
// even if that output format isn't configured for that page. // even if that output format isn't configured for that page.

View file

@ -21,18 +21,18 @@ import (
"github.com/gohugoio/hugo/htesting" "github.com/gohugoio/hugo/htesting"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
// We have many tests for the different resize operations etc. in the resource package, // We have many tests for the different resize operations etc. in the resource package,
// this is an integration test. // this is an integration test.
func TestImageResize(t *testing.T) { func TestImageResize(t *testing.T) {
assert := require.New(t) c := qt.New(t)
// Make this a real as possible. // Make this a real as possible.
workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "image-resize") workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "image-resize")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer clean() defer clean()
newBuilder := func() *sitesBuilder { newBuilder := func() *sitesBuilder {
@ -74,22 +74,22 @@ title: "My bundle"
imageDir := filepath.Join(workDir, "assets", "images") imageDir := filepath.Join(workDir, "assets", "images")
bundleDir := filepath.Join(workDir, "content", "mybundle") bundleDir := filepath.Join(workDir, "content", "mybundle")
assert.NoError(os.MkdirAll(imageDir, 0777)) c.Assert(os.MkdirAll(imageDir, 0777), qt.IsNil)
assert.NoError(os.MkdirAll(bundleDir, 0777)) c.Assert(os.MkdirAll(bundleDir, 0777), qt.IsNil)
src, err := os.Open("testdata/sunset.jpg") src, err := os.Open("testdata/sunset.jpg")
assert.NoError(err) c.Assert(err, qt.IsNil)
out, err := os.Create(filepath.Join(imageDir, "sunset.jpg")) out, err := os.Create(filepath.Join(imageDir, "sunset.jpg"))
assert.NoError(err) c.Assert(err, qt.IsNil)
_, err = io.Copy(out, src) _, err = io.Copy(out, src)
assert.NoError(err) c.Assert(err, qt.IsNil)
out.Close() out.Close()
src.Seek(0, 0) src.Seek(0, 0)
out, err = os.Create(filepath.Join(bundleDir, "sunset.jpg")) out, err = os.Create(filepath.Join(bundleDir, "sunset.jpg"))
assert.NoError(err) c.Assert(err, qt.IsNil)
_, err = io.Copy(out, src) _, err = io.Copy(out, src)
assert.NoError(err) c.Assert(err, qt.IsNil)
out.Close() out.Close()
src.Close() src.Close()

View file

@ -19,9 +19,11 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/spf13/cast"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
/* /*
@ -42,7 +44,7 @@ import (
func TestLanguageContentRoot(t *testing.T) { func TestLanguageContentRoot(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
config := ` config := `
baseURL = "https://example.org/" baseURL = "https://example.org/"
@ -215,9 +217,9 @@ Content.
//dumpPages(b.H.Sites[1].RegularPages()...) //dumpPages(b.H.Sites[1].RegularPages()...)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(3, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 3)
enSite := b.H.Sites[0] enSite := b.H.Sites[0]
nnSite := b.H.Sites[1] nnSite := b.H.Sites[1]
@ -228,25 +230,26 @@ Content.
//dumpPages(nnSite.RegularPages()...) //dumpPages(nnSite.RegularPages()...)
assert.Equal(12, len(nnSite.RegularPages())) c.Assert(len(nnSite.RegularPages()), qt.Equals, 12)
assert.Equal(13, len(enSite.RegularPages())) c.Assert(len(enSite.RegularPages()), qt.Equals, 13)
assert.Equal(10, len(svSite.RegularPages())) c.Assert(len(svSite.RegularPages()), qt.Equals, 10)
svP2, err := svSite.getPageNew(nil, "/sect/page2.md") svP2, err := svSite.getPageNew(nil, "/sect/page2.md")
assert.NoError(err) c.Assert(err, qt.IsNil)
nnP2, err := nnSite.getPageNew(nil, "/sect/page2.md") nnP2, err := nnSite.getPageNew(nil, "/sect/page2.md")
assert.NoError(err) c.Assert(err, qt.IsNil)
enP2, err := enSite.getPageNew(nil, "/sect/page2.md") enP2, err := enSite.getPageNew(nil, "/sect/page2.md")
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("en", enP2.Language().Lang) c.Assert(enP2.Language().Lang, qt.Equals, "en")
assert.Equal("sv", svP2.Language().Lang) c.Assert(svP2.Language().Lang, qt.Equals, "sv")
assert.Equal("nn", nnP2.Language().Lang) c.Assert(nnP2.Language().Lang, qt.Equals, "nn")
content, _ := nnP2.Content() content, _ := nnP2.Content()
assert.Contains(content, "SVP3-REF: https://example.org/sv/sect/p-sv-3/") contentStr := cast.ToString(content)
assert.Contains(content, "SVP3-RELREF: /sv/sect/p-sv-3/") c.Assert(contentStr, qt.Contains, "SVP3-REF: https://example.org/sv/sect/p-sv-3/")
c.Assert(contentStr, qt.Contains, "SVP3-RELREF: /sv/sect/p-sv-3/")
// Test RelRef with and without language indicator. // Test RelRef with and without language indicator.
nn3RefArgs := map[string]interface{}{ nn3RefArgs := map[string]interface{}{
@ -256,38 +259,34 @@ Content.
nnP3RelRef, err := svP2.RelRef( nnP3RelRef, err := svP2.RelRef(
nn3RefArgs, nn3RefArgs,
) )
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("/nn/sect/p-nn-3/", nnP3RelRef) c.Assert(nnP3RelRef, qt.Equals, "/nn/sect/p-nn-3/")
nnP3Ref, err := svP2.Ref( nnP3Ref, err := svP2.Ref(
nn3RefArgs, nn3RefArgs,
) )
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal("https://example.org/nn/sect/p-nn-3/", nnP3Ref) c.Assert(nnP3Ref, qt.Equals, "https://example.org/nn/sect/p-nn-3/")
for i, p := range enSite.RegularPages() { for i, p := range enSite.RegularPages() {
j := i + 1 j := i + 1
msg := fmt.Sprintf("Test %d", j) c.Assert(p.Language().Lang, qt.Equals, "en")
assert.Equal("en", p.Language().Lang, msg) c.Assert(p.Section(), qt.Equals, "sect")
assert.Equal("sect", p.Section())
if j < 9 { if j < 9 {
if j%4 == 0 { if j%4 == 0 {
assert.Contains(p.Title(), fmt.Sprintf("p-sv-%d.en", i+1), msg)
} else { } else {
assert.Contains(p.Title(), "p-en", msg) c.Assert(p.Title(), qt.Contains, "p-en")
} }
} }
} }
for i, p := range nnSite.RegularPages() { for _, p := range nnSite.RegularPages() {
msg := fmt.Sprintf("Test %d", i+1) c.Assert(p.Language().Lang, qt.Equals, "nn")
assert.Equal("nn", p.Language().Lang, msg) c.Assert(p.Title(), qt.Contains, "nn")
assert.Contains(p.Title(), "nn", msg)
} }
for i, p := range svSite.RegularPages() { for _, p := range svSite.RegularPages() {
msg := fmt.Sprintf("Test %d", i+1) c.Assert(p.Language().Lang, qt.Equals, "sv")
assert.Equal("sv", p.Language().Lang, msg) c.Assert(p.Title(), qt.Contains, "sv")
assert.Contains(p.Title(), "sv", msg)
} }
// Check bundles // Check bundles
@ -295,12 +294,12 @@ Content.
bundleNn := nnSite.RegularPages()[len(nnSite.RegularPages())-1] bundleNn := nnSite.RegularPages()[len(nnSite.RegularPages())-1]
bundleSv := svSite.RegularPages()[len(svSite.RegularPages())-1] bundleSv := svSite.RegularPages()[len(svSite.RegularPages())-1]
assert.Equal("/en/sect/mybundle/", bundleEn.RelPermalink()) c.Assert(bundleEn.RelPermalink(), qt.Equals, "/en/sect/mybundle/")
assert.Equal("/sv/sect/mybundle/", bundleSv.RelPermalink()) c.Assert(bundleSv.RelPermalink(), qt.Equals, "/sv/sect/mybundle/")
assert.Equal(4, len(bundleNn.Resources())) c.Assert(len(bundleNn.Resources()), qt.Equals, 4)
assert.Equal(4, len(bundleSv.Resources())) c.Assert(len(bundleSv.Resources()), qt.Equals, 4)
assert.Equal(4, len(bundleEn.Resources())) c.Assert(len(bundleEn.Resources()), qt.Equals, 4)
b.AssertFileContent("/my/project/public/en/sect/mybundle/index.html", "image/png: /en/sect/mybundle/logo.png") b.AssertFileContent("/my/project/public/en/sect/mybundle/index.html", "image/png: /en/sect/mybundle/logo.png")
b.AssertFileContent("/my/project/public/nn/sect/mybundle/index.html", "image/png: /nn/sect/mybundle/logo.png") b.AssertFileContent("/my/project/public/nn/sect/mybundle/index.html", "image/png: /nn/sect/mybundle/logo.png")
@ -314,9 +313,9 @@ Content.
b.AssertFileContent("/my/project/public/nn/sect/mybundle/logo.png", "PNG Data") b.AssertFileContent("/my/project/public/nn/sect/mybundle/logo.png", "PNG Data")
nnSect := nnSite.getPage(page.KindSection, "sect") nnSect := nnSite.getPage(page.KindSection, "sect")
assert.NotNil(nnSect) c.Assert(nnSect, qt.Not(qt.IsNil))
assert.Equal(12, len(nnSect.Pages())) c.Assert(len(nnSect.Pages()), qt.Equals, 12)
nnHome, _ := nnSite.Info.Home() nnHome, _ := nnSite.Info.Home()
assert.Equal("/nn/", nnHome.RelPermalink()) c.Assert(nnHome.RelPermalink(), qt.Equals, "/nn/")
} }

View file

@ -18,7 +18,7 @@ import (
"fmt" "fmt"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
const ( const (
@ -77,12 +77,12 @@ Menu Main: {{ partial "menu.html" (dict "page" . "menu" "main") }}`,
s := h.Sites[0] s := h.Sites[0]
require.Len(t, s.Menus(), 2) b.Assert(len(s.Menus()), qt.Equals, 2)
p1 := s.RegularPages()[0].Menus() p1 := s.RegularPages()[0].Menus()
// There is only one menu in the page, but it is "member of" 2 // There is only one menu in the page, but it is "member of" 2
require.Len(t, p1, 1) b.Assert(len(p1), qt.Equals, 1)
b.AssertFileContent("public/sect1/p1/index.html", "Single", b.AssertFileContent("public/sect1/p1/index.html", "Single",
"Menu Sect: "+ "Menu Sect: "+

View file

@ -19,7 +19,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
) )
@ -66,6 +66,7 @@ func TestPermalink(t *testing.T) {
test := test test := test
t.Run(fmt.Sprintf("%s-%d", test.file, i), func(t *testing.T) { t.Run(fmt.Sprintf("%s-%d", test.file, i), func(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
cfg.Set("uglyURLs", test.uglyURLs) cfg.Set("uglyURLs", test.uglyURLs)
@ -84,7 +85,7 @@ Content
writeSource(t, fs, filepath.Join("content", filepath.FromSlash(test.file)), pageContent) writeSource(t, fs, filepath.Join("content", filepath.FromSlash(test.file)), pageContent)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0] p := s.RegularPages()[0]

View file

@ -34,10 +34,9 @@ import (
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/spf13/viper" "github.com/spf13/viper"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -306,7 +305,6 @@ func checkPageContent(t *testing.T, page page.Page, expected string, msg ...inte
a := normalizeContent(expected) a := normalizeContent(expected)
b := normalizeContent(content(page)) b := normalizeContent(content(page))
if a != b { if a != b {
t.Log(stackTrace())
t.Fatalf("Page content is:\n%q\nExpected:\n%q (%q)", b, a, msg) t.Fatalf("Page content is:\n%q\nExpected:\n%q (%q)", b, a, msg)
} }
} }
@ -422,15 +420,15 @@ func testAllMarkdownEnginesForPages(t *testing.T,
s := b.H.Sites[0] s := b.H.Sites[0]
require.Len(t, s.RegularPages(), len(pageSources)) b.Assert(len(s.RegularPages()), qt.Equals, len(pageSources))
assertFunc(t, e.ext, s.RegularPages()) assertFunc(t, e.ext, s.RegularPages())
home, err := s.Info.Home() home, err := s.Info.Home()
require.NoError(t, err) b.Assert(err, qt.IsNil)
require.NotNil(t, home) b.Assert(home, qt.Not(qt.IsNil))
require.Equal(t, homePath, home.File().Path()) b.Assert(home.File().Path(), qt.Equals, homePath)
require.Contains(t, content(home), "Home Page Content") b.Assert(content(home), qt.Contains, "Home Page Content")
} }
@ -440,12 +438,13 @@ func testAllMarkdownEnginesForPages(t *testing.T,
func TestPageWithDelimiterForMarkdownThatCrossesBorder(t *testing.T) { func TestPageWithDelimiterForMarkdownThatCrossesBorder(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder) writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageWithSummaryDelimiterAndMarkdownThatCrossesBorder)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0] p := s.RegularPages()[0]
@ -454,15 +453,14 @@ func TestPageWithDelimiterForMarkdownThatCrossesBorder(t *testing.T) {
t.Fatalf("Got summary:\n%q", p.Summary()) t.Fatalf("Got summary:\n%q", p.Summary())
} }
c := content(p) cnt := content(p)
if c != "<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup class=\"footnote-ref\" id=\"fnref:1\"><a href=\"#fn:1\">1</a></sup></p>\n\n<div class=\"footnotes\">\n\n<hr />\n\n<ol>\n<li id=\"fn:1\">Many people say so.\n <a class=\"footnote-return\" href=\"#fnref:1\"><sup>[return]</sup></a></li>\n</ol>\n</div>" { if cnt != "<p>The <a href=\"http://gohugo.io/\">best static site generator</a>.<sup class=\"footnote-ref\" id=\"fnref:1\"><a href=\"#fn:1\">1</a></sup></p>\n\n<div class=\"footnotes\">\n\n<hr />\n\n<ol>\n<li id=\"fn:1\">Many people say so.\n <a class=\"footnote-return\" href=\"#fnref:1\"><sup>[return]</sup></a></li>\n</ol>\n</div>" {
t.Fatalf("Got content:\n%q", c) t.Fatalf("Got content:\n%q", cnt)
} }
} }
func TestPageDatesAllKinds(t *testing.T) { func TestPageDatesAllKinds(t *testing.T) {
t.Parallel() t.Parallel()
assert := assert.New(t)
pageContent := ` pageContent := `
--- ---
@ -479,11 +477,11 @@ categories: ["cool stuff"]
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) b.Assert(len(b.H.Sites), qt.Equals, 1)
s := b.H.Sites[0] s := b.H.Sites[0]
checkDate := func(t time.Time, msg string) { checkDate := func(t time.Time, msg string) {
assert.Equal(2017, t.Year(), msg) b.Assert(t.Year(), qt.Equals, 2017)
} }
checkDated := func(d resource.Dated, msg string) { checkDated := func(d resource.Dated, msg string) {
@ -499,7 +497,6 @@ categories: ["cool stuff"]
func TestPageDatesSections(t *testing.T) { func TestPageDatesSections(t *testing.T) {
t.Parallel() t.Parallel()
assert := assert.New(t)
b := newTestSitesBuilder(t) b := newTestSitesBuilder(t)
b.WithSimpleConfigFile().WithContent("no-index/page.md", ` b.WithSimpleConfigFile().WithContent("no-index/page.md", `
@ -524,23 +521,24 @@ date: 2018-01-15
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) b.Assert(len(b.H.Sites), qt.Equals, 1)
s := b.H.Sites[0] s := b.H.Sites[0]
assert.Equal(2017, s.getPage("/").Date().Year()) b.Assert(s.getPage("/").Date().Year(), qt.Equals, 2017)
assert.Equal(2017, s.getPage("/no-index").Date().Year()) b.Assert(s.getPage("/no-index").Date().Year(), qt.Equals, 2017)
assert.True(s.getPage("/with-index-no-date").Date().IsZero()) b.Assert(s.getPage("/with-index-no-date").Date().IsZero(), qt.Equals, true)
assert.Equal(2018, s.getPage("/with-index-date").Date().Year()) b.Assert(s.getPage("/with-index-date").Date().Year(), qt.Equals, 2018)
} }
func TestCreateNewPage(t *testing.T) { func TestCreateNewPage(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
assertFunc := func(t *testing.T, ext string, pages page.Pages) { assertFunc := func(t *testing.T, ext string, pages page.Pages) {
p := pages[0] p := pages[0]
// issue #2290: Path is relative to the content dir and will continue to be so. // issue #2290: Path is relative to the content dir and will continue to be so.
require.Equal(t, filepath.FromSlash(fmt.Sprintf("p0.%s", ext)), p.File().Path()) c.Assert(p.File().Path(), qt.Equals, fmt.Sprintf("p0.%s", ext))
assert.False(t, p.IsHome()) c.Assert(p.IsHome(), qt.Equals, false)
checkPageTitle(t, p, "Simple") checkPageTitle(t, p, "Simple")
checkPageContent(t, p, normalizeExpected(ext, "<p>Simple Page</p>\n")) checkPageContent(t, p, normalizeExpected(ext, "<p>Simple Page</p>\n"))
checkPageSummary(t, p, "Simple Page") checkPageSummary(t, p, "Simple Page")
@ -602,7 +600,7 @@ func TestPageWithSummaryParameter(t *testing.T) {
// Issue #3854 // Issue #3854
// Also see https://github.com/gohugoio/hugo/issues/3977 // Also see https://github.com/gohugoio/hugo/issues/3977
func TestPageWithDateFields(t *testing.T) { func TestPageWithDateFields(t *testing.T) {
assert := require.New(t) c := qt.New(t)
pageWithDate := `--- pageWithDate := `---
title: P%d title: P%d
weight: %d weight: %d
@ -620,9 +618,9 @@ Simple Page With Some Date`
t.Parallel() t.Parallel()
assertFunc := func(t *testing.T, ext string, pages page.Pages) { assertFunc := func(t *testing.T, ext string, pages page.Pages) {
assert.True(len(pages) > 0) c.Assert(len(pages) > 0, qt.Equals, true)
for _, p := range pages { for _, p := range pages {
assert.True(hasDate(p)) c.Assert(hasDate(p), qt.Equals, true)
} }
} }
@ -640,6 +638,7 @@ Simple Page With Some Date`
func TestPageRawContent(t *testing.T) { func TestPageRawContent(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "raw.md"), `--- writeSource(t, fs, filepath.Join("content", "raw.md"), `---
title: Raw title: Raw
@ -650,10 +649,10 @@ title: Raw
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0] p := s.RegularPages()[0]
require.Equal(t, p.RawContent(), "**Raw**") c.Assert("**Raw**", qt.Equals, p.RawContent())
} }
@ -687,12 +686,13 @@ func TestPageWithEmbeddedScriptTag(t *testing.T) {
func TestPageWithAdditionalExtension(t *testing.T) { func TestPageWithAdditionalExtension(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageWithAdditionalExtension) writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageWithAdditionalExtension)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0] p := s.RegularPages()[0]
@ -702,12 +702,13 @@ func TestPageWithAdditionalExtension(t *testing.T) {
func TestTableOfContents(t *testing.T) { func TestTableOfContents(t *testing.T) {
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "tocpage.md"), pageWithToC) writeSource(t, fs, filepath.Join("content", "tocpage.md"), pageWithToC)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0] p := s.RegularPages()[0]
@ -733,9 +734,11 @@ func TestPageWithMoreTag(t *testing.T) {
func TestSummaryWithHTMLTagsOnNextLine(t *testing.T) { func TestSummaryWithHTMLTagsOnNextLine(t *testing.T) {
assertFunc := func(t *testing.T, ext string, pages page.Pages) { assertFunc := func(t *testing.T, ext string, pages page.Pages) {
c := qt.New(t)
p := pages[0] p := pages[0]
require.Contains(t, p.Summary(), "Happy new year everyone!") s := string(p.Summary())
require.NotContains(t, p.Summary(), "User interface") c.Assert(s, qt.Contains, "Happy new year everyone!")
c.Assert(s, qt.Not(qt.Contains), "User interface")
} }
testAllMarkdownEnginesForPages(t, assertFunc, nil, `--- testAllMarkdownEnginesForPages(t, assertFunc, nil, `---
@ -755,12 +758,13 @@ Here is the last report for commits in the year 2016. It covers hrev50718-hrev50
func TestPageWithDate(t *testing.T) { func TestPageWithDate(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageRFC3339Date) writeSource(t, fs, filepath.Join("content", "simple.md"), simplePageRFC3339Date)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0] p := s.RegularPages()[0]
d, _ := time.Parse(time.RFC3339, "2013-05-17T16:59:30Z") d, _ := time.Parse(time.RFC3339, "2013-05-17T16:59:30Z")
@ -769,7 +773,7 @@ func TestPageWithDate(t *testing.T) {
} }
func TestPageWithLastmodFromGitInfo(t *testing.T) { func TestPageWithLastmodFromGitInfo(t *testing.T) {
assrt := require.New(t) c := qt.New(t)
// We need to use the OS fs for this. // We need to use the OS fs for this.
cfg := viper.New() cfg := viper.New()
@ -777,7 +781,7 @@ func TestPageWithLastmodFromGitInfo(t *testing.T) {
fs.Destination = &afero.MemMapFs{} fs.Destination = &afero.MemMapFs{}
wd, err := os.Getwd() wd, err := os.Getwd()
assrt.NoError(err) c.Assert(err, qt.IsNil)
cfg.Set("frontmatter", map[string]interface{}{ cfg.Set("frontmatter", map[string]interface{}{
"lastmod": []string{":git", "lastmod"}, "lastmod": []string{":git", "lastmod"},
@ -807,19 +811,19 @@ func TestPageWithLastmodFromGitInfo(t *testing.T) {
b.Build(BuildCfg{SkipRender: true}) b.Build(BuildCfg{SkipRender: true})
h := b.H h := b.H
assrt.Len(h.Sites, 2) c.Assert(len(h.Sites), qt.Equals, 2)
enSite := h.Sites[0] enSite := h.Sites[0]
assrt.Len(enSite.RegularPages(), 1) c.Assert(len(enSite.RegularPages()), qt.Equals, 1)
// 2018-03-11 is the Git author date for testsite/content/first-post.md // 2018-03-11 is the Git author date for testsite/content/first-post.md
assrt.Equal("2018-03-11", enSite.RegularPages()[0].Lastmod().Format("2006-01-02")) c.Assert(enSite.RegularPages()[0].Lastmod().Format("2006-01-02"), qt.Equals, "2018-03-11")
nnSite := h.Sites[1] nnSite := h.Sites[1]
assrt.Len(nnSite.RegularPages(), 1) c.Assert(len(nnSite.RegularPages()), qt.Equals, 1)
// 2018-08-11 is the Git author date for testsite/content_nn/first-post.md // 2018-08-11 is the Git author date for testsite/content_nn/first-post.md
assrt.Equal("2018-08-11", nnSite.RegularPages()[0].Lastmod().Format("2006-01-02")) c.Assert(nnSite.RegularPages()[0].Lastmod().Format("2006-01-02"), qt.Equals, "2018-08-11")
} }
@ -828,7 +832,7 @@ func TestPageWithFrontMatterConfig(t *testing.T) {
dateHandler := dateHandler dateHandler := dateHandler
t.Run(fmt.Sprintf("dateHandler=%q", dateHandler), func(t *testing.T) { t.Run(fmt.Sprintf("dateHandler=%q", dateHandler), func(t *testing.T) {
t.Parallel() t.Parallel()
assrt := require.New(t) c := qt.New(t)
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
pageTemplate := ` pageTemplate := `
@ -852,36 +856,36 @@ Content
writeSource(t, fs, c2, fmt.Sprintf(pageTemplate, 2, "slug: aslug")) writeSource(t, fs, c2, fmt.Sprintf(pageTemplate, 2, "slug: aslug"))
c1fi, err := fs.Source.Stat(c1) c1fi, err := fs.Source.Stat(c1)
assrt.NoError(err) c.Assert(err, qt.IsNil)
c2fi, err := fs.Source.Stat(c2) c2fi, err := fs.Source.Stat(c2)
assrt.NoError(err) c.Assert(err, qt.IsNil)
b := newTestSitesBuilderFromDepsCfg(t, deps.DepsCfg{Fs: fs, Cfg: cfg}).WithNothingAdded() b := newTestSitesBuilderFromDepsCfg(t, deps.DepsCfg{Fs: fs, Cfg: cfg}).WithNothingAdded()
b.Build(BuildCfg{SkipRender: true}) b.Build(BuildCfg{SkipRender: true})
s := b.H.Sites[0] s := b.H.Sites[0]
assrt.Len(s.RegularPages(), 2) c.Assert(len(s.RegularPages()), qt.Equals, 2)
noSlug := s.RegularPages()[0] noSlug := s.RegularPages()[0]
slug := s.RegularPages()[1] slug := s.RegularPages()[1]
assrt.Equal(28, noSlug.Lastmod().Day()) c.Assert(noSlug.Lastmod().Day(), qt.Equals, 28)
switch strings.ToLower(dateHandler) { switch strings.ToLower(dateHandler) {
case ":filename": case ":filename":
assrt.False(noSlug.Date().IsZero()) c.Assert(noSlug.Date().IsZero(), qt.Equals, false)
assrt.False(slug.Date().IsZero()) c.Assert(slug.Date().IsZero(), qt.Equals, false)
assrt.Equal(2012, noSlug.Date().Year()) c.Assert(noSlug.Date().Year(), qt.Equals, 2012)
assrt.Equal(2012, slug.Date().Year()) c.Assert(slug.Date().Year(), qt.Equals, 2012)
assrt.Equal("noslug", noSlug.Slug()) c.Assert(noSlug.Slug(), qt.Equals, "noslug")
assrt.Equal("aslug", slug.Slug()) c.Assert(slug.Slug(), qt.Equals, "aslug")
case ":filemodtime": case ":filemodtime":
assrt.Equal(c1fi.ModTime().Year(), noSlug.Date().Year()) c.Assert(noSlug.Date().Year(), qt.Equals, c1fi.ModTime().Year())
assrt.Equal(c2fi.ModTime().Year(), slug.Date().Year()) c.Assert(slug.Date().Year(), qt.Equals, c2fi.ModTime().Year())
fallthrough fallthrough
default: default:
assrt.Equal("", noSlug.Slug()) c.Assert(noSlug.Slug(), qt.Equals, "")
assrt.Equal("aslug", slug.Slug()) c.Assert(slug.Slug(), qt.Equals, "aslug")
} }
}) })
@ -978,6 +982,7 @@ func TestWordCount(t *testing.T) {
func TestPagePaths(t *testing.T) { func TestPagePaths(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
siteParmalinksSetting := map[string]string{ siteParmalinksSetting := map[string]string{
"post": ":year/:month/:day/:title/", "post": ":year/:month/:day/:title/",
@ -1009,14 +1014,14 @@ func TestPagePaths(t *testing.T) {
writeSource(t, fs, filepath.Join("content", filepath.FromSlash(test.path)), test.content) writeSource(t, fs, filepath.Join("content", filepath.FromSlash(test.path)), test.content)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
} }
} }
func TestTranslationKey(t *testing.T) { func TestTranslationKey(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
writeSource(t, fs, filepath.Join("content", filepath.FromSlash("sect/simple.no.md")), "---\ntitle: \"A1\"\ntranslationKey: \"k1\"\n---\nContent\n") writeSource(t, fs, filepath.Join("content", filepath.FromSlash("sect/simple.no.md")), "---\ntitle: \"A1\"\ntranslationKey: \"k1\"\n---\nContent\n")
@ -1024,20 +1029,21 @@ func TestTranslationKey(t *testing.T) {
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 2) c.Assert(len(s.RegularPages()), qt.Equals, 2)
home, _ := s.Info.Home() home, _ := s.Info.Home()
assert.NotNil(home) c.Assert(home, qt.Not(qt.IsNil))
assert.Equal("home", home.TranslationKey()) c.Assert(home.TranslationKey(), qt.Equals, "home")
assert.Equal("page/k1", s.RegularPages()[0].TranslationKey()) c.Assert(s.RegularPages()[0].TranslationKey(), qt.Equals, "page/k1")
p2 := s.RegularPages()[1] p2 := s.RegularPages()[1]
assert.Equal("page/sect/simple", p2.TranslationKey()) c.Assert(p2.TranslationKey(), qt.Equals, "page/sect/simple")
} }
func TestChompBOM(t *testing.T) { func TestChompBOM(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
const utf8BOM = "\xef\xbb\xbf" const utf8BOM = "\xef\xbb\xbf"
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
@ -1046,7 +1052,7 @@ func TestChompBOM(t *testing.T) {
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
p := s.RegularPages()[0] p := s.RegularPages()[0]
@ -1340,7 +1346,8 @@ func TestPathIssues(t *testing.T) {
t.Run(fmt.Sprintf("disablePathToLower=%t,uglyURLs=%t", disablePathToLower, uglyURLs), func(t *testing.T) { t.Run(fmt.Sprintf("disablePathToLower=%t,uglyURLs=%t", disablePathToLower, uglyURLs), func(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
th := testHelper{cfg, fs, t} th := newTestHelper(cfg, fs, t)
c := qt.New(t)
cfg.Set("permalinks", map[string]string{ cfg.Set("permalinks", map[string]string{
"post": ":section/:title", "post": ":section/:title",
@ -1376,7 +1383,7 @@ tags:
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
require.Len(t, s.RegularPages(), 4) c.Assert(len(s.RegularPages()), qt.Equals, 4)
pathFunc := func(s string) string { pathFunc := func(s string) string {
if uglyURLs { if uglyURLs {
@ -1409,9 +1416,9 @@ tags:
p := s.RegularPages()[0] p := s.RegularPages()[0]
if uglyURLs { if uglyURLs {
require.Equal(t, "/post/test0.dot.html", p.RelPermalink()) c.Assert(p.RelPermalink(), qt.Equals, "/post/test0.dot.html")
} else { } else {
require.Equal(t, "/post/test0.dot/", p.RelPermalink()) c.Assert(p.RelPermalink(), qt.Equals, "/post/test0.dot/")
} }
}) })
@ -1423,7 +1430,7 @@ tags:
func TestWordCountAndSimilarVsSummary(t *testing.T) { func TestWordCountAndSimilarVsSummary(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
single := []string{"_default/single.html", ` single := []string{"_default/single.html", `
WordCount: {{ .WordCount }} WordCount: {{ .WordCount }}
@ -1502,8 +1509,8 @@ Summary: In Chinese, 好 means good.
b.CreateSites().Build(BuildCfg{}) b.CreateSites().Build(BuildCfg{})
assert.Equal(1, len(b.H.Sites)) c.Assert(len(b.H.Sites), qt.Equals, 1)
require.Len(t, b.H.Sites[0].RegularPages(), 6) c.Assert(len(b.H.Sites[0].RegularPages()), qt.Equals, 6)
b.AssertFileContent("public/p1/index.html", "WordCount: 510\nFuzzyWordCount: 600\nReadingTime: 3\nLen Plain: 2550\nLen PlainWords: 510\nTruncated: false\nLen Summary: 2549\nLen Content: 2557") b.AssertFileContent("public/p1/index.html", "WordCount: 510\nFuzzyWordCount: 600\nReadingTime: 3\nLen Plain: 2550\nLen PlainWords: 510\nTruncated: false\nLen Summary: 2549\nLen Content: 2557")

View file

@ -16,16 +16,16 @@ package hugolib
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/stretchr/testify/require"
) )
func TestUnwrapPage(t *testing.T) { func TestUnwrapPage(t *testing.T) {
assert := require.New(t) c := qt.New(t)
p := &pageState{} p := &pageState{}
assert.Equal(p, mustUnwrap(newPageForShortcode(p))) c.Assert(mustUnwrap(newPageForShortcode(p)), qt.Equals, p)
} }
func mustUnwrap(v interface{}) page.Page { func mustUnwrap(v interface{}) page.Page {

View file

@ -38,7 +38,7 @@ import (
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestPageBundlerSiteRegular(t *testing.T) { func TestPageBundlerSiteRegular(t *testing.T) {
@ -63,7 +63,7 @@ func TestPageBundlerSiteRegular(t *testing.T) {
if canonify { if canonify {
relURLBase = "" relURLBase = ""
} }
assert := require.New(t) c := qt.New(t)
fs, cfg := newTestBundleSources(t) fs, cfg := newTestBundleSources(t)
cfg.Set("baseURL", baseURL) cfg.Set("baseURL", baseURL)
cfg.Set("canonifyURLs", canonify) cfg.Set("canonifyURLs", canonify)
@ -98,16 +98,16 @@ func TestPageBundlerSiteRegular(t *testing.T) {
s := b.H.Sites[0] s := b.H.Sites[0]
assert.Len(s.RegularPages(), 8) c.Assert(len(s.RegularPages()), qt.Equals, 8)
singlePage := s.getPage(page.KindPage, "a/1.md") singlePage := s.getPage(page.KindPage, "a/1.md")
assert.Equal("", singlePage.BundleType()) c.Assert(singlePage.BundleType(), qt.Equals, "")
assert.NotNil(singlePage) c.Assert(singlePage, qt.Not(qt.IsNil))
assert.Equal(singlePage, s.getPage("page", "a/1")) c.Assert(s.getPage("page", "a/1"), qt.Equals, singlePage)
assert.Equal(singlePage, s.getPage("page", "1")) c.Assert(s.getPage("page", "1"), qt.Equals, singlePage)
assert.Contains(content(singlePage), "TheContent") c.Assert(content(singlePage), qt.Contains, "TheContent")
relFilename := func(basePath, outBase string) (string, string) { relFilename := func(basePath, outBase string) (string, string) {
rel := basePath rel := basePath
@ -147,53 +147,53 @@ func TestPageBundlerSiteRegular(t *testing.T) {
b.AssertFileContent(filepath.FromSlash("/work/public/assets/pic1.png"), "content") b.AssertFileContent(filepath.FromSlash("/work/public/assets/pic1.png"), "content")
leafBundle1 := s.getPage(page.KindPage, "b/my-bundle/index.md") leafBundle1 := s.getPage(page.KindPage, "b/my-bundle/index.md")
assert.NotNil(leafBundle1) c.Assert(leafBundle1, qt.Not(qt.IsNil))
assert.Equal("leaf", leafBundle1.BundleType()) c.Assert(leafBundle1.BundleType(), qt.Equals, "leaf")
assert.Equal("b", leafBundle1.Section()) c.Assert(leafBundle1.Section(), qt.Equals, "b")
sectionB := s.getPage(page.KindSection, "b") sectionB := s.getPage(page.KindSection, "b")
assert.NotNil(sectionB) c.Assert(sectionB, qt.Not(qt.IsNil))
home, _ := s.Info.Home() home, _ := s.Info.Home()
assert.Equal("branch", home.BundleType()) c.Assert(home.BundleType(), qt.Equals, "branch")
// This is a root bundle and should live in the "home section" // This is a root bundle and should live in the "home section"
// See https://github.com/gohugoio/hugo/issues/4332 // See https://github.com/gohugoio/hugo/issues/4332
rootBundle := s.getPage(page.KindPage, "root") rootBundle := s.getPage(page.KindPage, "root")
assert.NotNil(rootBundle) c.Assert(rootBundle, qt.Not(qt.IsNil))
assert.True(rootBundle.Parent().IsHome()) c.Assert(rootBundle.Parent().IsHome(), qt.Equals, true)
if !ugly { if !ugly {
b.AssertFileContent(filepath.FromSlash("/work/public/root/index.html"), "Single RelPermalink: "+relURLBase+"/root/") b.AssertFileContent(filepath.FromSlash("/work/public/root/index.html"), "Single RelPermalink: "+relURLBase+"/root/")
b.AssertFileContent(filepath.FromSlash("/work/public/cpath/root/cindex.html"), "Single RelPermalink: "+relURLBase+"/cpath/root/") b.AssertFileContent(filepath.FromSlash("/work/public/cpath/root/cindex.html"), "Single RelPermalink: "+relURLBase+"/cpath/root/")
} }
leafBundle2 := s.getPage(page.KindPage, "a/b/index.md") leafBundle2 := s.getPage(page.KindPage, "a/b/index.md")
assert.NotNil(leafBundle2) c.Assert(leafBundle2, qt.Not(qt.IsNil))
unicodeBundle := s.getPage(page.KindPage, "c/bundle/index.md") unicodeBundle := s.getPage(page.KindPage, "c/bundle/index.md")
assert.NotNil(unicodeBundle) c.Assert(unicodeBundle, qt.Not(qt.IsNil))
pageResources := leafBundle1.Resources().ByType(pageResourceType) pageResources := leafBundle1.Resources().ByType(pageResourceType)
assert.Len(pageResources, 2) c.Assert(len(pageResources), qt.Equals, 2)
firstPage := pageResources[0].(page.Page) firstPage := pageResources[0].(page.Page)
secondPage := pageResources[1].(page.Page) secondPage := pageResources[1].(page.Page)
assert.Equal(filepath.FromSlash("/work/base/b/my-bundle/1.md"), firstPage.File().Filename(), secondPage.File().Filename()) c.Assert(firstPage.File().Filename(), qt.Equals, filepath.FromSlash("/work/base/b/my-bundle/1.md"))
assert.Contains(content(firstPage), "TheContent") c.Assert(content(firstPage), qt.Contains, "TheContent")
assert.Equal(6, len(leafBundle1.Resources())) c.Assert(len(leafBundle1.Resources()), qt.Equals, 6)
// Verify shortcode in bundled page // Verify shortcode in bundled page
assert.Contains(content(secondPage), filepath.FromSlash("MyShort in b/my-bundle/2.md")) c.Assert(content(secondPage), qt.Contains, filepath.FromSlash("MyShort in b/my-bundle/2.md"))
// https://github.com/gohugoio/hugo/issues/4582 // https://github.com/gohugoio/hugo/issues/4582
assert.Equal(leafBundle1, firstPage.Parent()) c.Assert(firstPage.Parent(), qt.Equals, leafBundle1)
assert.Equal(leafBundle1, secondPage.Parent()) c.Assert(secondPage.Parent(), qt.Equals, leafBundle1)
assert.Equal(firstPage, pageResources.GetMatch("1*")) c.Assert(pageResources.GetMatch("1*"), qt.Equals, firstPage)
assert.Equal(secondPage, pageResources.GetMatch("2*")) c.Assert(pageResources.GetMatch("2*"), qt.Equals, secondPage)
assert.Nil(pageResources.GetMatch("doesnotexist*")) c.Assert(pageResources.GetMatch("doesnotexist*"), qt.IsNil)
imageResources := leafBundle1.Resources().ByType("image") imageResources := leafBundle1.Resources().ByType("image")
assert.Equal(3, len(imageResources)) c.Assert(len(imageResources), qt.Equals, 3)
assert.NotNil(leafBundle1.OutputFormats().Get("CUSTOMO")) c.Assert(leafBundle1.OutputFormats().Get("CUSTOMO"), qt.Not(qt.IsNil))
relPermalinker := func(s string) string { relPermalinker := func(s string) string {
return fmt.Sprintf(s, relURLBase) return fmt.Sprintf(s, relURLBase)
@ -224,10 +224,10 @@ func TestPageBundlerSiteRegular(t *testing.T) {
b.AssertFileContent(filepath.FromSlash("/work/public/2017/pageslug/c/logo.png"), "content") b.AssertFileContent(filepath.FromSlash("/work/public/2017/pageslug/c/logo.png"), "content")
b.AssertFileContent(filepath.FromSlash("/work/public/cpath/2017/pageslug/c/logo.png"), "content") b.AssertFileContent(filepath.FromSlash("/work/public/cpath/2017/pageslug/c/logo.png"), "content")
assert.False(b.CheckExists("/work/public/cpath/cpath/2017/pageslug/c/logo.png")) c.Assert(b.CheckExists("/work/public/cpath/cpath/2017/pageslug/c/logo.png"), qt.Equals, false)
// Custom media type defined in site config. // Custom media type defined in site config.
assert.Len(leafBundle1.Resources().ByType("bepsays"), 1) c.Assert(len(leafBundle1.Resources().ByType("bepsays")), qt.Equals, 1)
if ugly { if ugly {
b.AssertFileContent(filepath.FromSlash("/work/public/2017/pageslug.html"), b.AssertFileContent(filepath.FromSlash("/work/public/2017/pageslug.html"),
@ -279,7 +279,7 @@ func TestPageBundlerSiteMultilingual(t *testing.T) {
t.Run(fmt.Sprintf("ugly=%t", ugly), t.Run(fmt.Sprintf("ugly=%t", ugly),
func(t *testing.T) { func(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
fs, cfg := newTestBundleSourcesMultilingual(t) fs, cfg := newTestBundleSourcesMultilingual(t)
cfg.Set("uglyURLs", ugly) cfg.Set("uglyURLs", ugly)
@ -288,17 +288,17 @@ func TestPageBundlerSiteMultilingual(t *testing.T) {
sites := b.H sites := b.H
assert.Equal(2, len(sites.Sites)) c.Assert(len(sites.Sites), qt.Equals, 2)
s := sites.Sites[0] s := sites.Sites[0]
assert.Equal(8, len(s.RegularPages())) c.Assert(len(s.RegularPages()), qt.Equals, 8)
assert.Equal(16, len(s.Pages())) c.Assert(len(s.Pages()), qt.Equals, 16)
//dumpPages(s.AllPages()...) //dumpPages(s.AllPages()...)
assert.Equal(31, len(s.AllPages())) c.Assert(len(s.AllPages()), qt.Equals, 31)
bundleWithSubPath := s.getPage(page.KindPage, "lb/index") bundleWithSubPath := s.getPage(page.KindPage, "lb/index")
assert.NotNil(bundleWithSubPath) c.Assert(bundleWithSubPath, qt.Not(qt.IsNil))
// See https://github.com/gohugoio/hugo/issues/4312 // See https://github.com/gohugoio/hugo/issues/4312
// Before that issue: // Before that issue:
@ -312,37 +312,36 @@ func TestPageBundlerSiteMultilingual(t *testing.T) {
// These may also be translated, so we also need to test that. // These may also be translated, so we also need to test that.
// "bf", "my-bf-bundle", "index.md + nn // "bf", "my-bf-bundle", "index.md + nn
bfBundle := s.getPage(page.KindPage, "bf/my-bf-bundle/index") bfBundle := s.getPage(page.KindPage, "bf/my-bf-bundle/index")
assert.NotNil(bfBundle) c.Assert(bfBundle, qt.Not(qt.IsNil))
assert.Equal("en", bfBundle.Language().Lang) c.Assert(bfBundle.Language().Lang, qt.Equals, "en")
assert.Equal(bfBundle, s.getPage(page.KindPage, "bf/my-bf-bundle/index.md")) c.Assert(s.getPage(page.KindPage, "bf/my-bf-bundle/index.md"), qt.Equals, bfBundle)
assert.Equal(bfBundle, s.getPage(page.KindPage, "bf/my-bf-bundle")) c.Assert(s.getPage(page.KindPage, "bf/my-bf-bundle"), qt.Equals, bfBundle)
assert.Equal(bfBundle, s.getPage(page.KindPage, "my-bf-bundle")) c.Assert(s.getPage(page.KindPage, "my-bf-bundle"), qt.Equals, bfBundle)
nnSite := sites.Sites[1] nnSite := sites.Sites[1]
assert.Equal(7, len(nnSite.RegularPages())) c.Assert(len(nnSite.RegularPages()), qt.Equals, 7)
bfBundleNN := nnSite.getPage(page.KindPage, "bf/my-bf-bundle/index") bfBundleNN := nnSite.getPage(page.KindPage, "bf/my-bf-bundle/index")
assert.NotNil(bfBundleNN) c.Assert(bfBundleNN, qt.Not(qt.IsNil))
assert.Equal("nn", bfBundleNN.Language().Lang) c.Assert(bfBundleNN.Language().Lang, qt.Equals, "nn")
assert.Equal(bfBundleNN, nnSite.getPage(page.KindPage, "bf/my-bf-bundle/index.nn.md")) c.Assert(nnSite.getPage(page.KindPage, "bf/my-bf-bundle/index.nn.md"), qt.Equals, bfBundleNN)
assert.Equal(bfBundleNN, nnSite.getPage(page.KindPage, "bf/my-bf-bundle")) c.Assert(nnSite.getPage(page.KindPage, "bf/my-bf-bundle"), qt.Equals, bfBundleNN)
assert.Equal(bfBundleNN, nnSite.getPage(page.KindPage, "my-bf-bundle")) c.Assert(nnSite.getPage(page.KindPage, "my-bf-bundle"), qt.Equals, bfBundleNN)
// See https://github.com/gohugoio/hugo/issues/4295 // See https://github.com/gohugoio/hugo/issues/4295
// Every resource should have its Name prefixed with its base folder. // Every resource should have its Name prefixed with its base folder.
cBundleResources := bundleWithSubPath.Resources().Match("c/**") cBundleResources := bundleWithSubPath.Resources().Match("c/**")
assert.Equal(4, len(cBundleResources)) c.Assert(len(cBundleResources), qt.Equals, 4)
bundlePage := bundleWithSubPath.Resources().GetMatch("c/page*") bundlePage := bundleWithSubPath.Resources().GetMatch("c/page*")
assert.NotNil(bundlePage) c.Assert(bundlePage, qt.Not(qt.IsNil))
assert.IsType(&pageState{}, bundlePage)
bcBundleNN, _ := nnSite.getPageNew(nil, "bc") bcBundleNN, _ := nnSite.getPageNew(nil, "bc")
assert.NotNil(bcBundleNN) c.Assert(bcBundleNN, qt.Not(qt.IsNil))
bcBundleEN, _ := s.getPageNew(nil, "bc") bcBundleEN, _ := s.getPageNew(nil, "bc")
assert.Equal("nn", bcBundleNN.Language().Lang) c.Assert(bcBundleNN.Language().Lang, qt.Equals, "nn")
assert.Equal("en", bcBundleEN.Language().Lang) c.Assert(bcBundleEN.Language().Lang, qt.Equals, "en")
assert.Equal(3, len(bcBundleNN.Resources())) c.Assert(len(bcBundleNN.Resources()), qt.Equals, 3)
assert.Equal(3, len(bcBundleEN.Resources())) c.Assert(len(bcBundleEN.Resources()), qt.Equals, 3)
b.AssertFileContent("public/en/bc/data1.json", "data1") b.AssertFileContent("public/en/bc/data1.json", "data1")
b.AssertFileContent("public/en/bc/data2.json", "data2") b.AssertFileContent("public/en/bc/data2.json", "data2")
b.AssertFileContent("public/en/bc/logo-bc.png", "logo") b.AssertFileContent("public/en/bc/logo-bc.png", "logo")
@ -357,22 +356,22 @@ func TestPageBundlerSiteMultilingual(t *testing.T) {
func TestMultilingualDisableDefaultLanguage(t *testing.T) { func TestMultilingualDisableDefaultLanguage(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
_, cfg := newTestBundleSourcesMultilingual(t) _, cfg := newTestBundleSourcesMultilingual(t)
cfg.Set("disableLanguages", []string{"en"}) cfg.Set("disableLanguages", []string{"en"})
err := loadDefaultSettingsFor(cfg) err := loadDefaultSettingsFor(cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
err = loadLanguageSettings(cfg, nil) err = loadLanguageSettings(cfg, nil)
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
assert.Contains(err.Error(), "cannot disable default language") c.Assert(err.Error(), qt.Contains, "cannot disable default language")
} }
func TestMultilingualDisableLanguage(t *testing.T) { func TestMultilingualDisableLanguage(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
fs, cfg := newTestBundleSourcesMultilingual(t) fs, cfg := newTestBundleSourcesMultilingual(t)
cfg.Set("disableLanguages", []string{"nn"}) cfg.Set("disableLanguages", []string{"nn"})
@ -380,19 +379,19 @@ func TestMultilingualDisableLanguage(t *testing.T) {
b.Build(BuildCfg{}) b.Build(BuildCfg{})
sites := b.H sites := b.H
assert.Equal(1, len(sites.Sites)) c.Assert(len(sites.Sites), qt.Equals, 1)
s := sites.Sites[0] s := sites.Sites[0]
assert.Equal(8, len(s.RegularPages())) c.Assert(len(s.RegularPages()), qt.Equals, 8)
assert.Equal(16, len(s.Pages())) c.Assert(len(s.Pages()), qt.Equals, 16)
// No nn pages // No nn pages
assert.Equal(16, len(s.AllPages())) c.Assert(len(s.AllPages()), qt.Equals, 16)
for _, p := range s.rawAllPages { for _, p := range s.rawAllPages {
assert.True(p.Language().Lang != "nn") c.Assert(p.Language().Lang != "nn", qt.Equals, true)
} }
for _, p := range s.AllPages() { for _, p := range s.AllPages() {
assert.True(p.Language().Lang != "nn") c.Assert(p.Language().Lang != "nn", qt.Equals, true)
} }
} }
@ -405,42 +404,42 @@ func TestPageBundlerSiteWitSymbolicLinksInContent(t *testing.T) {
os.Chdir(wd) os.Chdir(wd)
}() }()
assert := require.New(t) c := qt.New(t)
// We need to use the OS fs for this. // We need to use the OS fs for this.
cfg := viper.New() cfg := viper.New()
fs := hugofs.NewFrom(hugofs.Os, cfg) fs := hugofs.NewFrom(hugofs.Os, cfg)
workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugosym") workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugosym")
assert.NoError(err) c.Assert(err, qt.IsNil)
contentDirName := "content" contentDirName := "content"
contentDir := filepath.Join(workDir, contentDirName) contentDir := filepath.Join(workDir, contentDirName)
assert.NoError(os.MkdirAll(filepath.Join(contentDir, "a"), 0777)) c.Assert(os.MkdirAll(filepath.Join(contentDir, "a"), 0777), qt.IsNil)
for i := 1; i <= 3; i++ { for i := 1; i <= 3; i++ {
assert.NoError(os.MkdirAll(filepath.Join(workDir, fmt.Sprintf("symcontent%d", i)), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, fmt.Sprintf("symcontent%d", i)), 0777), qt.IsNil)
} }
assert.NoError(os.MkdirAll(filepath.Join(workDir, "symcontent2", "a1"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "symcontent2", "a1"), 0777), qt.IsNil)
// Symlinked sections inside content. // Symlinked sections inside content.
os.Chdir(contentDir) os.Chdir(contentDir)
for i := 1; i <= 3; i++ { for i := 1; i <= 3; i++ {
assert.NoError(os.Symlink(filepath.FromSlash(fmt.Sprintf(("../symcontent%d"), i)), fmt.Sprintf("symbolic%d", i))) c.Assert(os.Symlink(filepath.FromSlash(fmt.Sprintf(("../symcontent%d"), i)), fmt.Sprintf("symbolic%d", i)), qt.IsNil)
} }
assert.NoError(os.Chdir(filepath.Join(contentDir, "a"))) c.Assert(os.Chdir(filepath.Join(contentDir, "a")), qt.IsNil)
// Create a symlink to one single content file // Create a symlink to one single content file
assert.NoError(os.Symlink(filepath.FromSlash("../../symcontent2/a1/page.md"), "page_s.md")) c.Assert(os.Symlink(filepath.FromSlash("../../symcontent2/a1/page.md"), "page_s.md"), qt.IsNil)
assert.NoError(os.Chdir(filepath.FromSlash("../../symcontent3"))) c.Assert(os.Chdir(filepath.FromSlash("../../symcontent3")), qt.IsNil)
// Create a circular symlink. Will print some warnings. // Create a circular symlink. Will print some warnings.
assert.NoError(os.Symlink(filepath.Join("..", contentDirName), filepath.FromSlash("circus"))) c.Assert(os.Symlink(filepath.Join("..", contentDirName), filepath.FromSlash("circus")), qt.IsNil)
assert.NoError(os.Chdir(workDir)) c.Assert(os.Chdir(workDir), qt.IsNil)
defer clean() defer clean()
@ -491,11 +490,11 @@ TheContent.
b.Build(BuildCfg{}) b.Build(BuildCfg{})
s := b.H.Sites[0] s := b.H.Sites[0]
assert.Equal(7, len(s.RegularPages())) c.Assert(len(s.RegularPages()), qt.Equals, 7)
a1Bundle := s.getPage(page.KindPage, "symbolic2/a1/index.md") a1Bundle := s.getPage(page.KindPage, "symbolic2/a1/index.md")
assert.NotNil(a1Bundle) c.Assert(a1Bundle, qt.Not(qt.IsNil))
assert.Equal(2, len(a1Bundle.Resources())) c.Assert(len(a1Bundle.Resources()), qt.Equals, 2)
assert.Equal(1, len(a1Bundle.Resources().ByType(pageResourceType))) c.Assert(len(a1Bundle.Resources().ByType(pageResourceType)), qt.Equals, 1)
b.AssertFileContent(filepath.FromSlash(workDir+"/public/a/page/index.html"), "TheContent") b.AssertFileContent(filepath.FromSlash(workDir+"/public/a/page/index.html"), "TheContent")
b.AssertFileContent(filepath.FromSlash(workDir+"/public/symbolic1/s1/index.html"), "TheContent") b.AssertFileContent(filepath.FromSlash(workDir+"/public/symbolic1/s1/index.html"), "TheContent")
@ -507,7 +506,7 @@ func TestPageBundlerHeadless(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
assert := require.New(t) c := qt.New(t)
workDir := "/work" workDir := "/work"
cfg.Set("workingDir", workDir) cfg.Set("workingDir", workDir)
@ -549,30 +548,29 @@ HEADLESS {{< myShort >}}
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
assert.Equal(1, len(s.RegularPages())) c.Assert(len(s.RegularPages()), qt.Equals, 1)
assert.Equal(1, len(s.headlessPages)) c.Assert(len(s.headlessPages), qt.Equals, 1)
regular := s.getPage(page.KindPage, "a/index") regular := s.getPage(page.KindPage, "a/index")
assert.Equal("/s1/", regular.RelPermalink()) c.Assert(regular.RelPermalink(), qt.Equals, "/s1/")
headless := s.getPage(page.KindPage, "b/index") headless := s.getPage(page.KindPage, "b/index")
assert.NotNil(headless) c.Assert(headless, qt.Not(qt.IsNil))
assert.Equal("Headless Bundle in Topless Bar", headless.Title()) c.Assert(headless.Title(), qt.Equals, "Headless Bundle in Topless Bar")
assert.Equal("", headless.RelPermalink()) c.Assert(headless.RelPermalink(), qt.Equals, "")
assert.Equal("", headless.Permalink()) c.Assert(headless.Permalink(), qt.Equals, "")
assert.Contains(content(headless), "HEADLESS SHORTCODE") c.Assert(content(headless), qt.Contains, "HEADLESS SHORTCODE")
headlessResources := headless.Resources() headlessResources := headless.Resources()
assert.Equal(3, len(headlessResources)) c.Assert(len(headlessResources), qt.Equals, 3)
assert.Equal(2, len(headlessResources.Match("l*"))) c.Assert(len(headlessResources.Match("l*")), qt.Equals, 2)
pageResource := headlessResources.GetMatch("p*") pageResource := headlessResources.GetMatch("p*")
assert.NotNil(pageResource) c.Assert(pageResource, qt.Not(qt.IsNil))
assert.IsType(&pageState{}, pageResource)
p := pageResource.(page.Page) p := pageResource.(page.Page)
assert.Contains(content(p), "SHORTCODE") c.Assert(content(p), qt.Contains, "SHORTCODE")
assert.Equal("p1.md", p.Name()) c.Assert(p.Name(), qt.Equals, "p1.md")
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
th.assertFileContent(filepath.FromSlash(workDir+"/public/s1/index.html"), "TheContent") th.assertFileContent(filepath.FromSlash(workDir+"/public/s1/index.html"), "TheContent")
th.assertFileContent(filepath.FromSlash(workDir+"/public/s1/l1.png"), "PNG") th.assertFileContent(filepath.FromSlash(workDir+"/public/s1/l1.png"), "PNG")
@ -584,7 +582,7 @@ HEADLESS {{< myShort >}}
} }
func TestMultiSiteBundles(t *testing.T) { func TestMultiSiteBundles(t *testing.T) {
assert := require.New(t) c := qt.New(t)
b := newTestSitesBuilder(t) b := newTestSitesBuilder(t)
b.WithConfigFile("toml", ` b.WithConfigFile("toml", `
@ -656,12 +654,12 @@ Single content.
b.AssertFileContent("public/mybundle/data.yaml", "data en") b.AssertFileContent("public/mybundle/data.yaml", "data en")
b.AssertFileContent("public/mybundle/forms.yaml", "forms en") b.AssertFileContent("public/mybundle/forms.yaml", "forms en")
assert.False(b.CheckExists("public/nn/nn/mybundle/data.yaml")) c.Assert(b.CheckExists("public/nn/nn/mybundle/data.yaml"), qt.Equals, false)
assert.False(b.CheckExists("public/en/mybundle/data.yaml")) c.Assert(b.CheckExists("public/en/mybundle/data.yaml"), qt.Equals, false)
homeEn := b.H.Sites[0].home homeEn := b.H.Sites[0].home
assert.NotNil(homeEn) c.Assert(homeEn, qt.Not(qt.IsNil))
assert.Equal(2018, homeEn.Date().Year()) c.Assert(homeEn.Date().Year(), qt.Equals, 2018)
b.AssertFileContent("public/section-not-bundle/index.html", "Section Page", "Content: <p>Section content.</p>") b.AssertFileContent("public/section-not-bundle/index.html", "Section Page", "Content: <p>Section content.</p>")
b.AssertFileContent("public/section-not-bundle/single/index.html", "Section Single", "|<p>Single content.</p>") b.AssertFileContent("public/section-not-bundle/single/index.html", "Section Single", "|<p>Single content.</p>")
@ -670,7 +668,7 @@ Single content.
func newTestBundleSources(t *testing.T) (*hugofs.Fs, *viper.Viper) { func newTestBundleSources(t *testing.T) (*hugofs.Fs, *viper.Viper) {
cfg, fs := newTestCfgBasic() cfg, fs := newTestCfgBasic()
assert := require.New(t) c := qt.New(t)
workDir := "/work" workDir := "/work"
cfg.Set("workingDir", workDir) cfg.Set("workingDir", workDir)
@ -814,22 +812,22 @@ Content for 은행.
// Write a real image into one of the bundle above. // Write a real image into one of the bundle above.
src, err := os.Open("testdata/sunset.jpg") src, err := os.Open("testdata/sunset.jpg")
assert.NoError(err) c.Assert(err, qt.IsNil)
// We need 2 to test https://github.com/gohugoio/hugo/issues/4202 // We need 2 to test https://github.com/gohugoio/hugo/issues/4202
out, err := fs.Source.Create(filepath.Join(workDir, "base", "b", "my-bundle", "sunset1.jpg")) out, err := fs.Source.Create(filepath.Join(workDir, "base", "b", "my-bundle", "sunset1.jpg"))
assert.NoError(err) c.Assert(err, qt.IsNil)
out2, err := fs.Source.Create(filepath.Join(workDir, "base", "b", "my-bundle", "sunset2.jpg")) out2, err := fs.Source.Create(filepath.Join(workDir, "base", "b", "my-bundle", "sunset2.jpg"))
assert.NoError(err) c.Assert(err, qt.IsNil)
_, err = io.Copy(out, src) _, err = io.Copy(out, src)
assert.NoError(err) c.Assert(err, qt.IsNil)
out.Close() out.Close()
src.Seek(0, 0) src.Seek(0, 0)
_, err = io.Copy(out2, src) _, err = io.Copy(out2, src)
out2.Close() out2.Close()
src.Close() src.Close()
assert.NoError(err) c.Assert(err, qt.IsNil)
return fs, cfg return fs, cfg
@ -959,7 +957,7 @@ date: 2017-01-15
// https://github.com/gohugoio/hugo/issues/4870 // https://github.com/gohugoio/hugo/issues/4870
func TestBundleSlug(t *testing.T) { func TestBundleSlug(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
const pageTemplate = `--- const pageTemplate = `---
title: Title title: Title
@ -980,8 +978,8 @@ slug: %s
"|/about/services1/this-is-the-slug/|/", "|/about/services1/this-is-the-slug/|/",
"|/about/services2/this-is-another-slug/|") "|/about/services2/this-is-another-slug/|")
assert.True(b.CheckExists("public/about/services1/this-is-the-slug/index.html")) c.Assert(b.CheckExists("public/about/services1/this-is-the-slug/index.html"), qt.Equals, true)
assert.True(b.CheckExists("public/about/services2/this-is-another-slug/index.html")) c.Assert(b.CheckExists("public/about/services2/this-is-another-slug/index.html"), qt.Equals, true)
} }
@ -1087,8 +1085,8 @@ slug: leaf
b.AssertFileContent("public/en/enonly/myen/index.html", "Single: en: Page") b.AssertFileContent("public/en/enonly/myen/index.html", "Single: en: Page")
b.AssertFileContent("public/en/enonly/myendata.json", "mydata") b.AssertFileContent("public/en/enonly/myendata.json", "mydata")
assert := require.New(t) c := qt.New(t)
assert.False(b.CheckExists("public/sv/enonly/myen/index.html")) c.Assert(b.CheckExists("public/sv/enonly/myen/index.html"), qt.Equals, false)
// Both leaf and branch bundle in same dir // Both leaf and branch bundle in same dir
// We log a warning about it, but we keep both. // We log a warning about it, but we keep both.

View file

@ -21,10 +21,10 @@ import (
"testing" "testing"
"time" "time"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/stretchr/testify/require"
) )
const pageCollectionsPageTemplate = `--- const pageCollectionsPageTemplate = `---
@ -72,6 +72,7 @@ func BenchmarkGetPage(b *testing.B) {
func BenchmarkGetPageRegular(b *testing.B) { func BenchmarkGetPageRegular(b *testing.B) {
var ( var (
c = qt.New(b)
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
r = rand.New(rand.NewSource(time.Now().UnixNano())) r = rand.New(rand.NewSource(time.Now().UnixNano()))
) )
@ -94,7 +95,7 @@ func BenchmarkGetPageRegular(b *testing.B) {
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
page, _ := s.getPageNew(nil, pagePaths[i]) page, _ := s.getPageNew(nil, pagePaths[i])
require.NotNil(b, page) c.Assert(page, qt.Not(qt.IsNil))
} }
} }
@ -105,27 +106,28 @@ type testCase struct {
expectedTitle string expectedTitle string
} }
func (t *testCase) check(p page.Page, err error, errorMsg string, assert *require.Assertions) { func (t *testCase) check(p page.Page, err error, errorMsg string, c *qt.C) {
errorComment := qt.Commentf(errorMsg)
switch t.kind { switch t.kind {
case "Ambiguous": case "Ambiguous":
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
assert.Nil(p, errorMsg) c.Assert(p, qt.IsNil, errorComment)
case "NoPage": case "NoPage":
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Nil(p, errorMsg) c.Assert(p, qt.IsNil, errorComment)
default: default:
assert.NoError(err, errorMsg) c.Assert(err, qt.IsNil, errorComment)
assert.NotNil(p, errorMsg) c.Assert(p, qt.Not(qt.IsNil), errorComment)
assert.Equal(t.kind, p.Kind(), errorMsg) c.Assert(p.Kind(), qt.Equals, t.kind, errorComment)
assert.Equal(t.expectedTitle, p.Title(), errorMsg) c.Assert(p.Title(), qt.Equals, t.expectedTitle, errorComment)
} }
} }
func TestGetPage(t *testing.T) { func TestGetPage(t *testing.T) {
var ( var (
assert = require.New(t)
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
c = qt.New(t)
) )
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
@ -156,8 +158,8 @@ func TestGetPage(t *testing.T) {
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
sec3, err := s.getPageNew(nil, "/sect3") sec3, err := s.getPageNew(nil, "/sect3")
assert.NoError(err, "error getting Page for /sec3") c.Assert(err, qt.IsNil)
assert.NotNil(sec3, "failed to get Page for /sec3") c.Assert(sec3, qt.Not(qt.IsNil))
tests := []testCase{ tests := []testCase{
// legacy content root relative paths // legacy content root relative paths
@ -227,7 +229,7 @@ func TestGetPage(t *testing.T) {
if test.context == nil { if test.context == nil {
args := append([]string{test.kind}, test.path...) args := append([]string{test.kind}, test.path...)
page, err := s.Info.GetPage(args...) page, err := s.Info.GetPage(args...)
test.check(page, err, errorMsg, assert) test.check(page, err, errorMsg, c)
} }
// test new internal Site.getPageNew // test new internal Site.getPageNew
@ -238,7 +240,7 @@ func TestGetPage(t *testing.T) {
ref = path.Join(test.path...) ref = path.Join(test.path...)
} }
page2, err := s.getPageNew(test.context, ref) page2, err := s.getPageNew(test.context, ref)
test.check(page2, err, errorMsg, assert) test.check(page2, err, errorMsg, c)
} }
} }

View file

@ -26,9 +26,9 @@ import (
"github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/loggers"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require"
) )
func TestPagesCapture(t *testing.T) { func TestPagesCapture(t *testing.T) {
@ -36,10 +36,10 @@ func TestPagesCapture(t *testing.T) {
cfg, hfs := newTestCfg() cfg, hfs := newTestCfg()
fs := hfs.Source fs := hfs.Source
assert := require.New(t) c := qt.New(t)
var writeFile = func(filename string) { var writeFile = func(filename string) {
assert.NoError(afero.WriteFile(fs, filepath.FromSlash(filename), []byte(fmt.Sprintf("content-%s", filename)), 0755)) c.Assert(afero.WriteFile(fs, filepath.FromSlash(filename), []byte(fmt.Sprintf("content-%s", filename)), 0755), qt.IsNil)
} }
writeFile("_index.md") writeFile("_index.md")
@ -53,22 +53,22 @@ func TestPagesCapture(t *testing.T) {
writeFile("pages/page.png") writeFile("pages/page.png")
ps, err := helpers.NewPathSpec(hugofs.NewFrom(fs, cfg), cfg, loggers.NewErrorLogger()) ps, err := helpers.NewPathSpec(hugofs.NewFrom(fs, cfg), cfg, loggers.NewErrorLogger())
assert.NoError(err) c.Assert(err, qt.IsNil)
sourceSpec := source.NewSourceSpec(ps, fs) sourceSpec := source.NewSourceSpec(ps, fs)
t.Run("Collect", func(t *testing.T) { t.Run("Collect", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
proc := &testPagesCollectorProcessor{} proc := &testPagesCollectorProcessor{}
c := newPagesCollector(sourceSpec, loggers.NewErrorLogger(), nil, proc) coll := newPagesCollector(sourceSpec, loggers.NewErrorLogger(), nil, proc)
assert.NoError(c.Collect()) c.Assert(coll.Collect(), qt.IsNil)
assert.Equal(4, len(proc.items)) c.Assert(len(proc.items), qt.Equals, 4)
}) })
t.Run("error in Wait", func(t *testing.T) { t.Run("error in Wait", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
c := newPagesCollector(sourceSpec, loggers.NewErrorLogger(), nil, coll := newPagesCollector(sourceSpec, loggers.NewErrorLogger(), nil,
&testPagesCollectorProcessor{waitErr: errors.New("failed")}) &testPagesCollectorProcessor{waitErr: errors.New("failed")})
assert.Error(c.Collect()) c.Assert(coll.Collect(), qt.Not(qt.IsNil))
}) })
} }

View file

@ -17,15 +17,15 @@ import (
"fmt" "fmt"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource"
"github.com/stretchr/testify/require"
) )
// TODO(bep) move and rewrite in resource/page. // TODO(bep) move and rewrite in resource/page.
func TestMergeLanguages(t *testing.T) { func TestMergeLanguages(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
b := newTestSiteForLanguageMerge(t, 30) b := newTestSiteForLanguageMerge(t, 30)
b.CreateSites() b.CreateSites()
@ -38,53 +38,53 @@ func TestMergeLanguages(t *testing.T) {
frSite := h.Sites[1] frSite := h.Sites[1]
nnSite := h.Sites[2] nnSite := h.Sites[2]
assert.Equal(31, len(enSite.RegularPages())) c.Assert(len(enSite.RegularPages()), qt.Equals, 31)
assert.Equal(6, len(frSite.RegularPages())) c.Assert(len(frSite.RegularPages()), qt.Equals, 6)
assert.Equal(12, len(nnSite.RegularPages())) c.Assert(len(nnSite.RegularPages()), qt.Equals, 12)
for i := 0; i < 2; i++ { for i := 0; i < 2; i++ {
mergedNN := nnSite.RegularPages().MergeByLanguage(enSite.RegularPages()) mergedNN := nnSite.RegularPages().MergeByLanguage(enSite.RegularPages())
assert.Equal(31, len(mergedNN)) c.Assert(len(mergedNN), qt.Equals, 31)
for i := 1; i <= 31; i++ { for i := 1; i <= 31; i++ {
expectedLang := "en" expectedLang := "en"
if i == 2 || i%3 == 0 || i == 31 { if i == 2 || i%3 == 0 || i == 31 {
expectedLang = "nn" expectedLang = "nn"
} }
p := mergedNN[i-1] p := mergedNN[i-1]
assert.Equal(expectedLang, p.Language().Lang, fmt.Sprintf("Test %d", i)) c.Assert(p.Language().Lang, qt.Equals, expectedLang)
} }
} }
mergedFR := frSite.RegularPages().MergeByLanguage(enSite.RegularPages()) mergedFR := frSite.RegularPages().MergeByLanguage(enSite.RegularPages())
assert.Equal(31, len(mergedFR)) c.Assert(len(mergedFR), qt.Equals, 31)
for i := 1; i <= 31; i++ { for i := 1; i <= 31; i++ {
expectedLang := "en" expectedLang := "en"
if i%5 == 0 { if i%5 == 0 {
expectedLang = "fr" expectedLang = "fr"
} }
p := mergedFR[i-1] p := mergedFR[i-1]
assert.Equal(expectedLang, p.Language().Lang, fmt.Sprintf("Test %d", i)) c.Assert(p.Language().Lang, qt.Equals, expectedLang)
} }
firstNN := nnSite.RegularPages()[0] firstNN := nnSite.RegularPages()[0]
assert.Equal(4, len(firstNN.Sites())) c.Assert(len(firstNN.Sites()), qt.Equals, 4)
assert.Equal("en", firstNN.Sites().First().Language().Lang) c.Assert(firstNN.Sites().First().Language().Lang, qt.Equals, "en")
nnBundle := nnSite.getPage("page", "bundle") nnBundle := nnSite.getPage("page", "bundle")
enBundle := enSite.getPage("page", "bundle") enBundle := enSite.getPage("page", "bundle")
assert.Equal(6, len(enBundle.Resources())) c.Assert(len(enBundle.Resources()), qt.Equals, 6)
assert.Equal(2, len(nnBundle.Resources())) c.Assert(len(nnBundle.Resources()), qt.Equals, 2)
var ri interface{} = nnBundle.Resources() var ri interface{} = nnBundle.Resources()
// This looks less ugly in the templates ... // This looks less ugly in the templates ...
mergedNNResources := ri.(resource.ResourcesLanguageMerger).MergeByLanguage(enBundle.Resources()) mergedNNResources := ri.(resource.ResourcesLanguageMerger).MergeByLanguage(enBundle.Resources())
assert.Equal(6, len(mergedNNResources)) c.Assert(len(mergedNNResources), qt.Equals, 6)
unchanged, err := nnSite.RegularPages().MergeByLanguageInterface(nil) unchanged, err := nnSite.RegularPages().MergeByLanguageInterface(nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(nnSite.RegularPages(), unchanged) c.Assert(unchanged, deepEqualsPages, nnSite.RegularPages())
} }

View file

@ -16,51 +16,52 @@ package paths
import ( import (
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestBaseURL(t *testing.T) { func TestBaseURL(t *testing.T) {
c := qt.New(t)
b, err := newBaseURLFromString("http://example.com") b, err := newBaseURLFromString("http://example.com")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "http://example.com", b.String()) c.Assert(b.String(), qt.Equals, "http://example.com")
p, err := b.WithProtocol("webcal://") p, err := b.WithProtocol("webcal://")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "webcal://example.com", p) c.Assert(p, qt.Equals, "webcal://example.com")
p, err = b.WithProtocol("webcal") p, err = b.WithProtocol("webcal")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "webcal://example.com", p) c.Assert(p, qt.Equals, "webcal://example.com")
_, err = b.WithProtocol("mailto:") _, err = b.WithProtocol("mailto:")
require.Error(t, err) c.Assert(err, qt.Not(qt.IsNil))
b, err = newBaseURLFromString("mailto:hugo@rules.com") b, err = newBaseURLFromString("mailto:hugo@rules.com")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "mailto:hugo@rules.com", b.String()) c.Assert(b.String(), qt.Equals, "mailto:hugo@rules.com")
// These are pretty constructed // These are pretty constructed
p, err = b.WithProtocol("webcal") p, err = b.WithProtocol("webcal")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "webcal:hugo@rules.com", p) c.Assert(p, qt.Equals, "webcal:hugo@rules.com")
p, err = b.WithProtocol("webcal://") p, err = b.WithProtocol("webcal://")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "webcal://hugo@rules.com", p) c.Assert(p, qt.Equals, "webcal://hugo@rules.com")
// Test with "non-URLs". Some people will try to use these as a way to get // Test with "non-URLs". Some people will try to use these as a way to get
// relative URLs working etc. // relative URLs working etc.
b, err = newBaseURLFromString("/") b, err = newBaseURLFromString("/")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "/", b.String()) c.Assert(b.String(), qt.Equals, "/")
b, err = newBaseURLFromString("") b, err = newBaseURLFromString("")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "", b.String()) c.Assert(b.String(), qt.Equals, "")
// BaseURL with sub path // BaseURL with sub path
b, err = newBaseURLFromString("http://example.com/sub") b, err = newBaseURLFromString("http://example.com/sub")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, "http://example.com/sub", b.String()) c.Assert(b.String(), qt.Equals, "http://example.com/sub")
require.Equal(t, "http://example.com", b.HostURL()) c.Assert(b.HostURL(), qt.Equals, "http://example.com")
} }

View file

@ -18,13 +18,13 @@ import (
"github.com/gohugoio/hugo/langs" "github.com/gohugoio/hugo/langs"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestNewPaths(t *testing.T) { func TestNewPaths(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := viper.New() v := viper.New()
fs := hugofs.NewMem(v) fs := hugofs.NewMem(v)
@ -43,9 +43,9 @@ func TestNewPaths(t *testing.T) {
langs.LoadLanguageSettings(v, nil) langs.LoadLanguageSettings(v, nil)
p, err := New(fs, v) p, err := New(fs, v)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(true, p.defaultContentLanguageInSubdir) c.Assert(p.defaultContentLanguageInSubdir, qt.Equals, true)
assert.Equal("no", p.DefaultContentLanguage) c.Assert(p.DefaultContentLanguage, qt.Equals, "no")
assert.Equal(true, p.multilingual) c.Assert(p.multilingual, qt.Equals, true)
} }

View file

@ -22,7 +22,7 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
@ -34,9 +34,9 @@ func TestSCSSWithIncludePaths(t *testing.T) {
if !scss.Supports() { if !scss.Supports() {
t.Skip("Skip SCSS") t.Skip("Skip SCSS")
} }
assert := require.New(t) c := qt.New(t)
workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-include") workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-include")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer clean() defer clean()
v := viper.New() v := viper.New()
@ -49,13 +49,13 @@ func TestSCSSWithIncludePaths(t *testing.T) {
fooDir := filepath.Join(workDir, "node_modules", "foo") fooDir := filepath.Join(workDir, "node_modules", "foo")
scssDir := filepath.Join(workDir, "assets", "scss") scssDir := filepath.Join(workDir, "assets", "scss")
assert.NoError(os.MkdirAll(fooDir, 0777)) c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "data"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(scssDir), 0777)) c.Assert(os.MkdirAll(filepath.Join(scssDir), 0777), qt.IsNil)
b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), ` b.WithSourceFile(filepath.Join(fooDir, "_moo.scss"), `
$moolor: #fff; $moolor: #fff;
@ -85,9 +85,9 @@ func TestSCSSWithThemeOverrides(t *testing.T) {
if !scss.Supports() { if !scss.Supports() {
t.Skip("Skip SCSS") t.Skip("Skip SCSS")
} }
assert := require.New(t) c := qt.New(t)
workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-include") workDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-scss-include")
assert.NoError(err) c.Assert(err, qt.IsNil)
defer clean() defer clean()
theme := "mytheme" theme := "mytheme"
@ -105,14 +105,14 @@ func TestSCSSWithThemeOverrides(t *testing.T) {
fooDir := filepath.Join(workDir, "node_modules", "foo") fooDir := filepath.Join(workDir, "node_modules", "foo")
scssDir := filepath.Join(workDir, "assets", "scss") scssDir := filepath.Join(workDir, "assets", "scss")
scssThemeDir := filepath.Join(themeDirs, "assets", "scss") scssThemeDir := filepath.Join(themeDirs, "assets", "scss")
assert.NoError(os.MkdirAll(fooDir, 0777)) c.Assert(os.MkdirAll(fooDir, 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "content", "sect"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "data"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "data"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "i18n"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "shortcodes"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777)) c.Assert(os.MkdirAll(filepath.Join(workDir, "layouts", "_default"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(scssDir, "components"), 0777)) c.Assert(os.MkdirAll(filepath.Join(scssDir, "components"), 0777), qt.IsNil)
assert.NoError(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777)) c.Assert(os.MkdirAll(filepath.Join(scssThemeDir, "components"), 0777), qt.IsNil)
b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), ` b.WithSourceFile(filepath.Join(scssThemeDir, "components", "_imports.scss"), `
@import "moo"; @import "moo";
@ -170,7 +170,7 @@ T1: {{ $r.Content }}
func TestResourceChain(t *testing.T) { func TestResourceChain(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
tests := []struct { tests := []struct {
name string name string
@ -203,7 +203,7 @@ T6: {{ $bundle1.Permalink }}
b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`) b.AssertFileContent("public/index.html", `T5 RelPermalink: /sass/styles3.css|`)
b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`) b.AssertFileContent("public/index.html", `T6: http://example.com/styles/bundle1.css`)
assert.False(b.CheckExists("public/styles/templ.min.css")) c.Assert(b.CheckExists("public/styles/templ.min.css"), qt.Equals, false)
b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`) b.AssertFileContent("public/styles/bundle1.css", `.home{color:blue}body{color:#333}`)
}}, }},
@ -353,10 +353,9 @@ Publish 2: {{ $cssPublish2.Permalink }}
"Publish 1: body{color:blue} /external1.min.css", "Publish 1: body{color:blue} /external1.min.css",
"Publish 2: http://example.com/external2.min.css", "Publish 2: http://example.com/external2.min.css",
) )
assert.True(b.CheckExists("public/external2.min.css"), "Referenced content should be copied to /public") c.Assert(b.CheckExists("public/external2.min.css"), qt.Equals, true)
assert.True(b.CheckExists("public/external1.min.css"), "Referenced content should be copied to /public") c.Assert(b.CheckExists("public/external1.min.css"), qt.Equals, true)
c.Assert(b.CheckExists("public/inline.min.css"), qt.Equals, false)
assert.False(b.CheckExists("public/inline.min.css"), "Inline content should not be copied to /public")
}}, }},
{"unmarshal", func() bool { return true }, func(b *sitesBuilder) { {"unmarshal", func() bool { return true }, func(b *sitesBuilder) {
@ -489,7 +488,7 @@ $color: #333;
func TestMultiSiteResource(t *testing.T) { func TestMultiSiteResource(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
b := newMultiSiteTestDefaultBuilder(t) b := newMultiSiteTestDefaultBuilder(t)
@ -497,8 +496,8 @@ func TestMultiSiteResource(t *testing.T) {
// This build is multilingual, but not multihost. There should be only one pipes.txt // This build is multilingual, but not multihost. There should be only one pipes.txt
b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/fr/index.html", "French Home Page", "String Resource: /blog/text/pipes.txt")
assert.False(b.CheckExists("public/fr/text/pipes.txt")) c.Assert(b.CheckExists("public/fr/text/pipes.txt"), qt.Equals, false)
assert.False(b.CheckExists("public/en/text/pipes.txt")) c.Assert(b.CheckExists("public/en/text/pipes.txt"), qt.Equals, false)
b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt") b.AssertFileContent("public/en/index.html", "Default Home Page", "String Resource: /blog/text/pipes.txt")
b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes") b.AssertFileContent("public/text/pipes.txt", "Hugo Pipes")

View file

@ -25,7 +25,7 @@ func TestRSSOutput(t *testing.T) {
t.Parallel() t.Parallel()
var ( var (
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
rssLimit := len(weightedSources) - 1 rssLimit := len(weightedSources) - 1

View file

@ -16,7 +16,6 @@ package hugolib
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"regexp"
"reflect" "reflect"
@ -31,7 +30,7 @@ import (
"github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/tpl"
"github.com/spf13/cast" "github.com/spf13/cast"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func CheckShortCodeMatch(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateHandler) error) { func CheckShortCodeMatch(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateHandler) error) {
@ -41,6 +40,7 @@ func CheckShortCodeMatch(t *testing.T, input, expected string, withTemplate func
func CheckShortCodeMatchAndError(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateHandler) error, expectError bool) { func CheckShortCodeMatchAndError(t *testing.T, input, expected string, withTemplate func(templ tpl.TemplateHandler) error, expectError bool) {
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
// Need some front matter, see https://github.com/gohugoio/hugo/issues/2337 // Need some front matter, see https://github.com/gohugoio/hugo/issues/2337
contentFile := `--- contentFile := `---
@ -62,9 +62,9 @@ title: "Title"
} }
h := b.H h := b.H
require.Len(t, h.Sites, 1) c.Assert(len(h.Sites), qt.Equals, 1)
require.Len(t, h.Sites[0].RegularPages(), 1) c.Assert(len(h.Sites[0].RegularPages()), qt.Equals, 1)
output := strings.TrimSpace(content(h.Sites[0].RegularPages()[0])) output := strings.TrimSpace(content(h.Sites[0].RegularPages()[0]))
output = strings.TrimPrefix(output, "<p>") output = strings.TrimPrefix(output, "<p>")
@ -358,8 +358,8 @@ title: "Shortcodes Galore!"
/*errCheck := func(s string) func(name string, assert *require.Assertions, shortcode *shortcode, err error) { /*errCheck := func(s string) func(name string, assert *require.Assertions, shortcode *shortcode, err error) {
return func(name string, assert *require.Assertions, shortcode *shortcode, err error) { return func(name string, assert *require.Assertions, shortcode *shortcode, err error) {
assert.Error(err, name) c.Assert(err, name, qt.Not(qt.IsNil))
assert.Equal(s, err.Error(), name) c.Assert(err.Error(), name, qt.Equals, s)
} }
}*/ }*/
@ -374,18 +374,18 @@ title: "Shortcodes Galore!"
s.name, s.isInline, s.isClosing, s.inner, s.params, s.ordinal, s.doMarkup, s.info.Config.Version, s.pos)) s.name, s.isInline, s.isClosing, s.inner, s.params, s.ordinal, s.doMarkup, s.info.Config.Version, s.pos))
} }
regexpCheck := func(re string) func(assert *require.Assertions, shortcode *shortcode, err error) { regexpCheck := func(re string) func(c *qt.C, shortcode *shortcode, err error) {
return func(assert *require.Assertions, shortcode *shortcode, err error) { return func(c *qt.C, shortcode *shortcode, err error) {
assert.NoError(err) c.Assert(err, qt.IsNil)
got := str(shortcode) c.Assert(str(shortcode), qt.Matches, ".*"+re+".*")
assert.Regexp(regexp.MustCompile(re), got, got)
} }
} }
for _, test := range []struct { for _, test := range []struct {
name string name string
input string input string
check func(assert *require.Assertions, shortcode *shortcode, err error) check func(c *qt.C, shortcode *shortcode, err error)
}{ }{
{"one shortcode, no markup", "{{< tag >}}", regexpCheck("tag.*closing:false.*markup:false")}, {"one shortcode, no markup", "{{< tag >}}", regexpCheck("tag.*closing:false.*markup:false")},
{"one shortcode, markup", "{{% tag %}}", regexpCheck("tag.*closing:false.*markup:true;version:2")}, {"one shortcode, markup", "{{% tag %}}", regexpCheck("tag.*closing:false.*markup:true;version:2")},
@ -411,7 +411,7 @@ title: "Shortcodes Galore!"
t.Run(test.name, func(t *testing.T) { t.Run(test.name, func(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
counter := 0 counter := 0
placeholderFunc := func() string { placeholderFunc := func() string {
@ -420,13 +420,13 @@ title: "Shortcodes Galore!"
} }
p, err := pageparser.ParseMain(strings.NewReader(test.input), pageparser.Config{}) p, err := pageparser.ParseMain(strings.NewReader(test.input), pageparser.Config{})
assert.NoError(err) c.Assert(err, qt.IsNil)
handler := newShortcodeHandler(nil, s, placeholderFunc) handler := newShortcodeHandler(nil, s, placeholderFunc)
iter := p.Iterator() iter := p.Iterator()
short, err := handler.extractShortcode(0, 0, iter) short, err := handler.extractShortcode(0, 0, iter)
test.check(assert, short, err) test.check(c, short, err)
}) })
} }
@ -582,7 +582,7 @@ title: "Foo"
t.Skip("Skip Rst test case as no rst2html present.") t.Skip("Skip Rst test case as no rst2html present.")
} }
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
expected := cast.ToStringSlice(test.expected) expected := cast.ToStringSlice(test.expected)
th.assertFileContent(filepath.FromSlash(test.outFile), expected...) th.assertFileContent(filepath.FromSlash(test.outFile), expected...)
@ -655,12 +655,12 @@ CSV: {{< myShort >}}
b.Build(BuildCfg{}) b.Build(BuildCfg{})
h := b.H h := b.H
require.Len(t, h.Sites, 1) b.Assert(len(h.Sites), qt.Equals, 1)
s := h.Sites[0] s := h.Sites[0]
home := s.getPage(page.KindHome) home := s.getPage(page.KindHome)
require.NotNil(t, home) b.Assert(home, qt.Not(qt.IsNil))
require.Len(t, home.OutputFormats(), 3) b.Assert(len(home.OutputFormats()), qt.Equals, 3)
b.AssertFileContent("public/index.html", b.AssertFileContent("public/index.html",
"Home HTML", "Home HTML",
@ -827,7 +827,6 @@ func TestReplaceShortcodeTokens(t *testing.T) {
func TestShortcodeGetContent(t *testing.T) { func TestShortcodeGetContent(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t)
contentShortcode := ` contentShortcode := `
{{- $t := .Get 0 -}} {{- $t := .Get 0 -}}
@ -878,7 +877,7 @@ C-%s`
builder.WithContent(content...).WithTemplates(templates...).CreateSites().Build(BuildCfg{}) builder.WithContent(content...).WithTemplates(templates...).CreateSites().Build(BuildCfg{})
s := builder.H.Sites[0] s := builder.H.Sites[0]
assert.Equal(3, len(s.RegularPages())) builder.Assert(len(s.RegularPages()), qt.Equals, 3)
builder.AssertFileContent("public/en/section1/index.html", builder.AssertFileContent("public/en/section1/index.html",
"List Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|", "List Content: <p>Logo:P1:|P2:logo.png/PNG logo|:P1: P1:|P2:docs1p1/<p>C-s1p1</p>\n|",
@ -958,7 +957,7 @@ SHORTCODE: {{< c >}}
func TestShortcodePreserveOrder(t *testing.T) { func TestShortcodePreserveOrder(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
contentTemplate := `--- contentTemplate := `---
title: doc%d title: doc%d
@ -1004,7 +1003,7 @@ weight: %d
builder.WithContent(content...).WithTemplatesAdded(shortcodes...).CreateSites().Build(BuildCfg{}) builder.WithContent(content...).WithTemplatesAdded(shortcodes...).CreateSites().Build(BuildCfg{})
s := builder.H.Sites[0] s := builder.H.Sites[0]
assert.Equal(3, len(s.RegularPages())) c.Assert(len(s.RegularPages()), qt.Equals, 3)
builder.AssertFileContent("public/en/p1/index.html", `v1: 0 sgo: |v2: 1 sgo: 0|v3: 2 sgo: 1|v4: 3 sgo: 2|v5: 4 sgo: 3`) builder.AssertFileContent("public/en/p1/index.html", `v1: 0 sgo: |v2: 1 sgo: 0|v3: 2 sgo: 1|v4: 3 sgo: 2|v5: 4 sgo: 3`)
builder.AssertFileContent("public/en/p1/index.html", `outer ordinal: 5 inner: builder.AssertFileContent("public/en/p1/index.html", `outer ordinal: 5 inner:
@ -1016,7 +1015,7 @@ ordinal: 4 scratch ordinal: 5 scratch get ordinal: 4`)
func TestShortcodeVariables(t *testing.T) { func TestShortcodeVariables(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder := newTestSitesBuilder(t).WithSimpleConfigFile()
@ -1041,7 +1040,7 @@ String: {{ . | safeHTML }}
`).CreateSites().Build(BuildCfg{}) `).CreateSites().Build(BuildCfg{})
s := builder.H.Sites[0] s := builder.H.Sites[0]
assert.Equal(1, len(s.RegularPages())) c.Assert(len(s.RegularPages()), qt.Equals, 1)
builder.AssertFileContent("public/page/index.html", builder.AssertFileContent("public/page/index.html",
filepath.FromSlash("File: content/page.md"), filepath.FromSlash("File: content/page.md"),
@ -1134,7 +1133,7 @@ CONTENT:{{ .Content }}
// https://github.com/gohugoio/hugo/issues/5863 // https://github.com/gohugoio/hugo/issues/5863
func TestShortcodeNamespaced(t *testing.T) { func TestShortcodeNamespaced(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
builder := newTestSitesBuilder(t).WithSimpleConfigFile() builder := newTestSitesBuilder(t).WithSimpleConfigFile()
@ -1152,7 +1151,7 @@ title: "Hugo Rocks!"
"layouts/shortcodes/test/hello.html", `test/hello`).CreateSites().Build(BuildCfg{}) "layouts/shortcodes/test/hello.html", `test/hello`).CreateSites().Build(BuildCfg{})
s := builder.H.Sites[0] s := builder.H.Sites[0]
assert.Equal(1, len(s.RegularPages())) c.Assert(len(s.RegularPages()), qt.Equals, 1)
builder.AssertFileContent("public/page/index.html", builder.AssertFileContent("public/page/index.html",
"hello: hello", "hello: hello",

View file

@ -20,6 +20,8 @@ import (
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
qt "github.com/frankban/quicktest"
) )
type siteBenchmarkTestcase struct { type siteBenchmarkTestcase struct {
@ -182,9 +184,9 @@ contentDir="content/sv"
}, },
func(s *sitesBuilder) { func(s *sitesBuilder) {
s.CheckExists("public/blog/mybundle/index.html") s.CheckExists("public/blog/mybundle/index.html")
s.Assertions.Equal(4, len(s.H.Sites)) s.Assert(len(s.H.Sites), qt.Equals, 4)
s.Assertions.Equal(len(s.H.Sites[0].RegularPages()), len(s.H.Sites[1].RegularPages())) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, len(s.H.Sites[1].RegularPages()))
s.Assertions.Equal(30, len(s.H.Sites[0].RegularPages())) s.Assert(len(s.H.Sites[0].RegularPages()), qt.Equals, 30)
}, },
}, },

View file

@ -17,12 +17,11 @@ import (
"strings" "strings"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/spf13/afero" "github.com/spf13/afero"
"github.com/stretchr/testify/require"
"fmt" "fmt"
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
@ -142,15 +141,15 @@ Len Pages: {{ .Kind }} {{ len .Site.RegularPages }} Page Number: {{ .Paginator.P
b.Build(BuildCfg{}) b.Build(BuildCfg{})
s := b.H.Sites[0] s := b.H.Sites[0]
require.Equal(t, "en", s.language.Lang) b.Assert(s.language.Lang, qt.Equals, "en")
home := s.getPage(page.KindHome) home := s.getPage(page.KindHome)
require.NotNil(t, home) b.Assert(home, qt.Not(qt.IsNil))
lenOut := len(outputs) lenOut := len(outputs)
require.Len(t, home.OutputFormats(), lenOut) b.Assert(len(home.OutputFormats()), qt.Equals, lenOut)
// There is currently always a JSON output to make it simpler ... // There is currently always a JSON output to make it simpler ...
altFormats := lenOut - 1 altFormats := lenOut - 1
@ -179,9 +178,8 @@ Len Pages: {{ .Kind }} {{ len .Site.RegularPages }} Page Number: {{ .Paginator.P
"OtherShort: <h1>Hi!</h1>", "OtherShort: <h1>Hi!</h1>",
"Len Pages: home 10", "Len Pages: home 10",
) )
assert := require.New(t)
b.AssertFileContent("public/page/2/index.html", "Page Number: 2") b.AssertFileContent("public/page/2/index.html", "Page Number: 2")
assert.False(b.CheckExists("public/page/2/index.json")) b.Assert(b.CheckExists("public/page/2/index.json"), qt.Equals, false)
b.AssertFileContent("public/nn/index.html", b.AssertFileContent("public/nn/index.html",
"List HTML|JSON Nynorsk Heim|", "List HTML|JSON Nynorsk Heim|",
@ -204,19 +202,19 @@ Len Pages: {{ .Kind }} {{ len .Site.RegularPages }} Page Number: {{ .Paginator.P
of := home.OutputFormats() of := home.OutputFormats()
json := of.Get("JSON") json := of.Get("JSON")
require.NotNil(t, json) b.Assert(json, qt.Not(qt.IsNil))
require.Equal(t, "/blog/index.json", json.RelPermalink()) b.Assert(json.RelPermalink(), qt.Equals, "/blog/index.json")
require.Equal(t, "http://example.com/blog/index.json", json.Permalink()) b.Assert(json.Permalink(), qt.Equals, "http://example.com/blog/index.json")
if helpers.InStringArray(outputs, "cal") { if helpers.InStringArray(outputs, "cal") {
cal := of.Get("calendar") cal := of.Get("calendar")
require.NotNil(t, cal) b.Assert(cal, qt.Not(qt.IsNil))
require.Equal(t, "/blog/index.ics", cal.RelPermalink()) b.Assert(cal.RelPermalink(), qt.Equals, "/blog/index.ics")
require.Equal(t, "webcal://example.com/blog/index.ics", cal.Permalink()) b.Assert(cal.Permalink(), qt.Equals, "webcal://example.com/blog/index.ics")
} }
require.True(t, home.HasShortcode("myShort")) b.Assert(home.HasShortcode("myShort"), qt.Equals, true)
require.False(t, home.HasShortcode("doesNotExist")) b.Assert(home.HasShortcode("doesNotExist"), qt.Equals, false)
} }
@ -237,6 +235,8 @@ baseName = "feed"
` `
c := qt.New(t)
mf := afero.NewMemMapFs() mf := afero.NewMemMapFs()
writeToFs(t, mf, "content/foo.html", `foo`) writeToFs(t, mf, "content/foo.html", `foo`)
@ -244,14 +244,14 @@ baseName = "feed"
err := h.Build(BuildCfg{}) err := h.Build(BuildCfg{})
require.NoError(t, err) c.Assert(err, qt.IsNil)
th.assertFileContent("public/feed.xml", "Recent content on") th.assertFileContent("public/feed.xml", "Recent content on")
s := h.Sites[0] s := h.Sites[0]
//Issue #3450 //Issue #3450
require.Equal(t, "http://example.com/blog/feed.xml", s.Info.RSSLink) c.Assert(s.Info.RSSLink, qt.Equals, "http://example.com/blog/feed.xml")
} }
@ -294,6 +294,8 @@ baseName = "customdelimbase"
` `
c := qt.New(t)
mf := afero.NewMemMapFs() mf := afero.NewMemMapFs()
writeToFs(t, mf, "content/foo.html", `foo`) writeToFs(t, mf, "content/foo.html", `foo`)
writeToFs(t, mf, "layouts/_default/list.dotless", `a dotless`) writeToFs(t, mf, "layouts/_default/list.dotless", `a dotless`)
@ -305,7 +307,7 @@ baseName = "customdelimbase"
err := h.Build(BuildCfg{}) err := h.Build(BuildCfg{})
require.NoError(t, err) c.Assert(err, qt.IsNil)
th.assertFileContent("public/_redirects", "a dotless") th.assertFileContent("public/_redirects", "a dotless")
th.assertFileContent("public/defaultdelimbase.defd", "default delimim") th.assertFileContent("public/defaultdelimbase.defd", "default delimim")
@ -315,21 +317,21 @@ baseName = "customdelimbase"
s := h.Sites[0] s := h.Sites[0]
home := s.getPage(page.KindHome) home := s.getPage(page.KindHome)
require.NotNil(t, home) c.Assert(home, qt.Not(qt.IsNil))
outputs := home.OutputFormats() outputs := home.OutputFormats()
require.Equal(t, "/blog/_redirects", outputs.Get("DOTLESS").RelPermalink()) c.Assert(outputs.Get("DOTLESS").RelPermalink(), qt.Equals, "/blog/_redirects")
require.Equal(t, "/blog/defaultdelimbase.defd", outputs.Get("DEF").RelPermalink()) c.Assert(outputs.Get("DEF").RelPermalink(), qt.Equals, "/blog/defaultdelimbase.defd")
require.Equal(t, "/blog/nosuffixbase", outputs.Get("NOS").RelPermalink()) c.Assert(outputs.Get("NOS").RelPermalink(), qt.Equals, "/blog/nosuffixbase")
require.Equal(t, "/blog/customdelimbase_del", outputs.Get("CUS").RelPermalink()) c.Assert(outputs.Get("CUS").RelPermalink(), qt.Equals, "/blog/customdelimbase_del")
} }
func TestCreateSiteOutputFormats(t *testing.T) { func TestCreateSiteOutputFormats(t *testing.T) {
t.Run("Basic", func(t *testing.T) { t.Run("Basic", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
outputsConfig := map[string]interface{}{ outputsConfig := map[string]interface{}{
page.KindHome: []string{"HTML", "JSON"}, page.KindHome: []string{"HTML", "JSON"},
@ -340,28 +342,28 @@ func TestCreateSiteOutputFormats(t *testing.T) {
cfg.Set("outputs", outputsConfig) cfg.Set("outputs", outputsConfig)
outputs, err := createSiteOutputFormats(output.DefaultFormats, cfg) outputs, err := createSiteOutputFormats(output.DefaultFormats, cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(output.Formats{output.JSONFormat}, outputs[page.KindSection]) c.Assert(outputs[page.KindSection], deepEqualsOutputFormats, output.Formats{output.JSONFormat})
assert.Equal(output.Formats{output.HTMLFormat, output.JSONFormat}, outputs[page.KindHome]) c.Assert(outputs[page.KindHome], deepEqualsOutputFormats, output.Formats{output.HTMLFormat, output.JSONFormat})
// Defaults // Defaults
assert.Equal(output.Formats{output.HTMLFormat, output.RSSFormat}, outputs[page.KindTaxonomy]) c.Assert(outputs[page.KindTaxonomy], deepEqualsOutputFormats, output.Formats{output.HTMLFormat, output.RSSFormat})
assert.Equal(output.Formats{output.HTMLFormat, output.RSSFormat}, outputs[page.KindTaxonomyTerm]) c.Assert(outputs[page.KindTaxonomyTerm], deepEqualsOutputFormats, output.Formats{output.HTMLFormat, output.RSSFormat})
assert.Equal(output.Formats{output.HTMLFormat}, outputs[page.KindPage]) c.Assert(outputs[page.KindPage], deepEqualsOutputFormats, output.Formats{output.HTMLFormat})
// These aren't (currently) in use when rendering in Hugo, // These aren't (currently) in use when rendering in Hugo,
// but the pages needs to be assigned an output format, // but the pages needs to be assigned an output format,
// so these should also be correct/sensible. // so these should also be correct/sensible.
assert.Equal(output.Formats{output.RSSFormat}, outputs[kindRSS]) c.Assert(outputs[kindRSS], deepEqualsOutputFormats, output.Formats{output.RSSFormat})
assert.Equal(output.Formats{output.SitemapFormat}, outputs[kindSitemap]) c.Assert(outputs[kindSitemap], deepEqualsOutputFormats, output.Formats{output.SitemapFormat})
assert.Equal(output.Formats{output.RobotsTxtFormat}, outputs[kindRobotsTXT]) c.Assert(outputs[kindRobotsTXT], deepEqualsOutputFormats, output.Formats{output.RobotsTxtFormat})
assert.Equal(output.Formats{output.HTMLFormat}, outputs[kind404]) c.Assert(outputs[kind404], deepEqualsOutputFormats, output.Formats{output.HTMLFormat})
}) })
// Issue #4528 // Issue #4528
t.Run("Mixed case", func(t *testing.T) { t.Run("Mixed case", func(t *testing.T) {
assert := require.New(t) c := qt.New(t)
cfg := viper.New() cfg := viper.New()
outputsConfig := map[string]interface{}{ outputsConfig := map[string]interface{}{
@ -370,15 +372,15 @@ func TestCreateSiteOutputFormats(t *testing.T) {
cfg.Set("outputs", outputsConfig) cfg.Set("outputs", outputsConfig)
outputs, err := createSiteOutputFormats(output.DefaultFormats, cfg) outputs, err := createSiteOutputFormats(output.DefaultFormats, cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(output.Formats{output.JSONFormat}, outputs[page.KindTaxonomyTerm]) c.Assert(outputs[page.KindTaxonomyTerm], deepEqualsOutputFormats, output.Formats{output.JSONFormat})
}) })
} }
func TestCreateSiteOutputFormatsInvalidConfig(t *testing.T) { func TestCreateSiteOutputFormatsInvalidConfig(t *testing.T) {
assert := require.New(t) c := qt.New(t)
outputsConfig := map[string]interface{}{ outputsConfig := map[string]interface{}{
page.KindHome: []string{"FOO", "JSON"}, page.KindHome: []string{"FOO", "JSON"},
@ -388,11 +390,11 @@ func TestCreateSiteOutputFormatsInvalidConfig(t *testing.T) {
cfg.Set("outputs", outputsConfig) cfg.Set("outputs", outputsConfig)
_, err := createSiteOutputFormats(output.DefaultFormats, cfg) _, err := createSiteOutputFormats(output.DefaultFormats, cfg)
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
} }
func TestCreateSiteOutputFormatsEmptyConfig(t *testing.T) { func TestCreateSiteOutputFormatsEmptyConfig(t *testing.T) {
assert := require.New(t) c := qt.New(t)
outputsConfig := map[string]interface{}{ outputsConfig := map[string]interface{}{
page.KindHome: []string{}, page.KindHome: []string{},
@ -402,12 +404,12 @@ func TestCreateSiteOutputFormatsEmptyConfig(t *testing.T) {
cfg.Set("outputs", outputsConfig) cfg.Set("outputs", outputsConfig)
outputs, err := createSiteOutputFormats(output.DefaultFormats, cfg) outputs, err := createSiteOutputFormats(output.DefaultFormats, cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(output.Formats{output.HTMLFormat, output.RSSFormat}, outputs[page.KindHome]) c.Assert(outputs[page.KindHome], deepEqualsOutputFormats, output.Formats{output.HTMLFormat, output.RSSFormat})
} }
func TestCreateSiteOutputFormatsCustomFormats(t *testing.T) { func TestCreateSiteOutputFormatsCustomFormats(t *testing.T) {
assert := require.New(t) c := qt.New(t)
outputsConfig := map[string]interface{}{ outputsConfig := map[string]interface{}{
page.KindHome: []string{}, page.KindHome: []string{},
@ -422,8 +424,8 @@ func TestCreateSiteOutputFormatsCustomFormats(t *testing.T) {
) )
outputs, err := createSiteOutputFormats(output.Formats{customRSS, customHTML}, cfg) outputs, err := createSiteOutputFormats(output.Formats{customRSS, customHTML}, cfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.Equal(output.Formats{customHTML, customRSS}, outputs[page.KindHome]) c.Assert(outputs[page.KindHome], deepEqualsOutputFormats, output.Formats{customHTML, customRSS})
} }
// https://github.com/gohugoio/hugo/issues/5849 // https://github.com/gohugoio/hugo/issues/5849

View file

@ -19,17 +19,17 @@ import (
"strings" "strings"
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/stretchr/testify/require"
) )
func TestNestedSections(t *testing.T) { func TestNestedSections(t *testing.T) {
var ( var (
assert = require.New(t) c = qt.New(t)
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
) )
cfg.Set("permalinks", map[string]string{ cfg.Set("permalinks", map[string]string{
@ -117,179 +117,179 @@ PAG|{{ .Title }}|{{ $sect.InSection . }}
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
require.Len(t, s.RegularPages(), 21) c.Assert(len(s.RegularPages()), qt.Equals, 21)
tests := []struct { tests := []struct {
sections string sections string
verify func(assert *require.Assertions, p page.Page) verify func(c *qt.C, p page.Page)
}{ }{
{"elsewhere", func(assert *require.Assertions, p page.Page) { {"elsewhere", func(c *qt.C, p page.Page) {
assert.Len(p.Pages(), 1) c.Assert(len(p.Pages()), qt.Equals, 1)
for _, p := range p.Pages() { for _, p := range p.Pages() {
assert.Equal("elsewhere", p.SectionsPath()) c.Assert(p.SectionsPath(), qt.Equals, "elsewhere")
} }
}}, }},
{"post", func(assert *require.Assertions, p page.Page) { {"post", func(c *qt.C, p page.Page) {
assert.Len(p.Pages(), 2) c.Assert(len(p.Pages()), qt.Equals, 2)
for _, p := range p.Pages() { for _, p := range p.Pages() {
assert.Equal("post", p.Section()) c.Assert(p.Section(), qt.Equals, "post")
} }
}}, }},
{"empty1", func(assert *require.Assertions, p page.Page) { {"empty1", func(c *qt.C, p page.Page) {
// > b,c // > b,c
assert.Nil(getPage(p, "/empty1/b")) // No _index.md page. c.Assert(getPage(p, "/empty1/b"), qt.IsNil) // No _index.md page.
assert.NotNil(getPage(p, "/empty1/b/c")) c.Assert(getPage(p, "/empty1/b/c"), qt.Not(qt.IsNil))
}}, }},
{"empty2", func(assert *require.Assertions, p page.Page) { {"empty2", func(c *qt.C, p page.Page) {
// > b,c,d where b and d have _index.md files. // > b,c,d where b and d have _index.md files.
b := getPage(p, "/empty2/b") b := getPage(p, "/empty2/b")
assert.NotNil(b) c.Assert(b, qt.Not(qt.IsNil))
assert.Equal("T40_-1", b.Title()) c.Assert(b.Title(), qt.Equals, "T40_-1")
c := getPage(p, "/empty2/b/c") cp := getPage(p, "/empty2/b/c")
assert.Nil(c) // No _index.md c.Assert(cp, qt.IsNil) // No _index.md
d := getPage(p, "/empty2/b/c/d") d := getPage(p, "/empty2/b/c/d")
assert.NotNil(d) c.Assert(d, qt.Not(qt.IsNil))
assert.Equal("T41_-1", d.Title()) c.Assert(d.Title(), qt.Equals, "T41_-1")
assert.False(c.Eq(d)) c.Assert(cp.Eq(d), qt.Equals, false)
assert.True(c.Eq(c)) c.Assert(cp.Eq(cp), qt.Equals, true)
assert.False(c.Eq("asdf")) c.Assert(cp.Eq("asdf"), qt.Equals, false)
}}, }},
{"empty3", func(assert *require.Assertions, p page.Page) { {"empty3", func(c *qt.C, p page.Page) {
// b,c,d with regular page in b // b,c,d with regular page in b
b := getPage(p, "/empty3/b") b := getPage(p, "/empty3/b")
assert.Nil(b) // No _index.md c.Assert(b, qt.IsNil) // No _index.md
e3 := getPage(p, "/empty3/b/empty3") e3 := getPage(p, "/empty3/b/empty3")
assert.NotNil(e3) c.Assert(e3, qt.Not(qt.IsNil))
assert.Equal("empty3.md", e3.File().LogicalName()) c.Assert(e3.File().LogicalName(), qt.Equals, "empty3.md")
}}, }},
{"empty3", func(assert *require.Assertions, p page.Page) { {"empty3", func(c *qt.C, p page.Page) {
xxx := getPage(p, "/empty3/nil") xxx := getPage(p, "/empty3/nil")
assert.Nil(xxx) c.Assert(xxx, qt.IsNil)
}}, }},
{"top", func(assert *require.Assertions, p page.Page) { {"top", func(c *qt.C, p page.Page) {
assert.Equal("Tops", p.Title()) c.Assert(p.Title(), qt.Equals, "Tops")
assert.Len(p.Pages(), 2) c.Assert(len(p.Pages()), qt.Equals, 2)
assert.Equal("mypage2.md", p.Pages()[0].File().LogicalName()) c.Assert(p.Pages()[0].File().LogicalName(), qt.Equals, "mypage2.md")
assert.Equal("mypage3.md", p.Pages()[1].File().LogicalName()) c.Assert(p.Pages()[1].File().LogicalName(), qt.Equals, "mypage3.md")
home := p.Parent() home := p.Parent()
assert.True(home.IsHome()) c.Assert(home.IsHome(), qt.Equals, true)
assert.Len(p.Sections(), 0) c.Assert(len(p.Sections()), qt.Equals, 0)
assert.Equal(home, home.CurrentSection()) c.Assert(home.CurrentSection(), qt.Equals, home)
active, err := home.InSection(home) active, err := home.InSection(home)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.True(active) c.Assert(active, qt.Equals, true)
assert.Equal(p, p.FirstSection()) c.Assert(p.FirstSection(), qt.Equals, p)
}}, }},
{"l1", func(assert *require.Assertions, p page.Page) { {"l1", func(c *qt.C, p page.Page) {
assert.Equal("L1s", p.Title()) c.Assert(p.Title(), qt.Equals, "L1s")
assert.Len(p.Pages(), 4) // 2 pages + 2 sections c.Assert(len(p.Pages()), qt.Equals, 4) // 2 pages + 2 sections
assert.True(p.Parent().IsHome()) c.Assert(p.Parent().IsHome(), qt.Equals, true)
assert.Len(p.Sections(), 2) c.Assert(len(p.Sections()), qt.Equals, 2)
}}, }},
{"l1,l2", func(assert *require.Assertions, p page.Page) { {"l1,l2", func(c *qt.C, p page.Page) {
assert.Equal("T2_-1", p.Title()) c.Assert(p.Title(), qt.Equals, "T2_-1")
assert.Len(p.Pages(), 4) // 3 pages + 1 section c.Assert(len(p.Pages()), qt.Equals, 4) // 3 pages + 1 section
assert.Equal(p, p.Pages()[0].Parent()) c.Assert(p.Pages()[0].Parent(), qt.Equals, p)
assert.Equal("L1s", p.Parent().Title()) c.Assert(p.Parent().Title(), qt.Equals, "L1s")
assert.Equal("/l1/l2/", p.RelPermalink()) c.Assert(p.RelPermalink(), qt.Equals, "/l1/l2/")
assert.Len(p.Sections(), 1) c.Assert(len(p.Sections()), qt.Equals, 1)
for _, child := range p.Pages() { for _, child := range p.Pages() {
if child.IsSection() { if child.IsSection() {
assert.Equal(child, child.CurrentSection()) c.Assert(child.CurrentSection(), qt.Equals, child)
continue continue
} }
assert.Equal(p, child.CurrentSection()) c.Assert(child.CurrentSection(), qt.Equals, p)
active, err := child.InSection(p) active, err := child.InSection(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.True(active) c.Assert(active, qt.Equals, true)
active, err = p.InSection(child) active, err = p.InSection(child)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.True(active) c.Assert(active, qt.Equals, true)
active, err = p.InSection(getPage(p, "/")) active, err = p.InSection(getPage(p, "/"))
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(active) c.Assert(active, qt.Equals, false)
isAncestor, err := p.IsAncestor(child) isAncestor, err := p.IsAncestor(child)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.True(isAncestor) c.Assert(isAncestor, qt.Equals, true)
isAncestor, err = child.IsAncestor(p) isAncestor, err = child.IsAncestor(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isAncestor) c.Assert(isAncestor, qt.Equals, false)
isDescendant, err := p.IsDescendant(child) isDescendant, err := p.IsDescendant(child)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isDescendant) c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = child.IsDescendant(p) isDescendant, err = child.IsDescendant(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.True(isDescendant) c.Assert(isDescendant, qt.Equals, true)
} }
assert.True(p.Eq(p.CurrentSection())) c.Assert(p.Eq(p.CurrentSection()), qt.Equals, true)
}}, }},
{"l1,l2_2", func(assert *require.Assertions, p page.Page) { {"l1,l2_2", func(c *qt.C, p page.Page) {
assert.Equal("T22_-1", p.Title()) c.Assert(p.Title(), qt.Equals, "T22_-1")
assert.Len(p.Pages(), 2) c.Assert(len(p.Pages()), qt.Equals, 2)
assert.Equal(filepath.FromSlash("l1/l2_2/page_2_2_1.md"), p.Pages()[0].File().Path()) c.Assert(p.Pages()[0].File().Path(), qt.Equals, filepath.FromSlash("l1/l2_2/page_2_2_1.md"))
assert.Equal("L1s", p.Parent().Title()) c.Assert(p.Parent().Title(), qt.Equals, "L1s")
assert.Len(p.Sections(), 0) c.Assert(len(p.Sections()), qt.Equals, 0)
}}, }},
{"l1,l2,l3", func(assert *require.Assertions, p page.Page) { {"l1,l2,l3", func(c *qt.C, p page.Page) {
nilp, _ := p.GetPage("this/does/not/exist") nilp, _ := p.GetPage("this/does/not/exist")
assert.Equal("T3_-1", p.Title()) c.Assert(p.Title(), qt.Equals, "T3_-1")
assert.Len(p.Pages(), 2) c.Assert(len(p.Pages()), qt.Equals, 2)
assert.Equal("T2_-1", p.Parent().Title()) c.Assert(p.Parent().Title(), qt.Equals, "T2_-1")
assert.Len(p.Sections(), 0) c.Assert(len(p.Sections()), qt.Equals, 0)
l1 := getPage(p, "/l1") l1 := getPage(p, "/l1")
isDescendant, err := l1.IsDescendant(p) isDescendant, err := l1.IsDescendant(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isDescendant) c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = l1.IsDescendant(nil) isDescendant, err = l1.IsDescendant(nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isDescendant) c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = nilp.IsDescendant(p) isDescendant, err = nilp.IsDescendant(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isDescendant) c.Assert(isDescendant, qt.Equals, false)
isDescendant, err = p.IsDescendant(l1) isDescendant, err = p.IsDescendant(l1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.True(isDescendant) c.Assert(isDescendant, qt.Equals, true)
isAncestor, err := l1.IsAncestor(p) isAncestor, err := l1.IsAncestor(p)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.True(isAncestor) c.Assert(isAncestor, qt.Equals, true)
isAncestor, err = p.IsAncestor(l1) isAncestor, err = p.IsAncestor(l1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isAncestor) c.Assert(isAncestor, qt.Equals, false)
assert.Equal(l1, p.FirstSection()) c.Assert(p.FirstSection(), qt.Equals, l1)
isAncestor, err = p.IsAncestor(nil) isAncestor, err = p.IsAncestor(nil)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isAncestor) c.Assert(isAncestor, qt.Equals, false)
isAncestor, err = nilp.IsAncestor(l1) isAncestor, err = nilp.IsAncestor(l1)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.False(isAncestor) c.Assert(isAncestor, qt.Equals, false)
}}, }},
{"perm a,link", func(assert *require.Assertions, p page.Page) { {"perm a,link", func(c *qt.C, p page.Page) {
assert.Equal("T9_-1", p.Title()) c.Assert(p.Title(), qt.Equals, "T9_-1")
assert.Equal("/perm-a/link/", p.RelPermalink()) c.Assert(p.RelPermalink(), qt.Equals, "/perm-a/link/")
assert.Len(p.Pages(), 4) c.Assert(len(p.Pages()), qt.Equals, 4)
first := p.Pages()[0] first := p.Pages()[0]
assert.Equal("/perm-a/link/t1_1/", first.RelPermalink()) c.Assert(first.RelPermalink(), qt.Equals, "/perm-a/link/t1_1/")
th.assertFileContent("public/perm-a/link/t1_1/index.html", "Single|T1_1") th.assertFileContent("public/perm-a/link/t1_1/index.html", "Single|T1_1")
last := p.Pages()[3] last := p.Pages()[3]
assert.Equal("/perm-a/link/t1_5/", last.RelPermalink()) c.Assert(last.RelPermalink(), qt.Equals, "/perm-a/link/t1_5/")
}}, }},
} }
@ -300,27 +300,27 @@ PAG|{{ .Title }}|{{ $sect.InSection . }}
test := test test := test
t.Run(fmt.Sprintf("sections %s", test.sections), func(t *testing.T) { t.Run(fmt.Sprintf("sections %s", test.sections), func(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
sections := strings.Split(test.sections, ",") sections := strings.Split(test.sections, ",")
p := s.getPage(page.KindSection, sections...) p := s.getPage(page.KindSection, sections...)
assert.NotNil(p, fmt.Sprint(sections)) c.Assert(p, qt.Not(qt.IsNil))
if p.Pages() != nil { if p.Pages() != nil {
assert.Equal(p.Pages(), p.Data().(page.Data).Pages()) c.Assert(p.Data().(page.Data).Pages(), deepEqualsPages, p.Pages())
} }
assert.NotNil(p.Parent(), fmt.Sprintf("Parent nil: %q", test.sections)) c.Assert(p.Parent(), qt.Not(qt.IsNil))
test.verify(assert, p) test.verify(c, p)
}) })
} }
assert.NotNil(home) c.Assert(home, qt.Not(qt.IsNil))
assert.Len(home.Sections(), 9) c.Assert(len(home.Sections()), qt.Equals, 9)
assert.Equal(home.Sections(), s.Info.Sections()) c.Assert(s.Info.Sections(), deepEqualsPages, home.Sections())
rootPage := s.getPage(page.KindPage, "mypage.md") rootPage := s.getPage(page.KindPage, "mypage.md")
assert.NotNil(rootPage) c.Assert(rootPage, qt.Not(qt.IsNil))
assert.True(rootPage.Parent().IsHome()) c.Assert(rootPage.Parent().IsHome(), qt.Equals, true)
// Add a odd test for this as this looks a little bit off, but I'm not in the mood // Add a odd test for this as this looks a little bit off, but I'm not in the mood
// to think too hard a out this right now. It works, but people will have to spell // to think too hard a out this right now. It works, but people will have to spell
@ -329,8 +329,8 @@ PAG|{{ .Title }}|{{ $sect.InSection . }}
// getPage. // getPage.
// TODO(bep) // TODO(bep)
sectionWithSpace := s.getPage(page.KindSection, "Spaces in Section") sectionWithSpace := s.getPage(page.KindSection, "Spaces in Section")
require.NotNil(t, sectionWithSpace) c.Assert(sectionWithSpace, qt.Not(qt.IsNil))
require.Equal(t, "/spaces-in-section/", sectionWithSpace.RelPermalink()) c.Assert(sectionWithSpace.RelPermalink(), qt.Equals, "/spaces-in-section/")
th.assertFileContent("public/l1/l2/page/2/index.html", "L1/l2-IsActive: true", "PAG|T2_3|true") th.assertFileContent("public/l1/l2/page/2/index.html", "L1/l2-IsActive: true", "PAG|T2_3|true")

View file

@ -21,13 +21,13 @@ import (
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
func TestSiteStats(t *testing.T) { func TestSiteStats(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
siteConfig := ` siteConfig := `
baseURL = "http://example.com/blog" baseURL = "http://example.com/blog"
@ -93,6 +93,6 @@ aliases: [/Ali%d]
helpers.ProcessingStatsTable(&buff, stats...) helpers.ProcessingStatsTable(&buff, stats...)
assert.Contains(buff.String(), "Pages | 19 | 6") c.Assert(buff.String(), qt.Contains, "Pages | 19 | 6")
} }

View file

@ -24,10 +24,9 @@ import (
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
const ( const (
@ -145,6 +144,7 @@ func TestLastChange(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "sect/doc1.md"), "---\ntitle: doc1\nweight: 1\ndate: 2014-05-29\n---\n# doc1\n*some content*") writeSource(t, fs, filepath.Join("content", "sect/doc1.md"), "---\ntitle: doc1\nweight: 1\ndate: 2014-05-29\n---\n# doc1\n*some content*")
writeSource(t, fs, filepath.Join("content", "sect/doc2.md"), "---\ntitle: doc2\nweight: 2\ndate: 2015-05-29\n---\n# doc2\n*some content*") writeSource(t, fs, filepath.Join("content", "sect/doc2.md"), "---\ntitle: doc2\nweight: 2\ndate: 2015-05-29\n---\n# doc2\n*some content*")
@ -154,8 +154,8 @@ func TestLastChange(t *testing.T) {
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.False(t, s.Info.LastChange().IsZero(), "Site.LastChange is zero") c.Assert(s.Info.LastChange().IsZero(), qt.Equals, false)
require.Equal(t, 2017, s.Info.LastChange().Year(), "Site.LastChange should be set to the page with latest Lastmod (year 2017)") c.Assert(s.Info.LastChange().Year(), qt.Equals, 2017)
} }
// Issue #_index // Issue #_index
@ -163,12 +163,13 @@ func TestPageWithUnderScoreIndexInFilename(t *testing.T) {
t.Parallel() t.Parallel()
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
writeSource(t, fs, filepath.Join("content", "sect/my_index_file.md"), "---\ntitle: doc1\nweight: 1\ndate: 2014-05-29\n---\n# doc1\n*some content*") writeSource(t, fs, filepath.Join("content", "sect/my_index_file.md"), "---\ntitle: doc1\nweight: 1\ndate: 2014-05-29\n---\n# doc1\n*some content*")
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
require.Len(t, s.RegularPages(), 1) c.Assert(len(s.RegularPages()), qt.Equals, 1)
} }
@ -184,6 +185,8 @@ func TestCrossrefs(t *testing.T) {
func doTestCrossrefs(t *testing.T, relative, uglyURLs bool) { func doTestCrossrefs(t *testing.T, relative, uglyURLs bool) {
c := qt.New(t)
baseURL := "http://foo/bar" baseURL := "http://foo/bar"
var refShortcode string var refShortcode string
@ -253,9 +256,9 @@ THE END.`, refShortcode),
WithTemplate: createWithTemplateFromNameValues("_default/single.html", "{{.Content}}")}, WithTemplate: createWithTemplateFromNameValues("_default/single.html", "{{.Content}}")},
BuildCfg{}) BuildCfg{})
require.Len(t, s.RegularPages(), 4) c.Assert(len(s.RegularPages()), qt.Equals, 4)
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
tests := []struct { tests := []struct {
doc string doc string
@ -286,6 +289,7 @@ func TestShouldAlwaysHaveUglyURLs(t *testing.T) {
func doTestShouldAlwaysHaveUglyURLs(t *testing.T, uglyURLs bool) { func doTestShouldAlwaysHaveUglyURLs(t *testing.T, uglyURLs bool) {
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
c := qt.New(t)
cfg.Set("verbose", true) cfg.Set("verbose", true)
cfg.Set("baseURL", "http://auth/bub") cfg.Set("baseURL", "http://auth/bub")
@ -333,7 +337,7 @@ func doTestShouldAlwaysHaveUglyURLs(t *testing.T, uglyURLs bool) {
} }
for _, p := range s.RegularPages() { for _, p := range s.RegularPages() {
assert.False(t, p.IsHome()) c.Assert(p.IsHome(), qt.Equals, false)
} }
for _, test := range tests { for _, test := range tests {
@ -355,7 +359,7 @@ func TestShouldNotWriteZeroLengthFilesToDestination(t *testing.T) {
writeSource(t, fs, filepath.Join("layouts", "_default/list.html"), "") writeSource(t, fs, filepath.Join("layouts", "_default/list.html"), "")
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
th.assertFileNotExist(filepath.Join("public", "index.html")) th.assertFileNotExist(filepath.Join("public", "index.html"))
} }
@ -378,6 +382,7 @@ func TestSectionNaming(t *testing.T) {
} }
func doTestSectionNaming(t *testing.T, canonify, uglify, pluralize bool) { func doTestSectionNaming(t *testing.T, canonify, uglify, pluralize bool) {
c := qt.New(t)
var expectedPathSuffix string var expectedPathSuffix string
@ -412,10 +417,10 @@ func doTestSectionNaming(t *testing.T, canonify, uglify, pluralize bool) {
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
mainSections, err := s.Info.Param("mainSections") mainSections, err := s.Info.Param("mainSections")
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.Equal(t, []string{"sect"}, mainSections) c.Assert(mainSections, qt.DeepEquals, []string{"sect"})
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
tests := []struct { tests := []struct {
doc string doc string
pluralAware bool pluralAware bool
@ -527,7 +532,7 @@ func TestAbsURLify(t *testing.T) {
writeSource(t, fs, filepath.Join("layouts", "blue/single.html"), templateWithURLAbs) writeSource(t, fs, filepath.Join("layouts", "blue/single.html"), templateWithURLAbs)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
tests := []struct { tests := []struct {
file, expected string file, expected string

View file

@ -22,8 +22,8 @@ import (
"html/template" "html/template"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/stretchr/testify/require"
) )
const slugDoc1 = "---\ntitle: slug doc 1\nslug: slug-doc-1\naliases:\n - /sd1/foo/\n - /sd2\n - /sd3/\n - /sd4.html\n---\nslug doc 1 content\n" const slugDoc1 = "---\ntitle: slug doc 1\nslug: slug-doc-1\naliases:\n - /sd1/foo/\n - /sd2\n - /sd3/\n - /sd4.html\n---\nslug doc 1 content\n"
@ -43,6 +43,8 @@ var urlFakeSource = [][2]string{
// Issue #1105 // Issue #1105
func TestShouldNotAddTrailingSlashToBaseURL(t *testing.T) { func TestShouldNotAddTrailingSlashToBaseURL(t *testing.T) {
t.Parallel() t.Parallel()
c := qt.New(t)
for i, this := range []struct { for i, this := range []struct {
in string in string
expected string expected string
@ -56,8 +58,8 @@ func TestShouldNotAddTrailingSlashToBaseURL(t *testing.T) {
cfg.Set("baseURL", this.in) cfg.Set("baseURL", this.in)
d := deps.DepsCfg{Cfg: cfg, Fs: fs} d := deps.DepsCfg{Cfg: cfg, Fs: fs}
s, err := NewSiteForCfg(d) s, err := NewSiteForCfg(d)
require.NoError(t, err) c.Assert(err, qt.IsNil)
require.NoError(t, s.initializeSiteInfo()) c.Assert(s.initializeSiteInfo(), qt.IsNil)
if s.Info.BaseURL() != template.URL(this.expected) { if s.Info.BaseURL() != template.URL(this.expected) {
t.Errorf("[%d] got %s expected %s", i, s.Info.BaseURL(), this.expected) t.Errorf("[%d] got %s expected %s", i, s.Info.BaseURL(), this.expected)
@ -94,7 +96,7 @@ func TestPageCount(t *testing.T) {
func TestUglyURLsPerSection(t *testing.T) { func TestUglyURLsPerSection(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
const dt = `--- const dt = `---
title: Do not go gentle into that good night title: Do not go gentle into that good night
@ -117,23 +119,23 @@ Do not go gentle into that good night.
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{SkipRender: true})
assert.Len(s.RegularPages(), 2) c.Assert(len(s.RegularPages()), qt.Equals, 2)
notUgly := s.getPage(page.KindPage, "sect1/p1.md") notUgly := s.getPage(page.KindPage, "sect1/p1.md")
assert.NotNil(notUgly) c.Assert(notUgly, qt.Not(qt.IsNil))
assert.Equal("sect1", notUgly.Section()) c.Assert(notUgly.Section(), qt.Equals, "sect1")
assert.Equal("/sect1/p1/", notUgly.RelPermalink()) c.Assert(notUgly.RelPermalink(), qt.Equals, "/sect1/p1/")
ugly := s.getPage(page.KindPage, "sect2/p2.md") ugly := s.getPage(page.KindPage, "sect2/p2.md")
assert.NotNil(ugly) c.Assert(ugly, qt.Not(qt.IsNil))
assert.Equal("sect2", ugly.Section()) c.Assert(ugly.Section(), qt.Equals, "sect2")
assert.Equal("/sect2/p2.html", ugly.RelPermalink()) c.Assert(ugly.RelPermalink(), qt.Equals, "/sect2/p2.html")
} }
func TestSectionWithURLInFrontMatter(t *testing.T) { func TestSectionWithURLInFrontMatter(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t) c := qt.New(t)
const st = `--- const st = `---
title: Do not go gentle into that good night title: Do not go gentle into that good night
@ -157,7 +159,7 @@ Do not go gentle into that good night.
` `
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
th := testHelper{cfg, fs, t} th := newTestHelper(cfg, fs, t)
cfg.Set("paginate", 1) cfg.Set("paginate", 1)
@ -175,11 +177,11 @@ Do not go gentle into that good night.
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
assert.Len(s.RegularPages(), 10) c.Assert(len(s.RegularPages()), qt.Equals, 10)
sect1 := s.getPage(page.KindSection, "sect1") sect1 := s.getPage(page.KindSection, "sect1")
assert.NotNil(sect1) c.Assert(sect1, qt.Not(qt.IsNil))
assert.Equal("/ss1/", sect1.RelPermalink()) c.Assert(sect1.RelPermalink(), qt.Equals, "/ss1/")
th.assertFileContent(filepath.Join("public", "ss1", "index.html"), "P1|URL: /ss1/|Next: /ss1/page/2/") th.assertFileContent(filepath.Join("public", "ss1", "index.html"), "P1|URL: /ss1/|Next: /ss1/page/2/")
th.assertFileContent(filepath.Join("public", "ss1", "page", "2", "index.html"), "P2|URL: /ss1/page/2/|Next: /ss1/page/3/") th.assertFileContent(filepath.Join("public", "ss1", "page", "2", "index.html"), "P2|URL: /ss1/page/2/|Next: /ss1/page/3/")

View file

@ -18,10 +18,10 @@ import (
"reflect" "reflect"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/tpl" "github.com/gohugoio/hugo/tpl"
"github.com/stretchr/testify/require"
) )
const sitemapTemplate = `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> const sitemapTemplate = `<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@ -44,6 +44,7 @@ func TestSitemapOutput(t *testing.T) {
func doTestSitemapOutput(t *testing.T, internal bool) { func doTestSitemapOutput(t *testing.T, internal bool) {
c := qt.New(t)
cfg, fs := newTestCfg() cfg, fs := newTestCfg()
cfg.Set("baseURL", "http://auth/bub/") cfg.Set("baseURL", "http://auth/bub/")
@ -63,7 +64,7 @@ func doTestSitemapOutput(t *testing.T, internal bool) {
writeSourcesToSource(t, "content", fs, weightedSources...) writeSourcesToSource(t, "content", fs, weightedSources...)
s := buildSingleSite(t, depsCfg, BuildCfg{}) s := buildSingleSite(t, depsCfg, BuildCfg{})
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
outputSitemap := "public/sitemap.xml" outputSitemap := "public/sitemap.xml"
th.assertFileContent(outputSitemap, th.assertFileContent(outputSitemap,
@ -79,8 +80,8 @@ func doTestSitemapOutput(t *testing.T, internal bool) {
"<loc>http://auth/bub/categories/hugo/</loc>", "<loc>http://auth/bub/categories/hugo/</loc>",
) )
content := readDestination(th.T, th.Fs, outputSitemap) content := readDestination(th, th.Fs, outputSitemap)
require.NotContains(t, content, "404") c.Assert(content, qt.Not(qt.Contains), "404")
} }

View file

@ -23,7 +23,7 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
) )
@ -167,37 +167,37 @@ permalinkeds:
for taxonomy, count := range taxonomyTermPageCounts { for taxonomy, count := range taxonomyTermPageCounts {
term := s.getPage(page.KindTaxonomyTerm, taxonomy) term := s.getPage(page.KindTaxonomyTerm, taxonomy)
require.NotNil(t, term) b.Assert(term, qt.Not(qt.IsNil))
require.Len(t, term.Pages(), count, taxonomy) b.Assert(len(term.Pages()), qt.Equals, count, qt.Commentf(taxonomy))
for _, p := range term.Pages() { for _, p := range term.Pages() {
require.Equal(t, page.KindTaxonomy, p.Kind()) b.Assert(p.Kind(), qt.Equals, page.KindTaxonomy)
} }
} }
cat1 := s.getPage(page.KindTaxonomy, "categories", "cat1") cat1 := s.getPage(page.KindTaxonomy, "categories", "cat1")
require.NotNil(t, cat1) b.Assert(cat1, qt.Not(qt.IsNil))
if uglyURLs { if uglyURLs {
require.Equal(t, "/blog/categories/cat1.html", cat1.RelPermalink()) b.Assert(cat1.RelPermalink(), qt.Equals, "/blog/categories/cat1.html")
} else { } else {
require.Equal(t, "/blog/categories/cat1/", cat1.RelPermalink()) b.Assert(cat1.RelPermalink(), qt.Equals, "/blog/categories/cat1/")
} }
pl1 := s.getPage(page.KindTaxonomy, "permalinkeds", "pl1") pl1 := s.getPage(page.KindTaxonomy, "permalinkeds", "pl1")
permalinkeds := s.getPage(page.KindTaxonomyTerm, "permalinkeds") permalinkeds := s.getPage(page.KindTaxonomyTerm, "permalinkeds")
require.NotNil(t, pl1) b.Assert(pl1, qt.Not(qt.IsNil))
require.NotNil(t, permalinkeds) b.Assert(permalinkeds, qt.Not(qt.IsNil))
if uglyURLs { if uglyURLs {
require.Equal(t, "/blog/perma/pl1.html", pl1.RelPermalink()) b.Assert(pl1.RelPermalink(), qt.Equals, "/blog/perma/pl1.html")
require.Equal(t, "/blog/permalinkeds.html", permalinkeds.RelPermalink()) b.Assert(permalinkeds.RelPermalink(), qt.Equals, "/blog/permalinkeds.html")
} else { } else {
require.Equal(t, "/blog/perma/pl1/", pl1.RelPermalink()) b.Assert(pl1.RelPermalink(), qt.Equals, "/blog/perma/pl1/")
require.Equal(t, "/blog/permalinkeds/", permalinkeds.RelPermalink()) b.Assert(permalinkeds.RelPermalink(), qt.Equals, "/blog/permalinkeds/")
} }
helloWorld := s.getPage(page.KindTaxonomy, "others", "hello-hugo-world") helloWorld := s.getPage(page.KindTaxonomy, "others", "hello-hugo-world")
require.NotNil(t, helloWorld) b.Assert(helloWorld, qt.Not(qt.IsNil))
require.Equal(t, "Hello Hugo world", helloWorld.Title()) b.Assert(helloWorld.Title(), qt.Equals, "Hello Hugo world")
// Issue #2977 // Issue #2977
b.AssertFileContent(pathFunc("public/empties/index.html"), "Taxonomy Term Page", "Empties") b.AssertFileContent(pathFunc("public/empties/index.html"), "Taxonomy Term Page", "Empties")
@ -209,8 +209,6 @@ permalinkeds:
func TestTaxonomiesPathSeparation(t *testing.T) { func TestTaxonomiesPathSeparation(t *testing.T) {
t.Parallel() t.Parallel()
assert := require.New(t)
config := ` config := `
baseURL = "https://example.com" baseURL = "https://example.com"
[taxonomies] [taxonomies]
@ -263,8 +261,8 @@ title: "This is S3s"
ta := s.findPagesByKind(page.KindTaxonomy) ta := s.findPagesByKind(page.KindTaxonomy)
te := s.findPagesByKind(page.KindTaxonomyTerm) te := s.findPagesByKind(page.KindTaxonomyTerm)
assert.Equal(4, len(te)) b.Assert(len(te), qt.Equals, 4)
assert.Equal(7, len(ta)) b.Assert(len(ta), qt.Equals, 7)
b.AssertFileContent("public/news/categories/a/index.html", "Taxonomy List Page 1|a|Hello|https://example.com/news/categories/a/|") b.AssertFileContent("public/news/categories/a/index.html", "Taxonomy List Page 1|a|Hello|https://example.com/news/categories/a/|")
b.AssertFileContent("public/news/categories/b/index.html", "Taxonomy List Page 1|This is B|Hello|https://example.com/news/categories/b/|") b.AssertFileContent("public/news/categories/b/index.html", "Taxonomy List Page 1|This is B|Hello|https://example.com/news/categories/b/|")

View file

@ -97,7 +97,7 @@ Shortcode: {{< myShort >}}
writeSource(t, fs, filepath.Join("layouts", "shortcodes", fmt.Sprintf("myShort.%s", suffix)), shortcodeTempl) writeSource(t, fs, filepath.Join("layouts", "shortcodes", fmt.Sprintf("myShort.%s", suffix)), shortcodeTempl)
s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{}) s := buildSingleSite(t, deps.DepsCfg{Fs: fs, Cfg: cfg}, BuildCfg{})
th := testHelper{s.Cfg, s.Fs, t} th := newTestHelper(s.Cfg, s.Fs, t)
th.assertFileContent(filepath.Join("public", "p", "index.html"), th.assertFileContent(filepath.Join("public", "p", "index.html"),
"Page Title: My Title", "Page Title: My Title",

View file

@ -196,7 +196,7 @@ func TestTemplateLookupOrder(t *testing.T) {
t.Run(this.name, func(t *testing.T) { t.Run(this.name, func(t *testing.T) {
// TODO(bep) there are some function vars need to pull down here to enable => t.Parallel() // TODO(bep) there are some function vars need to pull down here to enable => t.Parallel()
cfg, fs = newTestCfg() cfg, fs = newTestCfg()
th = testHelper{cfg, fs, t} th = newTestHelper(cfg, fs, t)
for i := 1; i <= 3; i++ { for i := 1; i <= 3; i++ {
writeSource(t, fs, filepath.Join("content", fmt.Sprintf("sect%d", i), fmt.Sprintf("page%d.md", i)), `--- writeSource(t, fs, filepath.Join("content", fmt.Sprintf("sect%d", i), fmt.Sprintf("page%d.md", i)), `---

View file

@ -8,7 +8,10 @@ import (
"testing" "testing"
"unicode/utf8" "unicode/utf8"
"github.com/gohugoio/hugo/output"
"github.com/gohugoio/hugo/parser/metadecoders" "github.com/gohugoio/hugo/parser/metadecoders"
"github.com/google/go-cmp/cmp"
"github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -36,10 +39,16 @@ import (
"github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/stretchr/testify/assert" )
"github.com/stretchr/testify/require"
var (
deepEqualsPages = qt.CmpEquals(cmp.Comparer(func(p1, p2 *pageState) bool { return p1 == p2 }))
deepEqualsOutputFormats = qt.CmpEquals(cmp.Comparer(func(o1, o2 output.Format) bool {
return o1.Name == o2.Name && o1.MediaType.Type() == o2.MediaType.Type()
}))
) )
type sitesBuilder struct { type sitesBuilder struct {
@ -50,7 +59,7 @@ type sitesBuilder struct {
T testing.TB T testing.TB
depsCfg deps.DepsCfg depsCfg deps.DepsCfg
*require.Assertions *qt.C
logger *loggers.Logger logger *loggers.Logger
@ -101,11 +110,11 @@ func newTestSitesBuilder(t testing.TB) *sitesBuilder {
Separator: " ", Separator: " ",
} }
return &sitesBuilder{T: t, Assertions: require.New(t), Fs: fs, configFormat: "toml", dumper: litterOptions} return &sitesBuilder{T: t, C: qt.New(t), Fs: fs, configFormat: "toml", dumper: litterOptions}
} }
func newTestSitesBuilderFromDepsCfg(t testing.TB, d deps.DepsCfg) *sitesBuilder { func newTestSitesBuilderFromDepsCfg(t testing.TB, d deps.DepsCfg) *sitesBuilder {
assert := require.New(t) c := qt.New(t)
litterOptions := litter.Options{ litterOptions := litter.Options{
HidePrivateFields: true, HidePrivateFields: true,
@ -113,7 +122,7 @@ func newTestSitesBuilderFromDepsCfg(t testing.TB, d deps.DepsCfg) *sitesBuilder
Separator: " ", Separator: " ",
} }
b := &sitesBuilder{T: t, Assertions: assert, depsCfg: d, Fs: d.Fs, dumper: litterOptions} b := &sitesBuilder{T: t, C: c, depsCfg: d, Fs: d.Fs, dumper: litterOptions}
workingDir := d.Cfg.GetString("workingDir") workingDir := d.Cfg.GetString("workingDir")
b.WithWorkingDir(workingDir) b.WithWorkingDir(workingDir)
@ -177,7 +186,7 @@ func (s *sitesBuilder) WithViper(v *viper.Viper) *sitesBuilder {
// Write to a config file to make sure the tests follow the same code path. // Write to a config file to make sure the tests follow the same code path.
var buff bytes.Buffer var buff bytes.Buffer
m := v.AllSettings() m := v.AllSettings()
s.Assertions.NoError(parser.InterfaceToConfig(m, metadecoders.TOML, &buff)) s.Assert(parser.InterfaceToConfig(m, metadecoders.TOML, &buff), qt.IsNil)
return s.WithConfigFile("toml", buff.String()) return s.WithConfigFile("toml", buff.String())
} }
@ -323,13 +332,13 @@ lag = "lag"
func (s *sitesBuilder) WithSunset(in string) { func (s *sitesBuilder) WithSunset(in string) {
// Write a real image into one of the bundle above. // Write a real image into one of the bundle above.
src, err := os.Open(filepath.FromSlash("testdata/sunset.jpg")) src, err := os.Open(filepath.FromSlash("testdata/sunset.jpg"))
s.NoError(err) s.Assert(err, qt.IsNil)
out, err := s.Fs.Source.Create(filepath.FromSlash(in)) out, err := s.Fs.Source.Create(filepath.FromSlash(in))
s.NoError(err) s.Assert(err, qt.IsNil)
_, err = io.Copy(out, src) _, err = io.Copy(out, src)
s.NoError(err) s.Assert(err, qt.IsNil)
out.Close() out.Close()
src.Close() src.Close()
@ -630,10 +639,6 @@ func (s *sitesBuilder) Fatalf(format string, args ...interface{}) {
s.T.Fatalf(format, args...) s.T.Fatalf(format, args...)
} }
func stackTrace() string {
return strings.Join(assert.CallerInfo(), "\n\r\t\t\t")
}
func (s *sitesBuilder) AssertFileContentFn(filename string, f func(s string) bool) { func (s *sitesBuilder) AssertFileContentFn(filename string, f func(s string) bool) {
s.T.Helper() s.T.Helper()
content := s.FileContent(filename) content := s.FileContent(filename)
@ -698,36 +703,44 @@ func (s *sitesBuilder) CheckExists(filename string) bool {
return destinationExists(s.Fs, filepath.Clean(filename)) return destinationExists(s.Fs, filepath.Clean(filename))
} }
func newTestHelper(cfg config.Provider, fs *hugofs.Fs, t testing.TB) testHelper {
return testHelper{
Cfg: cfg,
Fs: fs,
C: qt.New(t),
}
}
type testHelper struct { type testHelper struct {
Cfg config.Provider Cfg config.Provider
Fs *hugofs.Fs Fs *hugofs.Fs
T testing.TB *qt.C
} }
func (th testHelper) assertFileContent(filename string, matches ...string) { func (th testHelper) assertFileContent(filename string, matches ...string) {
th.T.Helper() th.Helper()
filename = th.replaceDefaultContentLanguageValue(filename) filename = th.replaceDefaultContentLanguageValue(filename)
content := readDestination(th.T, th.Fs, filename) content := readDestination(th, th.Fs, filename)
for _, match := range matches { for _, match := range matches {
match = th.replaceDefaultContentLanguageValue(match) match = th.replaceDefaultContentLanguageValue(match)
require.True(th.T, strings.Contains(content, match), fmt.Sprintf("File no match for\n%q in\n%q:\n%s", strings.Replace(match, "%", "%%", -1), filename, strings.Replace(content, "%", "%%", -1))) th.Assert(strings.Contains(content, match), qt.Equals, true)
} }
} }
func (th testHelper) assertFileContentRegexp(filename string, matches ...string) { func (th testHelper) assertFileContentRegexp(filename string, matches ...string) {
filename = th.replaceDefaultContentLanguageValue(filename) filename = th.replaceDefaultContentLanguageValue(filename)
content := readDestination(th.T, th.Fs, filename) content := readDestination(th, th.Fs, filename)
for _, match := range matches { for _, match := range matches {
match = th.replaceDefaultContentLanguageValue(match) match = th.replaceDefaultContentLanguageValue(match)
r := regexp.MustCompile(match) r := regexp.MustCompile(match)
require.True(th.T, r.MatchString(content), fmt.Sprintf("File no match for\n%q in\n%q:\n%s", strings.Replace(match, "%", "%%", -1), filename, strings.Replace(content, "%", "%%", -1))) th.Assert(r.MatchString(content), qt.Equals, true)
} }
} }
func (th testHelper) assertFileNotExist(filename string) { func (th testHelper) assertFileNotExist(filename string) {
exists, err := helpers.Exists(filename, th.Fs.Destination) exists, err := helpers.Exists(filename, th.Fs.Destination)
require.NoError(th.T, err) th.Assert(err, qt.IsNil)
require.False(th.T, exists) th.Assert(exists, qt.Equals, false)
} }
func (th testHelper) replaceDefaultContentLanguageValue(value string) string { func (th testHelper) replaceDefaultContentLanguageValue(value string) string {
@ -786,14 +799,16 @@ func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layou
t.Fatalf("Layouts must be provided in pairs") t.Fatalf("Layouts must be provided in pairs")
} }
c := qt.New(t)
writeToFs(t, afs, filepath.Join("content", ".gitkeep"), "") writeToFs(t, afs, filepath.Join("content", ".gitkeep"), "")
writeToFs(t, afs, "config.toml", tomlConfig) writeToFs(t, afs, "config.toml", tomlConfig)
cfg, err := LoadConfigDefault(afs) cfg, err := LoadConfigDefault(afs)
require.NoError(t, err) c.Assert(err, qt.IsNil)
fs := hugofs.NewFrom(afs, cfg) fs := hugofs.NewFrom(afs, cfg)
th := testHelper{cfg, fs, t} th := newTestHelper(cfg, fs, t)
for i := 0; i < len(layoutPathContentPairs); i += 2 { for i := 0; i < len(layoutPathContentPairs); i += 2 {
writeSource(t, fs, layoutPathContentPairs[i], layoutPathContentPairs[i+1]) writeSource(t, fs, layoutPathContentPairs[i], layoutPathContentPairs[i+1])
@ -801,7 +816,7 @@ func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layou
h, err := NewHugoSites(deps.DepsCfg{Fs: fs, Cfg: cfg}) h, err := NewHugoSites(deps.DepsCfg{Fs: fs, Cfg: cfg})
require.NoError(t, err) c.Assert(err, qt.IsNil)
return th, h return th, h
} }
@ -821,6 +836,7 @@ func createWithTemplateFromNameValues(additionalTemplates ...string) func(templ
// TODO(bep) replace these with the builder // TODO(bep) replace these with the builder
func buildSingleSite(t testing.TB, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site { func buildSingleSite(t testing.TB, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site {
t.Helper()
return buildSingleSiteExpected(t, false, false, depsCfg, buildCfg) return buildSingleSiteExpected(t, false, false, depsCfg, buildCfg)
} }
@ -831,23 +847,23 @@ func buildSingleSiteExpected(t testing.TB, expectSiteInitEror, expectBuildError
err := b.CreateSitesE() err := b.CreateSitesE()
if expectSiteInitEror { if expectSiteInitEror {
require.Error(t, err) b.Assert(err, qt.Not(qt.IsNil))
return nil return nil
} else { } else {
require.NoError(t, err) b.Assert(err, qt.IsNil)
} }
h := b.H h := b.H
require.Len(t, h.Sites, 1) b.Assert(len(h.Sites), qt.Equals, 1)
if expectBuildError { if expectBuildError {
require.Error(t, h.Build(buildCfg)) b.Assert(h.Build(buildCfg), qt.Not(qt.IsNil))
return nil return nil
} }
require.NoError(t, h.Build(buildCfg)) b.Assert(h.Build(buildCfg), qt.IsNil)
return h.Sites[0] return h.Sites[0]
} }

View file

@ -29,9 +29,9 @@ import (
"github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/deps"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/hugofs"
"github.com/stretchr/testify/require"
) )
var logger = loggers.NewErrorLogger() var logger = loggers.NewErrorLogger()
@ -179,19 +179,19 @@ func doTestI18nTranslate(t testing.TB, test i18nTest, cfg config.Provider) strin
} }
func prepareTranslationProvider(t testing.TB, test i18nTest, cfg config.Provider) *TranslationProvider { func prepareTranslationProvider(t testing.TB, test i18nTest, cfg config.Provider) *TranslationProvider {
assert := require.New(t) c := qt.New(t)
fs := hugofs.NewMem(cfg) fs := hugofs.NewMem(cfg)
for file, content := range test.data { for file, content := range test.data {
err := afero.WriteFile(fs.Source, filepath.Join("i18n", file), []byte(content), 0755) err := afero.WriteFile(fs.Source, filepath.Join("i18n", file), []byte(content), 0755)
assert.NoError(err) c.Assert(err, qt.IsNil)
} }
tp := NewTranslationProvider() tp := NewTranslationProvider()
depsCfg := newDepsConfig(tp, cfg, fs) depsCfg := newDepsConfig(tp, cfg, fs)
d, err := deps.New(depsCfg) d, err := deps.New(depsCfg)
assert.NoError(err) c.Assert(err, qt.IsNil)
assert.NoError(d.LoadResources()) c.Assert(d.LoadResources(), qt.IsNil)
return tp return tp
} }
@ -233,6 +233,7 @@ func getConfig() *viper.Viper {
} }
func TestI18nTranslate(t *testing.T) { func TestI18nTranslate(t *testing.T) {
c := qt.New(t)
var actual, expected string var actual, expected string
v := getConfig() v := getConfig()
@ -247,7 +248,7 @@ func TestI18nTranslate(t *testing.T) {
expected = test.expected expected = test.expected
} }
actual = doTestI18nTranslate(t, test, v) actual = doTestI18nTranslate(t, test, v)
require.Equal(t, expected, actual) c.Assert(actual, qt.Equals, expected)
} }
} }
} }

View file

@ -16,11 +16,12 @@ package langs
import ( import (
"testing" "testing"
qt "github.com/frankban/quicktest"
"github.com/spf13/viper" "github.com/spf13/viper"
"github.com/stretchr/testify/require"
) )
func TestGetGlobalOnlySetting(t *testing.T) { func TestGetGlobalOnlySetting(t *testing.T) {
c := qt.New(t)
v := viper.New() v := viper.New()
v.Set("defaultContentLanguageInSubdir", true) v.Set("defaultContentLanguageInSubdir", true)
v.Set("contentDir", "content") v.Set("contentDir", "content")
@ -29,12 +30,12 @@ func TestGetGlobalOnlySetting(t *testing.T) {
lang.Set("defaultContentLanguageInSubdir", false) lang.Set("defaultContentLanguageInSubdir", false)
lang.Set("paginatePath", "side") lang.Set("paginatePath", "side")
require.True(t, lang.GetBool("defaultContentLanguageInSubdir")) c.Assert(lang.GetBool("defaultContentLanguageInSubdir"), qt.Equals, true)
require.Equal(t, "side", lang.GetString("paginatePath")) c.Assert(lang.GetString("paginatePath"), qt.Equals, "side")
} }
func TestLanguageParams(t *testing.T) { func TestLanguageParams(t *testing.T) {
assert := require.New(t) c := qt.New(t)
v := viper.New() v := viper.New()
v.Set("p1", "p1cfg") v.Set("p1", "p1cfg")
@ -43,6 +44,6 @@ func TestLanguageParams(t *testing.T) {
lang := NewDefaultLanguage(v) lang := NewDefaultLanguage(v)
lang.SetParam("p1", "p1p") lang.SetParam("p1", "p1p")
assert.Equal("p1p", lang.Params()["p1"]) c.Assert(lang.Params()["p1"], qt.Equals, "p1p")
assert.Equal("p1cfg", lang.Get("p1")) c.Assert(lang.Get("p1"), qt.Equals, "p1cfg")
} }

View file

@ -22,7 +22,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/stretchr/testify/require" qt "github.com/frankban/quicktest"
) )
var ( var (
@ -44,7 +44,7 @@ func doWorkOfSize(size int) {
} }
func TestInit(t *testing.T) { func TestInit(t *testing.T) {
assert := require.New(t) c := qt.New(t)
var result string var result string
@ -84,33 +84,33 @@ func TestInit(t *testing.T) {
var err error var err error
if rnd.Intn(10) < 5 { if rnd.Intn(10) < 5 {
_, err = root.Do() _, err = root.Do()
assert.NoError(err) c.Assert(err, qt.IsNil)
} }
// Add a new branch on the fly. // Add a new branch on the fly.
if rnd.Intn(10) > 5 { if rnd.Intn(10) > 5 {
branch := branch1_2.Branch(f2()) branch := branch1_2.Branch(f2())
_, err = branch.Do() _, err = branch.Do()
assert.NoError(err) c.Assert(err, qt.IsNil)
} else { } else {
_, err = branch1_2_1.Do() _, err = branch1_2_1.Do()
assert.NoError(err) c.Assert(err, qt.IsNil)
} }
_, err = branch1_2.Do() _, err = branch1_2.Do()
assert.NoError(err) c.Assert(err, qt.IsNil)
}(i) }(i)
wg.Wait() wg.Wait()
assert.Equal("root(1)|root(2)|branch_1|branch_1_1|branch_1_2|branch_1_2_1|", result) c.Assert(result, qt.Equals, "root(1)|root(2)|branch_1|branch_1_1|branch_1_2|branch_1_2_1|")
} }
} }
func TestInitAddWithTimeout(t *testing.T) { func TestInitAddWithTimeout(t *testing.T) {
assert := require.New(t) c := qt.New(t)
init := New().AddWithTimeout(100*time.Millisecond, func(ctx context.Context) (interface{}, error) { init := New().AddWithTimeout(100*time.Millisecond, func(ctx context.Context) (interface{}, error) {
return nil, nil return nil, nil
@ -118,11 +118,11 @@ func TestInitAddWithTimeout(t *testing.T) {
_, err := init.Do() _, err := init.Do()
assert.NoError(err) c.Assert(err, qt.IsNil)
} }
func TestInitAddWithTimeoutTimeout(t *testing.T) { func TestInitAddWithTimeoutTimeout(t *testing.T) {
assert := require.New(t) c := qt.New(t)
init := New().AddWithTimeout(100*time.Millisecond, func(ctx context.Context) (interface{}, error) { init := New().AddWithTimeout(100*time.Millisecond, func(ctx context.Context) (interface{}, error) {
time.Sleep(500 * time.Millisecond) time.Sleep(500 * time.Millisecond)
@ -137,16 +137,16 @@ func TestInitAddWithTimeoutTimeout(t *testing.T) {
_, err := init.Do() _, err := init.Do()
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
assert.Contains(err.Error(), "timed out") c.Assert(err.Error(), qt.Contains, "timed out")
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
} }
func TestInitAddWithTimeoutError(t *testing.T) { func TestInitAddWithTimeoutError(t *testing.T) {
assert := require.New(t) c := qt.New(t)
init := New().AddWithTimeout(100*time.Millisecond, func(ctx context.Context) (interface{}, error) { init := New().AddWithTimeout(100*time.Millisecond, func(ctx context.Context) (interface{}, error) {
return nil, errors.New("failed") return nil, errors.New("failed")
@ -154,7 +154,7 @@ func TestInitAddWithTimeoutError(t *testing.T) {
_, err := init.Do() _, err := init.Do()
assert.Error(err) c.Assert(err, qt.Not(qt.IsNil))
} }
type T struct { type T struct {
@ -177,7 +177,7 @@ func (t *T) Add2(v string) {
// https://github.com/gohugoio/hugo/issues/5901 // https://github.com/gohugoio/hugo/issues/5901
func TestInitBranchOrder(t *testing.T) { func TestInitBranchOrder(t *testing.T) {
assert := require.New(t) c := qt.New(t)
base := New() base := New()
@ -216,11 +216,11 @@ func TestInitBranchOrder(t *testing.T) {
go func() { go func() {
defer wg.Done() defer wg.Done()
_, err := v.Do() _, err := v.Do()
assert.NoError(err) c.Assert(err, qt.IsNil)
}() }()
} }
wg.Wait() wg.Wait()
assert.Equal("ABAB", state.V2) c.Assert(state.V2, qt.Equals, "ABAB")
} }

View file

@ -304,7 +304,7 @@ func TestCoverHTML() error {
} }
func isGoLatest() bool { func isGoLatest() bool {
return strings.Contains(runtime.Version(), "1.11") return strings.Contains(runtime.Version(), "1.12")
} }
func isCI() bool { func isCI() bool {

Some files were not shown because too many files have changed in this diff Show more