diff --git a/core/chaincode/platforms/golang/platform_test.go b/core/chaincode/platforms/golang/platform_test.go index 55b7567c067..4814ba7624a 100644 --- a/core/chaincode/platforms/golang/platform_test.go +++ b/core/chaincode/platforms/golang/platform_test.go @@ -23,6 +23,7 @@ import ( pb "github.com/hyperledger/fabric/protos/peer" "github.com/spf13/viper" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testerr(err error, succ bool) error { @@ -257,32 +258,52 @@ func TestValidateSpec(t *testing.T) { } } +func updateGopath(t *testing.T, path string) func() { + initialGopath, set := os.LookupEnv("GOPATH") + + if path == "" { + err := os.Unsetenv("GOPATH") + require.NoError(t, err) + } else { + err := os.Setenv("GOPATH", path) + require.NoError(t, err) + } + + if !set { + return func() { os.Unsetenv("GOPATH") } + } + return func() { os.Setenv("GOPATH", initialGopath) } +} + func TestGetDeploymentPayload(t *testing.T) { - emptyDir := fmt.Sprintf("pkg%d", os.Getpid()) - os.Mkdir(emptyDir, os.ModePerm) - defer os.Remove(emptyDir) + defaultGopath := os.Getenv("GOPATH") + testdataPath, err := filepath.Abs("testdata") + require.NoError(t, err) platform := &Platform{} var tests = []struct { - spec *pb.ChaincodeSpec - succ bool + gopath string + spec *pb.ChaincodeSpec + succ bool }{ - {spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/examples/chaincode/go/map"}}, succ: true}, - {spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/examples/bad/go/map"}}, succ: false}, - {spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/test/chaincodes/BadImport"}}, succ: false}, - {spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/test/chaincodes/BadMetadataInvalidIndex"}}, succ: false}, - {spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/test/chaincodes/BadMetadataUnexpectedFolderContent"}}, succ: false}, - {spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/test/chaincodes/BadMetadataIgnoreHiddenFile"}}, succ: true}, - {spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/core/chaincode/platforms/golang/" + emptyDir}}, succ: false}, + {gopath: defaultGopath, spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/examples/chaincode/go/map"}}, succ: true}, + {gopath: defaultGopath, spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "github.com/hyperledger/fabric/examples/bad/go/map"}}, succ: false}, + {gopath: testdataPath, spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "chaincodes/BadImport"}}, succ: false}, + {gopath: testdataPath, spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "chaincodes/BadMetadataInvalidIndex"}}, succ: false}, + {gopath: testdataPath, spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "chaincodes/BadMetadataUnexpectedFolderContent"}}, succ: false}, + {gopath: testdataPath, spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "chaincodes/BadMetadataIgnoreHiddenFile"}}, succ: true}, + {gopath: testdataPath, spec: &pb.ChaincodeSpec{ChaincodeId: &pb.ChaincodeID{Name: "Test Chaincode", Path: "chaincodes/empty/"}}, succ: false}, } for _, tst := range tests { + reset := updateGopath(t, tst.gopath) _, err := platform.GetDeploymentPayload(tst.spec) t.Log(err) if err = testerr(err, tst.succ); err != nil { t.Errorf("Error validating chaincode spec: %s, %s", tst.spec.ChaincodeId.Path, err) } + reset() } } diff --git a/test/chaincodes/BadImport/main.go b/core/chaincode/platforms/golang/testdata/src/chaincodes/BadImport/main.go similarity index 100% rename from test/chaincodes/BadImport/main.go rename to core/chaincode/platforms/golang/testdata/src/chaincodes/BadImport/main.go diff --git a/test/chaincodes/BadMetadataIgnoreHiddenFile/META-INF/.hiddenfile b/core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataIgnoreHiddenFile/META-INF/.hiddenfile similarity index 100% rename from test/chaincodes/BadMetadataIgnoreHiddenFile/META-INF/.hiddenfile rename to core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataIgnoreHiddenFile/META-INF/.hiddenfile diff --git a/test/chaincodes/BadMetadataIgnoreHiddenFile/main.go b/core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataIgnoreHiddenFile/main.go similarity index 100% rename from test/chaincodes/BadMetadataIgnoreHiddenFile/main.go rename to core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataIgnoreHiddenFile/main.go diff --git a/test/chaincodes/BadMetadataInvalidIndex/META-INF/statedb/couchdb/indexes/bad.json b/core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataInvalidIndex/META-INF/statedb/couchdb/indexes/bad.json similarity index 100% rename from test/chaincodes/BadMetadataInvalidIndex/META-INF/statedb/couchdb/indexes/bad.json rename to core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataInvalidIndex/META-INF/statedb/couchdb/indexes/bad.json diff --git a/test/chaincodes/BadMetadataInvalidIndex/main.go b/core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataInvalidIndex/main.go similarity index 100% rename from test/chaincodes/BadMetadataInvalidIndex/main.go rename to core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataInvalidIndex/main.go diff --git a/test/chaincodes/BadMetadataUnexpectedFolderContent/META-INF/unsupported metadata location.json b/core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataUnexpectedFolderContent/META-INF/unsupported_metadata_ocation.json similarity index 100% rename from test/chaincodes/BadMetadataUnexpectedFolderContent/META-INF/unsupported metadata location.json rename to core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataUnexpectedFolderContent/META-INF/unsupported_metadata_ocation.json diff --git a/test/chaincodes/BadMetadataUnexpectedFolderContent/main.go b/core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataUnexpectedFolderContent/main.go similarity index 100% rename from test/chaincodes/BadMetadataUnexpectedFolderContent/main.go rename to core/chaincode/platforms/golang/testdata/src/chaincodes/BadMetadataUnexpectedFolderContent/main.go diff --git a/core/container/util/testdata/BadMetadataInvalidIndex/META-INF/statedb/couchdb/indexes/bad.json b/core/container/util/testdata/BadMetadataInvalidIndex/META-INF/statedb/couchdb/indexes/bad.json new file mode 100644 index 00000000000..ff811658569 --- /dev/null +++ b/core/container/util/testdata/BadMetadataInvalidIndex/META-INF/statedb/couchdb/indexes/bad.json @@ -0,0 +1 @@ +This test file is expected to contain a json formatted couchdb index, but does not. It should fail golang chaincode packaging tests. diff --git a/core/container/util/testdata/BadMetadataUnexpectedFolderContent/META-INF/unsupported_metadata_location.json b/core/container/util/testdata/BadMetadataUnexpectedFolderContent/META-INF/unsupported_metadata_location.json new file mode 100644 index 00000000000..26a21ebc8ac --- /dev/null +++ b/core/container/util/testdata/BadMetadataUnexpectedFolderContent/META-INF/unsupported_metadata_location.json @@ -0,0 +1 @@ +This test file is located at an unexpected metadata location under META-INF. It should fail golang chaincode packaging tests. diff --git a/core/container/util/testdata/BadMetadataUnexpectedFolderContent/main.go b/core/container/util/testdata/BadMetadataUnexpectedFolderContent/main.go new file mode 100644 index 00000000000..d7818abf719 --- /dev/null +++ b/core/container/util/testdata/BadMetadataUnexpectedFolderContent/main.go @@ -0,0 +1,7 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + +package main diff --git a/core/container/util/testdata/sourcefiles/META-INF/.hiddenfile b/core/container/util/testdata/sourcefiles/META-INF/.hiddenfile new file mode 100644 index 00000000000..8da4582dce6 --- /dev/null +++ b/core/container/util/testdata/sourcefiles/META-INF/.hiddenfile @@ -0,0 +1 @@ +# this is a hidden file diff --git a/core/container/util/testdata/sourcefiles/META-INF/statedb/couchdb/indexes/indexOwner.json b/core/container/util/testdata/sourcefiles/META-INF/statedb/couchdb/indexes/indexOwner.json new file mode 100644 index 00000000000..305f0904446 --- /dev/null +++ b/core/container/util/testdata/sourcefiles/META-INF/statedb/couchdb/indexes/indexOwner.json @@ -0,0 +1 @@ +{"index":{"fields":["docType","owner"]},"ddoc":"indexOwnerDoc", "name":"indexOwner","type":"json"} diff --git a/core/container/util/testdata/sourcefiles/artifact.xml b/core/container/util/testdata/sourcefiles/artifact.xml new file mode 100644 index 00000000000..11cf4c3fc02 --- /dev/null +++ b/core/container/util/testdata/sourcefiles/artifact.xml @@ -0,0 +1,6 @@ + +true diff --git a/core/container/util/testdata/sourcefiles/src/Hello.class b/core/container/util/testdata/sourcefiles/src/Hello.class new file mode 100644 index 00000000000..3e673010208 --- /dev/null +++ b/core/container/util/testdata/sourcefiles/src/Hello.class @@ -0,0 +1 @@ +# This is a file that should not be included in java packages diff --git a/core/container/util/testdata/sourcefiles/src/Hello.java b/core/container/util/testdata/sourcefiles/src/Hello.java new file mode 100644 index 00000000000..ee3ff42e404 --- /dev/null +++ b/core/container/util/testdata/sourcefiles/src/Hello.java @@ -0,0 +1,12 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 + */ + +public class Hello { + public static void main(String []args) { + System.out.println("Hello"); + System.exit(0); + } +} diff --git a/core/container/util/testdata/sourcefiles/src/main.go b/core/container/util/testdata/sourcefiles/src/main.go new file mode 100644 index 00000000000..d7818abf719 --- /dev/null +++ b/core/container/util/testdata/sourcefiles/src/main.go @@ -0,0 +1,7 @@ +/* +Copyright IBM Corp. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 +*/ + +package main diff --git a/core/container/util/writer_test.go b/core/container/util/writer_test.go index 0c13a324715..b654d5007b0 100644 --- a/core/container/util/writer_test.go +++ b/core/container/util/writer_test.go @@ -10,7 +10,6 @@ import ( "archive/tar" "bytes" "compress/gzip" - "fmt" "io" "io/ioutil" "os" @@ -18,68 +17,75 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_WriteFileToPackage(t *testing.T) { + tempDir, err := ioutil.TempDir("", "utiltest") + require.NoError(t, err) + defer os.RemoveAll(tempDir) + buf := bytes.NewBuffer(nil) gw := gzip.NewWriter(buf) tw := tar.NewWriter(gw) - err := WriteFileToPackage("blah", "", tw) + err = WriteFileToPackage("blah", "", tw) assert.Error(t, err, "Expected error writing non existent file to package") // Create a file and write it to tar writer filename := "test.txt" filecontent := "hello" - filepath := os.TempDir() + filename - err = ioutil.WriteFile(filepath, bytes.NewBufferString(filecontent).Bytes(), 0600) - assert.NoError(t, err, "Error creating file %s", filepath) - defer os.Remove(filepath) + filePath := filepath.Join(tempDir, filename) + err = ioutil.WriteFile(filePath, bytes.NewBufferString(filecontent).Bytes(), 0600) + require.NoError(t, err, "Error creating file %s", filePath) - err = WriteFileToPackage(filepath, filename, tw) + err = WriteFileToPackage(filePath, filename, tw) assert.NoError(t, err, "Error returned by WriteFileToPackage while writing existing file") tw.Close() gw.Close() + // tar writer is closed. Call WriteFileToPackage again, this should + // return an error + err = WriteFileToPackage(filePath, "", tw) + assert.Error(t, err, "Expected error writing using a closed writer") + // Read the file from the archive and check the name and file content r := bytes.NewReader(buf.Bytes()) - gr, err1 := gzip.NewReader(r) + gr, err := gzip.NewReader(r) + require.NoError(t, err, "Error creating a gzip reader") defer gr.Close() - assert.NoError(t, err1, "Error creating a gzip reader") + tr := tar.NewReader(gr) - header, err2 := tr.Next() - assert.NoError(t, err2, "Error getting the file from the tar") - assert.Equal(t, filename, header.Name, - "Name of the file read from the archive is not same as the file added to the archive") + header, err := tr.Next() + require.NoError(t, err, "Error getting the file from the tar") + assert.Equal(t, filename, header.Name, "filename read from archive does not match what was added") b := make([]byte, 5) - _, err3 := tr.Read(b) - assert.NoError(t, err3, "Error reading file from the archive") - assert.Equal(t, filecontent, bytes.NewBuffer(b).String(), - "file content from the archive is not same as original file content") - - // tar writer is closed. Call WriteFileToPackage again, this should - // return an error - err = WriteFileToPackage(filepath, "", tw) - fmt.Println(err) - assert.Error(t, err, "Expected error writing using a closed writer") + n, err := tr.Read(b) + assert.Equal(t, 5, n) + assert.True(t, err == nil || err == io.EOF, "Error reading file from the archive") // go1.10 returns io.EOF + assert.Equal(t, filecontent, string(b), "file content from archive does not equal original content") } func Test_WriteStreamToPackage(t *testing.T) { + tempDir, err := ioutil.TempDir("", "utiltest") + require.NoError(t, err) + defer os.RemoveAll(tempDir) + tarw := tar.NewWriter(bytes.NewBuffer(nil)) input := bytes.NewReader([]byte("hello")) // Error case 1 - err := WriteStreamToPackage(nil, "/nonexistentpath", "", tarw) + err = WriteStreamToPackage(nil, "nonexistentpath", "", tarw) assert.Error(t, err, "Expected error getting info of non existent file") // Error case 2 - err = WriteStreamToPackage(input, os.TempDir(), "", tarw) + err = WriteStreamToPackage(input, tempDir, "", tarw) assert.Error(t, err, "Expected error copying to the tar writer (tarw)") tarw.Close() // Error case 3 - err = WriteStreamToPackage(input, os.TempDir(), "", tarw) + err = WriteStreamToPackage(input, tempDir, "", tarw) assert.Error(t, err, "Expected error copying to closed tar writer (tarw)") // Success case @@ -90,19 +96,18 @@ func Test_WriteStreamToPackage(t *testing.T) { // Create a file and write it to tar writer filename := "test.txt" filecontent := "hello" - filepath := os.TempDir() + filename - err = ioutil.WriteFile(filepath, bytes.NewBufferString(filecontent).Bytes(), 0600) - assert.NoError(t, err, "Error creating file %s", filepath) - defer os.Remove(filepath) + filePath := filepath.Join(tempDir, filename) + err = ioutil.WriteFile(filePath, bytes.NewBufferString(filecontent).Bytes(), 0600) + assert.NoError(t, err, "Error creating file %s", filePath) // Read the file into a stream var b []byte - b, err = ioutil.ReadFile(filepath) - assert.NoError(t, err, "Error reading file %s", filepath) + b, err = ioutil.ReadFile(filePath) + assert.NoError(t, err, "Error reading file %s", filePath) is := bytes.NewReader(b) // Write contents of the file stream to tar writer - err = WriteStreamToPackage(is, filepath, filename, tw) + err = WriteStreamToPackage(is, filePath, filename, tw) assert.NoError(t, err, "Error copying file to the tar writer (tw)") // Close the writers @@ -111,220 +116,107 @@ func Test_WriteStreamToPackage(t *testing.T) { // Read the file from the archive and check the name and file content br := bytes.NewReader(buf.Bytes()) - gr, err1 := gzip.NewReader(br) + gr, err := gzip.NewReader(br) defer gr.Close() - assert.NoError(t, err1, "Error creating a gzip reader") + assert.NoError(t, err, "Error creating a gzip reader") tr := tar.NewReader(gr) - header, err2 := tr.Next() - assert.NoError(t, err2, "Error getting the file from the tar") - assert.Equal(t, filename, header.Name, - "Name of the file read from the archive is not same as the file added to the archive") + header, err := tr.Next() + assert.NoError(t, err, "Error getting the file from the tar") + assert.Equal(t, filename, header.Name, "filename read from archive does not match what was added") b1 := make([]byte, 5) - _, err3 := tr.Read(b1) - assert.NoError(t, err3, "Error reading file from the archive") - assert.Equal(t, filecontent, bytes.NewBuffer(b1).String(), - "file content from the archive is not same as original file content") + n, err := tr.Read(b1) + assert.Equal(t, 5, n) + assert.True(t, err == nil || err == io.EOF, "Error reading file from the archive") // go1.10 returns io.EOF + assert.Equal(t, filecontent, string(b), "file content from archive does not equal original content") } -// Success case 1: with include and exclude file types and without exclude dir +// Success case 1: with include file types and without exclude dir func Test_WriteFolderToTarPackage1(t *testing.T) { - - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/examples/chaincode/java/SimpleSample") - filePath := "src/src/main/java/example/SimpleSample.java" + srcPath := filepath.Join("testdata", "sourcefiles") + filePath := "src/src/Hello.java" includeFileTypes := map[string]bool{ ".java": true, } - excludeFileTypes := map[string]bool{ - ".xml": true, - } + excludeFileTypes := map[string]bool{} tarBytes := createTestTar(t, srcPath, "", includeFileTypes, excludeFileTypes) // Read the file from the archive and check the name - br := bytes.NewReader(tarBytes) - gr, err1 := gzip.NewReader(br) - defer gr.Close() - assert.NoError(t, err1, "Error creating a gzip reader") - tr := tar.NewReader(gr) - header, err2 := tr.Next() - assert.NoError(t, err2, "Error getting the file from the tar") - assert.Equal(t, filePath, header.Name, - "Name of the file read from the archive is not same as the file added to the archive") + entries := tarContents(t, tarBytes) + assert.ElementsMatch(t, []string{filePath}, entries, "archive should only contain one file") } // Success case 2: with exclude dir and no include file types func Test_WriteFolderToTarPackage2(t *testing.T) { + srcPath := filepath.Join("testdata", "sourcefiles") + tarBytes := createTestTar(t, srcPath, "src", nil, nil) - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/examples/chaincode/java") - excludeFileTypes := map[string]bool{ - ".xml": true, - } - - createTestTar(t, srcPath, "SimpleSample", nil, excludeFileTypes) + entries := tarContents(t, tarBytes) + assert.ElementsMatch(t, []string{"src/artifact.xml", "META-INF/statedb/couchdb/indexes/indexOwner.json"}, entries) } // Success case 3: with chaincode metadata in META-INF directory func Test_WriteFolderToTarPackage3(t *testing.T) { - - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - // Note - go chaincode does not use WriteFolderToTarPackage(), - // but we can still use the go example for unit test, - // since there are no node chaincode examples in fabric repos - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/examples/chaincode/go/marbles02") + srcPath := filepath.Join("testdata", "sourcefiles") filePath := "META-INF/statedb/couchdb/indexes/indexOwner.json" tarBytes := createTestTar(t, srcPath, "", nil, nil) // Read the files from the archive and check for the metadata index file - br := bytes.NewReader(tarBytes) - gr, err := gzip.NewReader(br) - defer gr.Close() - assert.NoError(t, err, "Error creating a gzip reader") - tr := tar.NewReader(gr) - var foundIndexArtifact bool - for { - header, err := tr.Next() - if err == io.EOF { // No more entries - break - } - assert.NoError(t, err, "Error getting Next() file in tar") - t.Logf("Found file in tar: %s", header.Name) - if header.Name == filePath { - foundIndexArtifact = true - break - } - } - assert.True(t, foundIndexArtifact, "should have found statedb index artifact in marbles02 META-INF directory") + entries := tarContents(t, tarBytes) + assert.Contains(t, entries, filePath, "should have found statedb index artifact in META-INF directory") } // Success case 4: with chaincode metadata in META-INF directory, pass trailing slash in srcPath func Test_WriteFolderToTarPackage4(t *testing.T) { - - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - // Note - go chaincode does not use WriteFolderToTarPackage(), - // but we can still use the go example for unit test, - // since there are no node chaincode examples in fabric repos - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/examples/chaincode/go/marbles02") - srcPath = srcPath + "/" + srcPath := filepath.Join("testdata", "sourcefiles") + string(filepath.Separator) filePath := "META-INF/statedb/couchdb/indexes/indexOwner.json" tarBytes := createTestTar(t, srcPath, "", nil, nil) // Read the files from the archive and check for the metadata index file - br := bytes.NewReader(tarBytes) - gr, err := gzip.NewReader(br) - defer gr.Close() - assert.NoError(t, err, "Error creating a gzip reader") - tr := tar.NewReader(gr) - var foundIndexArtifact bool - for { - header, err := tr.Next() - if err == io.EOF { // No more entries - break - } - assert.NoError(t, err, "Error getting Next() file in tar") - t.Logf("Found file in tar: %s", header.Name) - if header.Name == filePath { - foundIndexArtifact = true - break - } - } - assert.True(t, foundIndexArtifact, "should have found statedb index artifact in marbles02 META-INF directory") + entries := tarContents(t, tarBytes) + assert.Contains(t, entries, filePath, "should have found statedb index artifact in META-INF directory") } // Success case 5: with hidden files in META-INF directory (hidden files get ignored) func Test_WriteFolderToTarPackage5(t *testing.T) { - - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/test/chaincodes/BadMetadataIgnoreHiddenFile") - + srcPath := filepath.Join("testdata", "sourcefiles") filePath := "META-INF/.hiddenfile" - tarBytes := createTestTar(t, srcPath, "", nil, nil) - - // Read the files from the archive and check for no hidden files - br := bytes.NewReader(tarBytes) - gr, err := gzip.NewReader(br) - defer gr.Close() - assert.NoError(t, err, "Error creating a gzip reader") - tr := tar.NewReader(gr) - for { - header, err := tr.Next() - if err == io.EOF { // No more entries - break - } - assert.NoError(t, err, "Error getting Next() file in tar") - t.Logf("Found file in tar: %s", header.Name) - assert.NotEqual(t, filePath, header.Name, "should not have found hidden file META-INF/.hiddenfile") - } -} - -func createTestTar(t *testing.T, srcPath string, excludeDir string, includeFileTypeMap map[string]bool, excludeFileTypeMap map[string]bool) []byte { - buf := bytes.NewBuffer(nil) - gw := gzip.NewWriter(buf) - tw := tar.NewWriter(gw) + assert.FileExists(t, filepath.Join(srcPath, "META-INF", ".hiddenfile")) - err := WriteFolderToTarPackage(tw, srcPath, "", includeFileTypeMap, excludeFileTypeMap) - assert.NoError(t, err, "Error writing folder to package") + tarBytes := createTestTar(t, srcPath, "", nil, nil) - tw.Close() - gw.Close() - return buf.Bytes() + // Read the files from the archive and check for the metadata index file + entries := tarContents(t, tarBytes) + assert.NotContains(t, entries, filePath, "should not contain .hiddenfile in META-INF directory") } // Failure case 1: no files in directory func Test_WriteFolderToTarPackageFailure1(t *testing.T) { - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/core/container/util", - fmt.Sprintf("%d", os.Getpid())) - os.Mkdir(srcPath, os.ModePerm) - defer os.Remove(srcPath) + srcPath, err := ioutil.TempDir("", "utiltest") + require.NoError(t, err) + defer os.RemoveAll(srcPath) tw := tar.NewWriter(bytes.NewBuffer(nil)) defer tw.Close() - err := WriteFolderToTarPackage(tw, srcPath, "", nil, nil) + + err = WriteFolderToTarPackage(tw, srcPath, "", nil, nil) assert.Contains(t, err.Error(), "no source files found") } // Failure case 2: with invalid chaincode metadata in META-INF directory func Test_WriteFolderToTarPackageFailure2(t *testing.T) { - - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - // Note - go chaincode does not use WriteFolderToTarPackage(), - // but we can still use the go example for unit test, - // since there are no node chaincode examples in fabric repos - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/test/chaincodes/BadMetadataInvalidIndex") - + srcPath := filepath.Join("testdata", "BadMetadataInvalidIndex") buf := bytes.NewBuffer(nil) gw := gzip.NewWriter(buf) tw := tar.NewWriter(gw) err := WriteFolderToTarPackage(tw, srcPath, "", nil, nil) assert.Error(t, err, "Should have received error writing folder to package") + assert.Contains(t, err.Error(), "file [bad.json] is not a valid JSON") tw.Close() gw.Close() @@ -332,22 +224,14 @@ func Test_WriteFolderToTarPackageFailure2(t *testing.T) { // Failure case 3: with unexpected content in META-INF directory func Test_WriteFolderToTarPackageFailure3(t *testing.T) { - - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - - // Note - go chaincode does not use WriteFolderToTarPackage(), - // but we can still use the go example for unit test, - // since there are no node chaincode examples in fabric repos - srcPath := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/test/chaincodes/BadMetadataUnexpectedFolderContent") - + srcPath := filepath.Join("testdata", "BadMetadataUnexpectedFolderContent") buf := bytes.NewBuffer(nil) gw := gzip.NewWriter(buf) tw := tar.NewWriter(gw) err := WriteFolderToTarPackage(tw, srcPath, "", nil, nil) assert.Error(t, err, "Should have received error writing folder to package") + assert.Contains(t, err.Error(), "Metadata not supported in directory: META-INF") tw.Close() gw.Close() @@ -358,18 +242,24 @@ func Test_WriteJavaProjectToPackage(t *testing.T) { gw := gzip.NewWriter(inputbuf) tw := tar.NewWriter(gw) - gopath := os.Getenv("GOPATH") - gopath = filepath.SplitList(gopath)[0] - pkgDir := filepath.Join(gopath, "src", - "github.com/hyperledger/fabric/examples/chaincode/java") - err := WriteJavaProjectToPackage(tw, pkgDir) + srcPath := filepath.Join("testdata", "sourcefiles") + assert.FileExists(t, filepath.Join(srcPath, "src", "Hello.class")) + + err := WriteJavaProjectToPackage(tw, srcPath) assert.NoError(t, err, "Error writing java project to package") // Close the tar writer and call WriteFileToPackage again, this should // return an error tw.Close() gw.Close() - err = WriteJavaProjectToPackage(tw, pkgDir) + + entries := tarContents(t, inputbuf.Bytes()) + assert.Contains(t, entries, "META-INF/statedb/couchdb/indexes/indexOwner.json") + assert.Contains(t, entries, "src/artifact.xml") + assert.Contains(t, entries, "src/src/Hello.java") + assert.NotContains(t, entries, "src/src/Hello.class") + + err = WriteJavaProjectToPackage(tw, srcPath) assert.Error(t, err, "WriteJavaProjectToPackage was called with closed writer, should have failed") } @@ -380,3 +270,37 @@ func Test_WriteBytesToPackage(t *testing.T) { err := WriteBytesToPackage("foo", []byte("blah"), tw) assert.NoError(t, err, "Error writing bytes to package") } + +func createTestTar(t *testing.T, srcPath string, excludeDir string, includeFileTypeMap map[string]bool, excludeFileTypeMap map[string]bool) []byte { + buf := bytes.NewBuffer(nil) + gw := gzip.NewWriter(buf) + tw := tar.NewWriter(gw) + + err := WriteFolderToTarPackage(tw, srcPath, excludeDir, includeFileTypeMap, excludeFileTypeMap) + assert.NoError(t, err, "Error writing folder to package") + + tw.Close() + gw.Close() + return buf.Bytes() +} + +func tarContents(t *testing.T, buf []byte) []string { + br := bytes.NewReader(buf) + gr, err := gzip.NewReader(br) + require.NoError(t, err) + defer gr.Close() + + tr := tar.NewReader(gr) + + var entries []string + for { + header, err := tr.Next() + if err == io.EOF { // No more entries + break + } + require.NoError(t, err, "failed to get next entry") + entries = append(entries, header.Name) + } + + return entries +}