Source file src/embed/internal/embedtest/embedx_test.go

     1  // Copyright 2020 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package embedtest_test
     6  
     7  import (
     8  	"embed"
     9  	"os"
    10  	"testing"
    11  )
    12  
    13  var (
    14  	global2      = global
    15  	concurrency2 = concurrency
    16  	glass2       = glass
    17  	sbig2        = sbig
    18  	bbig2        = bbig
    19  )
    20  
    21  //go:embed testdata/*.txt
    22  var global embed.FS
    23  
    24  //go:embed c*txt
    25  var concurrency string
    26  
    27  //go:embed testdata/g*.txt
    28  var glass []byte
    29  
    30  //go:embed testdata/ascii.txt
    31  var sbig string
    32  
    33  //go:embed testdata/ascii.txt
    34  var bbig []byte
    35  
    36  func testFiles(t *testing.T, f embed.FS, name, data string) {
    37  	t.Helper()
    38  	d, err := f.ReadFile(name)
    39  	if err != nil {
    40  		t.Error(err)
    41  		return
    42  	}
    43  	if string(d) != data {
    44  		t.Errorf("read %v = %q, want %q", name, d, data)
    45  	}
    46  }
    47  
    48  func testString(t *testing.T, s, name, data string) {
    49  	t.Helper()
    50  	if s != data {
    51  		t.Errorf("%v = %q, want %q", name, s, data)
    52  	}
    53  }
    54  
    55  func TestXGlobal(t *testing.T) {
    56  	testFiles(t, global, "testdata/hello.txt", "hello, world\n")
    57  	testString(t, concurrency, "concurrency", "Concurrency is not parallelism.\n")
    58  	testString(t, string(glass), "glass", "I can eat glass and it doesn't hurt me.\n")
    59  	testString(t, concurrency2, "concurrency2", "Concurrency is not parallelism.\n")
    60  	testString(t, string(glass2), "glass2", "I can eat glass and it doesn't hurt me.\n")
    61  
    62  	big, err := os.ReadFile("testdata/ascii.txt")
    63  	if err != nil {
    64  		t.Fatal(err)
    65  	}
    66  	testString(t, sbig, "sbig", string(big))
    67  	testString(t, sbig2, "sbig2", string(big))
    68  	testString(t, string(bbig), "bbig", string(big))
    69  	testString(t, string(bbig2), "bbig", string(big))
    70  
    71  	if t.Failed() {
    72  		return
    73  	}
    74  
    75  	// Could check &glass[0] == &glass2[0] but also want to make sure write does not fault
    76  	// (data must not be in read-only memory).
    77  	old := glass[0]
    78  	glass[0]++
    79  	if glass2[0] != glass[0] {
    80  		t.Fatalf("glass and glass2 do not share storage")
    81  	}
    82  	glass[0] = old
    83  
    84  	// Could check &bbig[0] == &bbig2[0] but also want to make sure write does not fault
    85  	// (data must not be in read-only memory).
    86  	old = bbig[0]
    87  	bbig[0]++
    88  	if bbig2[0] != bbig[0] {
    89  		t.Fatalf("bbig and bbig2 do not share storage")
    90  	}
    91  	bbig[0] = old
    92  }
    93  

View as plain text