github.com/dominikszabo/hugo-ds-clean@v0.47.1/helpers/general_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 helpers
    15  
    16  import (
    17  	"fmt"
    18  	"reflect"
    19  	"strings"
    20  	"testing"
    21  
    22  	"github.com/spf13/afero"
    23  	"github.com/stretchr/testify/assert"
    24  	"github.com/stretchr/testify/require"
    25  )
    26  
    27  func TestGuessType(t *testing.T) {
    28  	for i, this := range []struct {
    29  		in     string
    30  		expect string
    31  	}{
    32  		{"md", "markdown"},
    33  		{"markdown", "markdown"},
    34  		{"mdown", "markdown"},
    35  		{"asciidoc", "asciidoc"},
    36  		{"adoc", "asciidoc"},
    37  		{"ad", "asciidoc"},
    38  		{"rst", "rst"},
    39  		{"pandoc", "pandoc"},
    40  		{"pdc", "pandoc"},
    41  		{"mmark", "mmark"},
    42  		{"html", "html"},
    43  		{"htm", "html"},
    44  		{"org", "org"},
    45  		{"excel", "unknown"},
    46  	} {
    47  		result := GuessType(this.in)
    48  		if result != this.expect {
    49  			t.Errorf("[%d] got %s but expected %s", i, result, this.expect)
    50  		}
    51  	}
    52  }
    53  
    54  func TestFirstUpper(t *testing.T) {
    55  	for i, this := range []struct {
    56  		in     string
    57  		expect string
    58  	}{
    59  		{"foo", "Foo"},
    60  		{"foo bar", "Foo bar"},
    61  		{"Foo Bar", "Foo Bar"},
    62  		{"", ""},
    63  		{"å", "Å"},
    64  	} {
    65  		result := FirstUpper(this.in)
    66  		if result != this.expect {
    67  			t.Errorf("[%d] got %s but expected %s", i, result, this.expect)
    68  		}
    69  	}
    70  }
    71  
    72  func TestHasStringsPrefix(t *testing.T) {
    73  	for i, this := range []struct {
    74  		s      []string
    75  		prefix []string
    76  		expect bool
    77  	}{
    78  		{[]string{"a"}, []string{"a"}, true},
    79  		{[]string{}, []string{}, true},
    80  		{[]string{"a", "b", "c"}, []string{"a", "b"}, true},
    81  		{[]string{"d", "a", "b", "c"}, []string{"a", "b"}, false},
    82  		{[]string{"abra", "ca", "dabra"}, []string{"abra", "ca"}, true},
    83  		{[]string{"abra", "ca"}, []string{"abra", "ca", "dabra"}, false},
    84  	} {
    85  		result := HasStringsPrefix(this.s, this.prefix)
    86  		if result != this.expect {
    87  			t.Fatalf("[%d] got %t but expected %t", i, result, this.expect)
    88  		}
    89  	}
    90  }
    91  
    92  func TestHasStringsSuffix(t *testing.T) {
    93  	for i, this := range []struct {
    94  		s      []string
    95  		suffix []string
    96  		expect bool
    97  	}{
    98  		{[]string{"a"}, []string{"a"}, true},
    99  		{[]string{}, []string{}, true},
   100  		{[]string{"a", "b", "c"}, []string{"b", "c"}, true},
   101  		{[]string{"abra", "ca", "dabra"}, []string{"abra", "ca"}, false},
   102  		{[]string{"abra", "ca", "dabra"}, []string{"ca", "dabra"}, true},
   103  	} {
   104  		result := HasStringsSuffix(this.s, this.suffix)
   105  		if result != this.expect {
   106  			t.Fatalf("[%d] got %t but expected %t", i, result, this.expect)
   107  		}
   108  	}
   109  }
   110  
   111  var containsTestText = (`На берегу пустынных волн
   112  Стоял он, дум великих полн,
   113  И вдаль глядел. Пред ним широко
   114  Река неслася; бедный чёлн
   115  По ней стремился одиноко.
   116  По мшистым, топким берегам
   117  Чернели избы здесь и там,
   118  Приют убогого чухонца;
   119  И лес, неведомый лучам
   120  В тумане спрятанного солнца,
   121  Кругом шумел.
   122  
   123  Τη γλώσσα μου έδωσαν ελληνική
   124  το σπίτι φτωχικό στις αμμουδιές του Ομήρου.
   125  Μονάχη έγνοια η γλώσσα μου στις αμμουδιές του Ομήρου.
   126  
   127  από το Άξιον Εστί
   128  του Οδυσσέα Ελύτη
   129  
   130  Sîne klâwen durh die wolken sint geslagen,
   131  er stîget ûf mit grôzer kraft,
   132  ich sih in grâwen tägelîch als er wil tagen,
   133  den tac, der im geselleschaft
   134  erwenden wil, dem werden man,
   135  den ich mit sorgen în verliez.
   136  ich bringe in hinnen, ob ich kan.
   137  sîn vil manegiu tugent michz leisten hiez.
   138  `)
   139  
   140  var containsBenchTestData = []struct {
   141  	v1     string
   142  	v2     []byte
   143  	expect bool
   144  }{
   145  	{"abc", []byte("a"), true},
   146  	{"abc", []byte("b"), true},
   147  	{"abcdefg", []byte("efg"), true},
   148  	{"abc", []byte("d"), false},
   149  	{containsTestText, []byte("стремился"), true},
   150  	{containsTestText, []byte(containsTestText[10:80]), true},
   151  	{containsTestText, []byte(containsTestText[100:111]), true},
   152  	{containsTestText, []byte(containsTestText[len(containsTestText)-100 : len(containsTestText)-10]), true},
   153  	{containsTestText, []byte(containsTestText[len(containsTestText)-20:]), true},
   154  	{containsTestText, []byte("notfound"), false},
   155  }
   156  
   157  // some corner cases
   158  var containsAdditionalTestData = []struct {
   159  	v1     string
   160  	v2     []byte
   161  	expect bool
   162  }{
   163  	{"", nil, false},
   164  	{"", []byte("a"), false},
   165  	{"a", []byte(""), false},
   166  	{"", []byte(""), false},
   167  }
   168  
   169  func TestReaderContains(t *testing.T) {
   170  	for i, this := range append(containsBenchTestData, containsAdditionalTestData...) {
   171  		result := ReaderContains(strings.NewReader(this.v1), this.v2)
   172  		if result != this.expect {
   173  			t.Errorf("[%d] got %t but expected %t", i, result, this.expect)
   174  		}
   175  	}
   176  
   177  	assert.False(t, ReaderContains(nil, []byte("a")))
   178  	assert.False(t, ReaderContains(nil, nil))
   179  }
   180  
   181  func TestGetTitleFunc(t *testing.T) {
   182  	title := "somewhere over the rainbow"
   183  	assert := require.New(t)
   184  
   185  	assert.Equal("Somewhere Over The Rainbow", GetTitleFunc("go")(title))
   186  	assert.Equal("Somewhere over the Rainbow", GetTitleFunc("chicago")(title), "Chicago style")
   187  	assert.Equal("Somewhere over the Rainbow", GetTitleFunc("Chicago")(title), "Chicago style")
   188  	assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("ap")(title), "AP style")
   189  	assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("ap")(title), "AP style")
   190  	assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("")(title), "AP style")
   191  	assert.Equal("Somewhere Over the Rainbow", GetTitleFunc("unknown")(title), "AP style")
   192  
   193  }
   194  
   195  func BenchmarkReaderContains(b *testing.B) {
   196  	b.ResetTimer()
   197  	for i := 0; i < b.N; i++ {
   198  		for i, this := range containsBenchTestData {
   199  			result := ReaderContains(strings.NewReader(this.v1), this.v2)
   200  			if result != this.expect {
   201  				b.Errorf("[%d] got %t but expected %t", i, result, this.expect)
   202  			}
   203  		}
   204  	}
   205  }
   206  
   207  func TestUniqueStrings(t *testing.T) {
   208  	in := []string{"a", "b", "a", "b", "c", "", "a", "", "d"}
   209  	output := UniqueStrings(in)
   210  	expected := []string{"a", "b", "c", "", "d"}
   211  	if !reflect.DeepEqual(output, expected) {
   212  		t.Errorf("Expected %#v, got %#v\n", expected, output)
   213  	}
   214  }
   215  
   216  func TestFindAvailablePort(t *testing.T) {
   217  	addr, err := FindAvailablePort()
   218  	assert.Nil(t, err)
   219  	assert.NotNil(t, addr)
   220  	assert.True(t, addr.Port > 0)
   221  }
   222  
   223  func TestFastMD5FromFile(t *testing.T) {
   224  	fs := afero.NewMemMapFs()
   225  
   226  	if err := afero.WriteFile(fs, "small.txt", []byte("abc"), 0777); err != nil {
   227  		t.Fatal(err)
   228  	}
   229  
   230  	if err := afero.WriteFile(fs, "small2.txt", []byte("abd"), 0777); err != nil {
   231  		t.Fatal(err)
   232  	}
   233  
   234  	if err := afero.WriteFile(fs, "bigger.txt", []byte(strings.Repeat("a bc d e", 100)), 0777); err != nil {
   235  		t.Fatal(err)
   236  	}
   237  
   238  	if err := afero.WriteFile(fs, "bigger2.txt", []byte(strings.Repeat("c d e f g", 100)), 0777); err != nil {
   239  		t.Fatal(err)
   240  	}
   241  
   242  	req := require.New(t)
   243  
   244  	sf1, err := fs.Open("small.txt")
   245  	req.NoError(err)
   246  	sf2, err := fs.Open("small2.txt")
   247  	req.NoError(err)
   248  
   249  	bf1, err := fs.Open("bigger.txt")
   250  	req.NoError(err)
   251  	bf2, err := fs.Open("bigger2.txt")
   252  	req.NoError(err)
   253  
   254  	defer sf1.Close()
   255  	defer sf2.Close()
   256  	defer bf1.Close()
   257  	defer bf2.Close()
   258  
   259  	m1, err := MD5FromFileFast(sf1)
   260  	req.NoError(err)
   261  	req.Equal("e9c8989b64b71a88b4efb66ad05eea96", m1)
   262  
   263  	m2, err := MD5FromFileFast(sf2)
   264  	req.NoError(err)
   265  	req.NotEqual(m1, m2)
   266  
   267  	m3, err := MD5FromFileFast(bf1)
   268  	req.NoError(err)
   269  	req.NotEqual(m2, m3)
   270  
   271  	m4, err := MD5FromFileFast(bf2)
   272  	req.NoError(err)
   273  	req.NotEqual(m3, m4)
   274  
   275  	m5, err := MD5FromFile(bf2)
   276  	req.NoError(err)
   277  	req.NotEqual(m4, m5)
   278  }
   279  
   280  func BenchmarkMD5FromFileFast(b *testing.B) {
   281  	fs := afero.NewMemMapFs()
   282  
   283  	for _, full := range []bool{false, true} {
   284  		b.Run(fmt.Sprintf("full=%t", full), func(b *testing.B) {
   285  			for i := 0; i < b.N; i++ {
   286  				b.StopTimer()
   287  				if err := afero.WriteFile(fs, "file.txt", []byte(strings.Repeat("1234567890", 2000)), 0777); err != nil {
   288  					b.Fatal(err)
   289  				}
   290  				f, err := fs.Open("file.txt")
   291  				if err != nil {
   292  					b.Fatal(err)
   293  				}
   294  				b.StartTimer()
   295  				if full {
   296  					if _, err := MD5FromFile(f); err != nil {
   297  						b.Fatal(err)
   298  					}
   299  				} else {
   300  					if _, err := MD5FromFileFast(f); err != nil {
   301  						b.Fatal(err)
   302  					}
   303  				}
   304  				f.Close()
   305  			}
   306  		})
   307  	}
   308  
   309  }