gitee.com/mirrors/Hugo-Go@v0.47.1/commands/commands_test.go (about)

     1  // Copyright 2018 The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package commands
    15  
    16  import (
    17  	"fmt"
    18  	"io/ioutil"
    19  	"os"
    20  	"path/filepath"
    21  	"testing"
    22  
    23  	"github.com/spf13/cobra"
    24  	"github.com/spf13/viper"
    25  
    26  	"github.com/stretchr/testify/require"
    27  )
    28  
    29  func TestExecute(t *testing.T) {
    30  
    31  	assert := require.New(t)
    32  
    33  	dir, err := createSimpleTestSite(t)
    34  	assert.NoError(err)
    35  
    36  	defer func() {
    37  		os.RemoveAll(dir)
    38  	}()
    39  
    40  	resp := Execute([]string{"-s=" + dir})
    41  	assert.NoError(resp.Err)
    42  	result := resp.Result
    43  	assert.True(len(result.Sites) == 1)
    44  	assert.True(len(result.Sites[0].RegularPages) == 1)
    45  }
    46  
    47  func TestCommandsPersistentFlags(t *testing.T) {
    48  	assert := require.New(t)
    49  
    50  	noOpRunE := func(cmd *cobra.Command, args []string) error {
    51  		return nil
    52  	}
    53  
    54  	tests := []struct {
    55  		args  []string
    56  		check func(command []cmder)
    57  	}{{[]string{"server",
    58  		"--config=myconfig.toml",
    59  		"--contentDir=mycontent",
    60  		"--disableKinds=page,home",
    61  		"--layoutDir=mylayouts",
    62  		"--theme=mytheme",
    63  		"--gc",
    64  		"--themesDir=mythemes",
    65  		"--cleanDestinationDir",
    66  		"--navigateToChanged",
    67  		"--disableLiveReload",
    68  		"--noHTTPCache",
    69  		"--i18n-warnings",
    70  		"--destination=/tmp/mydestination",
    71  		"-b=https://example.com/b/",
    72  		"--port=1366",
    73  		"--renderToDisk",
    74  		"--source=mysource",
    75  		"--uglyURLs"}, func(commands []cmder) {
    76  		var sc *serverCmd
    77  		for _, command := range commands {
    78  			if b, ok := command.(commandsBuilderGetter); ok {
    79  				v := b.getCmmandsBuilder().hugoBuilderCommon
    80  				assert.Equal("myconfig.toml", v.cfgFile)
    81  				assert.Equal("mysource", v.source)
    82  				assert.Equal("https://example.com/b/", v.baseURL)
    83  			}
    84  
    85  			if srvCmd, ok := command.(*serverCmd); ok {
    86  				sc = srvCmd
    87  			}
    88  		}
    89  
    90  		assert.NotNil(sc)
    91  		assert.True(sc.navigateToChanged)
    92  		assert.True(sc.disableLiveReload)
    93  		assert.True(sc.noHTTPCache)
    94  		assert.True(sc.renderToDisk)
    95  		assert.Equal(1366, sc.serverPort)
    96  
    97  		cfg := viper.New()
    98  		sc.flagsToConfig(cfg)
    99  		assert.Equal("/tmp/mydestination", cfg.GetString("publishDir"))
   100  		assert.Equal("mycontent", cfg.GetString("contentDir"))
   101  		assert.Equal("mylayouts", cfg.GetString("layoutDir"))
   102  		assert.Equal("mytheme", cfg.GetString("theme"))
   103  		assert.Equal("mythemes", cfg.GetString("themesDir"))
   104  		assert.Equal("https://example.com/b/", cfg.GetString("baseURL"))
   105  
   106  		assert.Equal([]string{"page", "home"}, cfg.Get("disableKinds"))
   107  
   108  		assert.True(cfg.GetBool("uglyURLs"))
   109  		assert.True(cfg.GetBool("gc"))
   110  
   111  		// The flag is named i18n-warnings
   112  		assert.True(cfg.GetBool("logI18nWarnings"))
   113  
   114  	}}}
   115  
   116  	for _, test := range tests {
   117  		b := newCommandsBuilder()
   118  		root := b.addAll().build()
   119  
   120  		for _, c := range b.commands {
   121  			if c.getCommand() == nil {
   122  				continue
   123  			}
   124  			// We are only intereseted in the flag handling here.
   125  			c.getCommand().RunE = noOpRunE
   126  		}
   127  		rootCmd := root.getCommand()
   128  		rootCmd.SetArgs(test.args)
   129  		assert.NoError(rootCmd.Execute())
   130  		test.check(b.commands)
   131  	}
   132  
   133  }
   134  
   135  func TestCommandsExecute(t *testing.T) {
   136  
   137  	assert := require.New(t)
   138  
   139  	dir, err := createSimpleTestSite(t)
   140  	assert.NoError(err)
   141  
   142  	dirOut, err := ioutil.TempDir("", "hugo-cli-out")
   143  	assert.NoError(err)
   144  
   145  	defer func() {
   146  		os.RemoveAll(dir)
   147  		os.RemoveAll(dirOut)
   148  	}()
   149  
   150  	sourceFlag := fmt.Sprintf("-s=%s", dir)
   151  
   152  	tests := []struct {
   153  		commands           []string
   154  		flags              []string
   155  		expectErrToContain string
   156  	}{
   157  		// TODO(bep) permission issue on my OSX? "operation not permitted" {[]string{"check", "ulimit"}, nil, false},
   158  		{[]string{"env"}, nil, ""},
   159  		{[]string{"version"}, nil, ""},
   160  		// no args = hugo build
   161  		{nil, []string{sourceFlag}, ""},
   162  		{nil, []string{sourceFlag, "--renderToMemory"}, ""},
   163  		{[]string{"config"}, []string{sourceFlag}, ""},
   164  		{[]string{"benchmark"}, []string{sourceFlag, "-n=1"}, ""},
   165  		{[]string{"convert", "toTOML"}, []string{sourceFlag, "-o=" + filepath.Join(dirOut, "toml")}, ""},
   166  		{[]string{"convert", "toYAML"}, []string{sourceFlag, "-o=" + filepath.Join(dirOut, "yaml")}, ""},
   167  		{[]string{"convert", "toJSON"}, []string{sourceFlag, "-o=" + filepath.Join(dirOut, "json")}, ""},
   168  		{[]string{"gen", "autocomplete"}, []string{"--completionfile=" + filepath.Join(dirOut, "autocomplete.txt")}, ""},
   169  		{[]string{"gen", "chromastyles"}, []string{"--style=manni"}, ""},
   170  		{[]string{"gen", "doc"}, []string{"--dir=" + filepath.Join(dirOut, "doc")}, ""},
   171  		{[]string{"gen", "man"}, []string{"--dir=" + filepath.Join(dirOut, "man")}, ""},
   172  		{[]string{"list", "drafts"}, []string{sourceFlag}, ""},
   173  		{[]string{"list", "expired"}, []string{sourceFlag}, ""},
   174  		{[]string{"list", "future"}, []string{sourceFlag}, ""},
   175  		{[]string{"new", "new-page.md"}, []string{sourceFlag}, ""},
   176  		{[]string{"new", "site", filepath.Join(dirOut, "new-site")}, nil, ""},
   177  		{[]string{"unknowncommand"}, nil, "unknown command"},
   178  		// TODO(bep) cli refactor fix https://github.com/gohugoio/hugo/issues/4450
   179  		//{[]string{"new", "theme", filepath.Join(dirOut, "new-theme")}, nil,false},
   180  	}
   181  
   182  	for _, test := range tests {
   183  
   184  		hugoCmd := newCommandsBuilder().addAll().build().getCommand()
   185  		test.flags = append(test.flags, "--quiet")
   186  		hugoCmd.SetArgs(append(test.commands, test.flags...))
   187  
   188  		// TODO(bep) capture output and add some simple asserts
   189  		// TODO(bep) misspelled subcommands does not return an error. We should investigate this
   190  		// but before that, check for "Error: unknown command".
   191  
   192  		_, err := hugoCmd.ExecuteC()
   193  		if test.expectErrToContain != "" {
   194  			assert.Error(err, fmt.Sprintf("%v", test.commands))
   195  			assert.Contains(err.Error(), test.expectErrToContain)
   196  		} else {
   197  			assert.NoError(err, fmt.Sprintf("%v", test.commands))
   198  		}
   199  
   200  	}
   201  
   202  }
   203  
   204  func createSimpleTestSite(t *testing.T) (string, error) {
   205  	d, e := ioutil.TempDir("", "hugo-cli")
   206  	if e != nil {
   207  		return "", e
   208  	}
   209  
   210  	// Just the basic. These are for CLI tests, not site testing.
   211  	writeFile(t, filepath.Join(d, "config.toml"), `
   212  
   213  baseURL = "https://example.org"
   214  title = "Hugo Commands"
   215  
   216  `)
   217  
   218  	writeFile(t, filepath.Join(d, "content", "p1.md"), `
   219  ---
   220  title: "P1"
   221  weight: 1
   222  ---
   223  
   224  Content
   225  
   226  `)
   227  
   228  	writeFile(t, filepath.Join(d, "layouts", "_default", "single.html"), `
   229  
   230  Single: {{ .Title }}
   231  
   232  `)
   233  
   234  	writeFile(t, filepath.Join(d, "layouts", "_default", "list.html"), `
   235  
   236  List: {{ .Title }}
   237  
   238  `)
   239  
   240  	return d, nil
   241  
   242  }
   243  
   244  func writeFile(t *testing.T, filename, content string) {
   245  	must(t, os.MkdirAll(filepath.Dir(filename), os.FileMode(0755)))
   246  	must(t, ioutil.WriteFile(filename, []byte(content), os.FileMode(0755)))
   247  }
   248  
   249  func must(t *testing.T, err error) {
   250  	if err != nil {
   251  		t.Fatal(err)
   252  	}
   253  }