vfsgen icon indicating copy to clipboard operation
vfsgen copied to clipboard

Can't access assets outside of the package

Open cmoulliard opened this issue 6 years ago • 1 comments

The assets var populated within a generated vfs go file can only be accessed within the same package

Generated file name is : vfsdata.go

package template

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	pathpkg "path"
	"time"
)

// assets statically implements the virtual filesystem provided to vfsgen.
var assets = func() http.FileSystem {
	fs := vfsgen۰FS{
		"/": &vfsgen۰DirInfo{
			name:    "/",
			modTime: time.Date(2018, 8, 16, 7, 18, 33, 728614945, time.UTC),
		},
		"/rest": &vfsgen۰DirInfo{
			name:    "rest",
			modTime: time.Date(2018, 8, 16, 7, 18, 33, 726532235, time.UTC),
		},
        ...
	return fs
}()

If I would like to define a Go test class to test it, then I can't access the assets var

package template_test

import (
	"os"
	"fmt"

	"github.com/shurcooL/httpfs/vfsutil"
	"testing"
	"github.com/snowdrop/k8s-supervisor/pkg/template"
	"net/http"
)

var (
	templateFiles   []string
	project         = "simple"
)

func TestVfsSimpleJavaProject(t *testing.T) {
	tExpectedFiles := []string {
		"simple/pom.xml",
		"simple/src/main/java/dummy/DemoApplication.java",
		"simple/src/main/resources/application.properties",
	}

	tFiles := walkTree()

	for i := range tExpectedFiles {
		if tExpectedFiles[i] != tFiles[i] {
			t.Errorf("Template was incorrect, got: '%s', want: '%s'.", tFiles[i], tExpectedFiles[i])
		}
	}
}

func walkTree() []string {
	var fs http.FileSystem = template.assets
...

Error:

go test pkg/template/template_java_test.go -v
# command-line-arguments_test
pkg/template/template_java_test.go:35:27: cannot refer to unexported name template.assets
pkg/template/template_java_test.go:35:27: undefined: template.assets

Is there a workaround ?

cmoulliard avatar Aug 16 '18 10:08 cmoulliard

How are you generating vfsdata.go?

If you want your assets variable to be accessible outside the template package, you need to make it exported, i.e., Assets.

If all you want is to be able to access assets from the template package tests, you could use internal tests rather than external. In other words, change package template_test to package template and access the assets variable directly. See https://golang.org/cmd/go/#hdr-Test_packages for more info about Go tests.

dmitshur avatar Aug 16 '18 13:08 dmitshur