hugo/tpl/data/resources_test.go

234 lines
5.8 KiB
Go
Raw Normal View History

// Copyright 2016 The Hugo Authors. All rights reserved.
//
2015-11-23 22:16:36 -05:00
// 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
2015-11-23 22:16:36 -05:00
// 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 data
import (
"bytes"
"net/http"
"net/http/httptest"
"net/url"
"sync"
"testing"
"time"
"github.com/gohugoio/hugo/config/security"
"github.com/gohugoio/hugo/modules"
"github.com/gohugoio/hugo/helpers"
qt "github.com/frankban/quicktest"
"github.com/gohugoio/hugo/cache/filecache"
"github.com/gohugoio/hugo/common/hexec"
"github.com/gohugoio/hugo/common/loggers"
"github.com/gohugoio/hugo/config"
"github.com/gohugoio/hugo/deps"
"github.com/gohugoio/hugo/hugofs"
Add support for theme composition and inheritance This commit adds support for theme composition and inheritance in Hugo. With this, it helps thinking about a theme as a set of ordered components: ```toml theme = ["my-shortcodes", "base-theme", "hyde"] ``` The theme definition example above in `config.toml` creates a theme with the 3 components with presedence from left to right. So, Hugo will, for any given file, data entry etc., look first in the project, and then in `my-shortcode`, `base-theme` and lastly `hyde`. Hugo uses two different algorithms to merge the filesystems, depending on the file type: * For `i18n` and `data` files, Hugo merges deeply using the translation id and data key inside the files. * For `static`, `layouts` (templates) and `archetypes` files, these are merged on file level. So the left-most file will be chosen. The name used in the `theme` definition above must match a folder in `/your-site/themes`, e.g. `/your-site/themes/my-shortcodes`. There are plans to improve on this and get a URL scheme so this can be resolved automatically. Also note that a component that is part of a theme can have its own configuration file, e.g. `config.toml`. There are currently some restrictions to what a theme component can configure: * `params` (global and per language) * `menu` (global and per language) * `outputformats` and `mediatypes` The same rules apply here: The left-most param/menu etc. with the same ID will win. There are some hidden and experimental namespace support in the above, which we will work to improve in the future, but theme authors are encouraged to create their own namespaces to avoid naming conflicts. A final note: Themes/components can also have a `theme` definition in their `config.toml` and similar, which is the "inheritance" part of this commit's title. This is currently not supported by the Hugo theme site. We will have to wait for some "auto dependency" feature to be implemented for that to happen, but this can be a powerful feature if you want to create your own theme-variant based on others. Fixes #4460 Fixes #4450
2018-03-01 09:01:25 -05:00
"github.com/gohugoio/hugo/langs"
"github.com/spf13/afero"
)
func TestScpGetLocal(t *testing.T) {
t.Parallel()
v := config.New()
fs := hugofs.NewMem(v)
ps := helpers.FilePathSeparator
tests := []struct {
path string
content []byte
}{
{"testpath" + ps + "test.txt", []byte(`T€st Content 123 fOO,bar:foo%bAR`)},
{"FOo" + ps + "BaR.html", []byte(`FOo/BaR.html T€st Content 123`)},
{"трям" + ps + "трям", []byte(`T€st трям/трям Content 123`)},
{"은행", []byte(`T€st C은행ontent 123`)},
{"Банковский кассир", []byte(`Банковский кассир T€st Content 123`)},
}
for _, test := range tests {
r := bytes.NewReader(test.content)
err := helpers.WriteToDisk(test.path, r, fs.Source)
if err != nil {
t.Error(err)
}
c, err := getLocal(test.path, fs.Source, v)
if err != nil {
t.Errorf("Error getting resource content: %s", err)
}
2016-11-23 12:53:50 -05:00
if !bytes.Equal(c, test.content) {
t.Errorf("\nExpected: %s\nActual: %s\n", string(test.content), string(c))
}
}
}
func getTestServer(handler func(w http.ResponseWriter, r *http.Request)) (*httptest.Server, *http.Client) {
testServer := httptest.NewServer(http.HandlerFunc(handler))
client := &http.Client{
Transport: &http.Transport{Proxy: func(r *http.Request) (*url.URL, error) {
2015-12-18 17:23:37 -05:00
// Remove when https://github.com/golang/go/issues/13686 is fixed
r.Host = "gohugo.io"
return url.Parse(testServer.URL)
}},
}
return testServer, client
}
func TestScpGetRemote(t *testing.T) {
t.Parallel()
c := qt.New(t)
fs := new(afero.MemMapFs)
cache := filecache.NewCache(fs, 100, "")
tests := []struct {
path string
content []byte
}{
{"http://Foo.Bar/foo_Bar-Foo", []byte(`T€st Content 123`)},
{"http://Doppel.Gänger/foo_Bar-Foo", []byte(`T€st Cont€nt 123`)},
{"http://Doppel.Gänger/Fizz_Bazz-Foo", []byte(`T€st Банковский кассир Cont€nt 123`)},
{"http://Doppel.Gänger/Fizz_Bazz-Bar", []byte(`T€st Банковский кассир Cont€nt 456`)},
}
for _, test := range tests {
msg := qt.Commentf("%v", test)
req, err := http.NewRequest("GET", test.path, nil)
c.Assert(err, qt.IsNil, msg)
srv, cl := getTestServer(func(w http.ResponseWriter, r *http.Request) {
w.Write(test.content)
})
defer func() { srv.Close() }()
ns := newTestNs()
ns.client = cl
var cb []byte
2019-03-24 05:11:16 -04:00
f := func(b []byte) (bool, error) {
cb = b
2019-03-24 05:11:16 -04:00
return false, nil
}
err = ns.getRemote(cache, f, req)
c.Assert(err, qt.IsNil, msg)
c.Assert(string(cb), qt.Equals, string(test.content))
c.Assert(string(cb), qt.Equals, string(test.content))
}
}
func TestScpGetRemoteParallel(t *testing.T) {
t.Parallel()
c := qt.New(t)
content := []byte(`T€st Content 123`)
srv, cl := getTestServer(func(w http.ResponseWriter, r *http.Request) {
w.Write(content)
})
defer func() { srv.Close() }()
url := "http://Foo.Bar/foo_Bar-Foo"
req, err := http.NewRequest("GET", url, nil)
c.Assert(err, qt.IsNil)
for _, ignoreCache := range []bool{false} {
cfg := config.New()
cfg.Set("ignoreCache", ignoreCache)
cfg.Set("contentDir", "content")
ns := New(newDeps(cfg))
ns.client = cl
var wg sync.WaitGroup
for i := 0; i < 1; i++ {
wg.Add(1)
go func(gor int) {
defer wg.Done()
for j := 0; j < 10; j++ {
var cb []byte
2019-03-24 05:11:16 -04:00
f := func(b []byte) (bool, error) {
cb = b
2019-03-24 05:11:16 -04:00
return false, nil
}
err := ns.getRemote(ns.cacheGetJSON, f, req)
c.Assert(err, qt.IsNil)
if string(content) != string(cb) {
t.Errorf("expected\n%q\ngot\n%q", content, cb)
}
time.Sleep(23 * time.Millisecond)
}
}(i)
}
wg.Wait()
}
}
func newDeps(cfg config.Provider) *deps.Deps {
cfg.Set("resourceDir", "resources")
cfg.Set("dataDir", "resources")
cfg.Set("i18nDir", "i18n")
cfg.Set("assetDir", "assets")
cfg.Set("layoutDir", "layouts")
cfg.Set("archetypeDir", "archetypes")
langs.LoadLanguageSettings(cfg, nil)
mod, err := modules.CreateProjectModule(cfg)
if err != nil {
panic(err)
}
cfg.Set("allModules", modules.Modules{mod})
ex := hexec.New(security.DefaultConfig)
logger := loggers.NewIgnorableLogger(loggers.NewErrorLogger(), "none")
cs, err := helpers.NewContentSpec(cfg, logger, afero.NewMemMapFs(), ex)
if err != nil {
panic(err)
}
fs := hugofs.NewMem(cfg)
p, err := helpers.NewPathSpec(fs, cfg, nil)
if err != nil {
panic(err)
}
fileCaches, err := filecache.NewCaches(p)
if err != nil {
panic(err)
}
return &deps.Deps{
Cfg: cfg,
Fs: fs,
FileCaches: fileCaches,
ExecHelper: ex,
ContentSpec: cs,
Log: logger,
LogDistinct: helpers.NewDistinctLogger(logger),
}
}
2018-03-21 12:21:46 -04:00
func newTestNs() *Namespace {
v := config.New()
2018-03-21 12:21:46 -04:00
v.Set("contentDir", "content")
return New(newDeps(v))
}