Skip to content
Myr

yaml_docs_test.go

This file

Path

doc/yaml_docs_test.go

100 lines · 2.6 KiB · Go

Last changed by

Replace deprecated ioutil usage (#2181)Nir Sofferbefore adoption511af59

History of this file

Take it

1// Copyright 2013-2023 The Cobra Authors2//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 at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415package doc1617import (18	"bytes"19	"fmt"20	"os"21	"path/filepath"22	"testing"2324	"github.com/spf13/cobra"25)2627func TestGenYamlDoc(t *testing.T) {28	// We generate on s subcommand so we have both subcommands and parents29	buf := new(bytes.Buffer)30	if err := GenYaml(echoCmd, buf); err != nil {31		t.Fatal(err)32	}33	output := buf.String()3435	checkStringContains(t, output, echoCmd.Long)36	checkStringContains(t, output, echoCmd.Example)37	checkStringContains(t, output, "boolone")38	checkStringContains(t, output, "rootflag")39	checkStringContains(t, output, rootCmd.Short)40	checkStringContains(t, output, echoSubCmd.Short)41	checkStringContains(t, output, fmt.Sprintf("- %s - %s", echoSubCmd.CommandPath(), echoSubCmd.Short))42}4344func TestGenYamlNoTag(t *testing.T) {45	rootCmd.DisableAutoGenTag = true46	defer func() { rootCmd.DisableAutoGenTag = false }()4748	buf := new(bytes.Buffer)49	if err := GenYaml(rootCmd, buf); err != nil {50		t.Fatal(err)51	}52	output := buf.String()5354	checkStringOmits(t, output, "Auto generated")55}5657func TestGenYamlTree(t *testing.T) {58	c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}5960	tmpdir, err := os.MkdirTemp("", "test-gen-yaml-tree")61	if err != nil {62		t.Fatalf("Failed to create tmpdir: %s", err.Error())63	}64	defer os.RemoveAll(tmpdir)6566	if err := GenYamlTree(c, tmpdir); err != nil {67		t.Fatalf("GenYamlTree failed: %s", err.Error())68	}6970	if _, err := os.Stat(filepath.Join(tmpdir, "do.yaml")); err != nil {71		t.Fatalf("Expected file 'do.yaml' to exist")72	}73}7475func TestGenYamlDocRunnable(t *testing.T) {76	// Testing a runnable command: should contain the "usage" field77	buf := new(bytes.Buffer)78	if err := GenYaml(rootCmd, buf); err != nil {79		t.Fatal(err)80	}81	output := buf.String()8283	checkStringContains(t, output, "usage: "+rootCmd.Use)84}8586func BenchmarkGenYamlToFile(b *testing.B) {87	file, err := os.CreateTemp("", "")88	if err != nil {89		b.Fatal(err)90	}91	defer os.Remove(file.Name())92	defer file.Close()9394	b.ResetTimer()95	for i := 0; i < b.N; i++ {96		if err := GenYaml(rootCmd, file); err != nil {97			b.Fatal(err)98		}99	}100}