From 147a219e2099658c689179111182f5a806ba8491 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Tue, 12 Jul 2022 15:30:43 -0400 Subject: [PATCH 1/8] Perform Ethereum contract deploy from suite instead of run.sh Signed-off-by: Andrew Richardson --- test/e2e/gateway/ethereum_contract_test.go | 21 +++++++++++++------ test/e2e/multiparty/ethereum_contract_test.go | 19 +++++++++++------ test/e2e/run.sh | 4 ---- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/test/e2e/gateway/ethereum_contract_test.go b/test/e2e/gateway/ethereum_contract_test.go index e00349ce4..a189b2833 100644 --- a/test/e2e/gateway/ethereum_contract_test.go +++ b/test/e2e/gateway/ethereum_contract_test.go @@ -19,7 +19,8 @@ package gateway import ( "encoding/json" "fmt" - "os" + "os/exec" + "testing" "github.com/aidarkhanov/nanoid" "github.com/go-resty/resty/v2" @@ -27,6 +28,7 @@ import ( "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -106,6 +108,17 @@ func simpleStorageFFIGet() *fftypes.FFIMethod { } } +func deployContract(t *testing.T, stackName, contract string) string { + out, err := exec.Command("ff", "deploy", "ethereum", stackName, "../../data/contracts/"+contract).Output() + require.NoError(t, err) + var output map[string]interface{} + err = json.Unmarshal(out, &output) + require.NoError(t, err) + address := output["address"].(string) + t.Logf("Contract address: %s", address) + return address +} + type EthereumContractTestSuite struct { suite.Suite testState *testState @@ -123,11 +136,7 @@ func (suite *EthereumContractTestSuite) SetupSuite() { suite.ethClient.SetBaseURL(fmt.Sprintf("http://localhost:%d", stack.Members[0].ExposedConnectorPort)) account := stackState.Accounts[0].(map[string]interface{}) suite.ethIdentity = account["address"].(string) - suite.contractAddress = os.Getenv("CONTRACT_ADDRESS") - if suite.contractAddress == "" { - suite.T().Fatal("CONTRACT_ADDRESS must be set") - } - suite.T().Logf("contractAddress: %s", suite.contractAddress) + suite.contractAddress = deployContract(suite.T(), stack.Name, "simplestorage/simple_storage.json") res, err := e2e.CreateFFI(suite.T(), suite.testState.client1, simpleStorageFFI()) suite.interfaceID = fftypes.MustParseUUID(res.(map[string]interface{})["id"].(string)) diff --git a/test/e2e/multiparty/ethereum_contract_test.go b/test/e2e/multiparty/ethereum_contract_test.go index 7954eac38..fb5de8643 100644 --- a/test/e2e/multiparty/ethereum_contract_test.go +++ b/test/e2e/multiparty/ethereum_contract_test.go @@ -19,7 +19,8 @@ package multiparty import ( "encoding/json" "fmt" - "os" + "os/exec" + "testing" "github.com/aidarkhanov/nanoid" "github.com/go-resty/resty/v2" @@ -27,6 +28,7 @@ import ( "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" ) @@ -106,6 +108,15 @@ func simpleStorageFFIGet() *fftypes.FFIMethod { } } +func deployContract(t *testing.T, stackName string) string { + out, err := exec.Command("ff", "deploy", "ethereum", stackName, "../../data/simplestorage/simple_storage.json").Output() + require.NoError(t, err) + var output map[string]interface{} + err = json.Unmarshal(out, &output) + require.NoError(t, err) + return output["address"].(string) +} + type EthereumContractTestSuite struct { suite.Suite testState *testState @@ -121,11 +132,7 @@ func (suite *EthereumContractTestSuite) SetupSuite() { suite.ethClient = e2e.NewResty(suite.T()) suite.ethClient.SetBaseURL(fmt.Sprintf("http://localhost:%d", stack.Members[0].ExposedConnectorPort)) suite.ethIdentity = suite.testState.org1key.Value - suite.contractAddress = os.Getenv("CONTRACT_ADDRESS") - if suite.contractAddress == "" { - suite.T().Fatal("CONTRACT_ADDRESS must be set") - } - suite.T().Logf("contractAddress: %s", suite.contractAddress) + suite.contractAddress = deployContract(suite.T(), stack.Name) res, err := e2e.CreateFFI(suite.T(), suite.testState.client1, simpleStorageFFI()) suite.interfaceID = fftypes.MustParseUUID(res.(map[string]interface{})["id"].(string)) diff --git a/test/e2e/run.sh b/test/e2e/run.sh index 8ba56d6c6..42939c34d 100755 --- a/test/e2e/run.sh +++ b/test/e2e/run.sh @@ -124,10 +124,6 @@ if [ "$CREATE_STACK" == "true" ]; then checkOk $? fi -if [ "$TEST_SUITE" == "TestEthereumMultipartyE2ESuite" ] || [ "$TEST_SUITE" == "TestEthereumGatewayE2ESuite" ]; then - export CONTRACT_ADDRESS=$($CLI deploy ethereum $STACK_NAME ../data/simplestorage/simple_storage.json | jq -r '.address') -fi - create_accounts $CLI info $STACK_NAME From 44207eaf40618049546d4fc7e120f4cfa56e5a98 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Tue, 12 Jul 2022 16:38:31 -0400 Subject: [PATCH 2/8] Group test contracts into a folder Signed-off-by: Andrew Richardson --- test/data/{ => contracts}/assetcreator/assetCreator.go | 0 .../assetcreator/chaincode/smartcontract.go | 0 test/data/{ => contracts}/assetcreator/go.mod | 0 test/data/{ => contracts}/assetcreator/go.sum | 0 .../{ => contracts}/simplestorage/simple_storage.json | 0 test/e2e/deploy_chaincode.sh | 2 +- test/e2e/multiparty/ethereum_contract_test.go | 10 ++++++---- 7 files changed, 7 insertions(+), 5 deletions(-) rename test/data/{ => contracts}/assetcreator/assetCreator.go (100%) rename test/data/{ => contracts}/assetcreator/chaincode/smartcontract.go (100%) rename test/data/{ => contracts}/assetcreator/go.mod (100%) rename test/data/{ => contracts}/assetcreator/go.sum (100%) rename test/data/{ => contracts}/simplestorage/simple_storage.json (100%) diff --git a/test/data/assetcreator/assetCreator.go b/test/data/contracts/assetcreator/assetCreator.go similarity index 100% rename from test/data/assetcreator/assetCreator.go rename to test/data/contracts/assetcreator/assetCreator.go diff --git a/test/data/assetcreator/chaincode/smartcontract.go b/test/data/contracts/assetcreator/chaincode/smartcontract.go similarity index 100% rename from test/data/assetcreator/chaincode/smartcontract.go rename to test/data/contracts/assetcreator/chaincode/smartcontract.go diff --git a/test/data/assetcreator/go.mod b/test/data/contracts/assetcreator/go.mod similarity index 100% rename from test/data/assetcreator/go.mod rename to test/data/contracts/assetcreator/go.mod diff --git a/test/data/assetcreator/go.sum b/test/data/contracts/assetcreator/go.sum similarity index 100% rename from test/data/assetcreator/go.sum rename to test/data/contracts/assetcreator/go.sum diff --git a/test/data/simplestorage/simple_storage.json b/test/data/contracts/simplestorage/simple_storage.json similarity index 100% rename from test/data/simplestorage/simple_storage.json rename to test/data/contracts/simplestorage/simple_storage.json diff --git a/test/e2e/deploy_chaincode.sh b/test/e2e/deploy_chaincode.sh index 9595eba77..8298a4071 100755 --- a/test/e2e/deploy_chaincode.sh +++ b/test/e2e/deploy_chaincode.sh @@ -11,7 +11,7 @@ if [ -z "$CHAINCODE_NAME" ]; then fi TEST_DIR="$(cd "$(dirname $0)/.." && pwd)" -CHAINCODE="$TEST_DIR/data/assetcreator" +CHAINCODE="$TEST_DIR/data/contracts/assetcreator" CHAINCODE_VERSION=1.0 CHANNEL=firefly diff --git a/test/e2e/multiparty/ethereum_contract_test.go b/test/e2e/multiparty/ethereum_contract_test.go index fb5de8643..bf1cfbcf2 100644 --- a/test/e2e/multiparty/ethereum_contract_test.go +++ b/test/e2e/multiparty/ethereum_contract_test.go @@ -108,13 +108,15 @@ func simpleStorageFFIGet() *fftypes.FFIMethod { } } -func deployContract(t *testing.T, stackName string) string { - out, err := exec.Command("ff", "deploy", "ethereum", stackName, "../../data/simplestorage/simple_storage.json").Output() +func deployContract(t *testing.T, stackName, contract string) string { + out, err := exec.Command("ff", "deploy", "ethereum", stackName, "../../data/contracts/"+contract).Output() require.NoError(t, err) var output map[string]interface{} err = json.Unmarshal(out, &output) require.NoError(t, err) - return output["address"].(string) + address := output["address"].(string) + t.Logf("Contract address: %s", address) + return address } type EthereumContractTestSuite struct { @@ -132,7 +134,7 @@ func (suite *EthereumContractTestSuite) SetupSuite() { suite.ethClient = e2e.NewResty(suite.T()) suite.ethClient.SetBaseURL(fmt.Sprintf("http://localhost:%d", stack.Members[0].ExposedConnectorPort)) suite.ethIdentity = suite.testState.org1key.Value - suite.contractAddress = deployContract(suite.T(), stack.Name) + suite.contractAddress = deployContract(suite.T(), stack.Name, "simplestorage/simple_storage.json") res, err := e2e.CreateFFI(suite.T(), suite.testState.client1, simpleStorageFFI()) suite.interfaceID = fftypes.MustParseUUID(res.(map[string]interface{})["id"].(string)) From fefbc35b94ba25520bb07b9dc323f90d2b512b51 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Tue, 12 Jul 2022 16:39:57 -0400 Subject: [PATCH 3/8] Consolidate STACK_FILE/STACK_STATE with STACK_DIR instead Signed-off-by: Andrew Richardson --- .vscode/launch.json | 3 +-- test/e2e/e2e.go | 17 +++++++++-------- test/e2e/run.sh | 11 +++-------- 3 files changed, 13 insertions(+), 18 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index dc280359e..4c238ce2e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -11,8 +11,7 @@ "mode": "test", "program": "${fileDirname}", "env": { - "STACK_FILE": "${env:HOME}/.firefly/stacks/firefly_e2e/stack.json", - "STACK_STATE": "${env:HOME}/.firefly/stacks/firefly_e2e/runtime/stackState.json" + "STACK_DIR": "${env:HOME}/.firefly/stacks/firefly_e2e" }, "showLog": true }, diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index 5f3769c99..e84cc1a0e 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -20,6 +20,7 @@ import ( "encoding/json" "fmt" "os" + "path/filepath" "strings" "testing" "time" @@ -82,21 +83,21 @@ func PickTopic(i int, options []string) string { } func ReadStack(t *testing.T) *Stack { - stackFile := os.Getenv("STACK_FILE") - if stackFile == "" { - t.Fatal("STACK_FILE must be set") + stackDir := os.Getenv("STACK_DIR") + if stackDir == "" { + t.Fatal("STACK_DIR must be set") } - stack, err := ReadStackFile(stackFile) + stack, err := ReadStackFile(filepath.Join(stackDir, "stack.json")) assert.NoError(t, err) return stack } func ReadStackState(t *testing.T) *StackState { - stackFile := os.Getenv("STACK_STATE") - if stackFile == "" { - t.Fatal("STACK_STATE must be set") + stackDir := os.Getenv("STACK_DIR") + if stackDir == "" { + t.Fatal("STACK_DIR must be set") } - stackState, err := ReadStackStateFile(stackFile) + stackState, err := ReadStackStateFile(filepath.Join(stackDir, "runtime", "stackState.json")) assert.NoError(t, err) return stackState } diff --git a/test/e2e/run.sh b/test/e2e/run.sh index 42939c34d..df912bf70 100755 --- a/test/e2e/run.sh +++ b/test/e2e/run.sh @@ -65,12 +65,8 @@ if [ -z "${MULTIPARTY_ENABLED}" ]; then MULTIPARTY_ENABLED=true fi -if [ -z "${STACK_FILE}" ]; then - STACK_FILE=$STACKS_DIR/$STACK_NAME/stack.json -fi - -if [ -z "${STACK_STATE}" ]; then - STACK_STATE=$STACKS_DIR/$STACK_NAME/runtime/stackState.json +if [ -z "${STACK_DIR}" ]; then + STACK_DIR=$STACKS_DIR/$STACK_NAME fi if [ -z "${BLOCKCHAIN_PROVIDER}" ]; then @@ -129,8 +125,7 @@ create_accounts $CLI info $STACK_NAME checkOk $? -export STACK_FILE -export STACK_STATE +export STACK_DIR runTest() { go clean -testcache && go test -v -p 1 ./multiparty ./gateway -run $TEST_SUITE From 383ede43c461965427e6a25c574fbc048ff31192 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Wed, 13 Jul 2022 12:03:18 -0400 Subject: [PATCH 4/8] Wrap E2E REST calls in a new FireFlyClient type Eventually this could evolve into a proper Go client SDK. Signed-off-by: Andrew Richardson --- test/e2e/{ => client}/restclient.go | 245 ++++++++++-------- test/e2e/e2e.go | 19 +- test/e2e/gateway/ethereum_contract_test.go | 39 +-- test/e2e/gateway/fabric_contract_test.go | 19 +- test/e2e/gateway/gateway_test.go | 26 +- test/e2e/gateway/tokens_test.go | 14 +- test/e2e/multiparty/ethereum_contract_test.go | 39 +-- test/e2e/multiparty/fabric_contract_test.go | 19 +- test/e2e/multiparty/identity_test.go | 25 +- test/e2e/multiparty/multiparty_test.go | 52 ++-- test/e2e/multiparty/onchain_offchain_test.go | 53 ++-- test/e2e/multiparty/tokens_test.go | 76 +++--- 12 files changed, 323 insertions(+), 303 deletions(-) rename test/e2e/{ => client}/restclient.go (69%) diff --git a/test/e2e/restclient.go b/test/e2e/client/restclient.go similarity index 69% rename from test/e2e/restclient.go rename to test/e2e/client/restclient.go index a9793236a..b51d3ff5c 100644 --- a/test/e2e/restclient.go +++ b/test/e2e/client/restclient.go @@ -14,7 +14,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package e2e +package client import ( "bytes" @@ -69,39 +69,56 @@ var ( urlGetOrgKeys = "/namespaces/default/identities/%s/verifiers" ) -func NewResty(t *testing.T) *resty.Client { +type Logger interface { + Logf(format string, args ...interface{}) +} + +type FireFlyClient struct { + logger Logger + Client *resty.Client +} + +func NewFireFly(l Logger, baseURL string) *FireFlyClient { + client := NewResty(l) + client.SetBaseURL(baseURL) + return &FireFlyClient{ + logger: l, + Client: client, + } +} + +func NewResty(l Logger) *resty.Client { client := resty.New() client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error { if os.Getenv("NAMESPACE") != "" { req.URL = strings.Replace(req.URL, "/namespaces/default", "/namespaces/"+os.Getenv("NAMESPACE"), 1) } - t.Logf("==> %s %s %s", req.Method, req.URL, req.QueryParam) + l.Logf("==> %s %s %s", req.Method, req.URL, req.QueryParam) return nil }) client.OnAfterResponse(func(c *resty.Client, resp *resty.Response) error { if resp == nil { return nil } - t.Logf("<== %d", resp.StatusCode()) + l.Logf("<== %d", resp.StatusCode()) if resp.IsError() { - t.Logf("%d", startTime.UnixNano())). SetQueryParam("topic", topic). SetQueryParam("sort", "sequence"). @@ -113,9 +130,9 @@ func GetMessageEvents(t *testing.T, client *resty.Client, startTime time.Time, t return events } -func GetMessages(t *testing.T, client *resty.Client, startTime time.Time, msgType core.MessageType, topic string, expectedStatus int) (msgs []*core.Message) { +func (client *FireFlyClient) GetMessages(t *testing.T, startTime time.Time, msgType core.MessageType, topic string, expectedStatus int) (msgs []*core.Message) { path := urlGetMessages - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("type", string(msgType)). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetQueryParam("topics", topic). @@ -127,9 +144,9 @@ func GetMessages(t *testing.T, client *resty.Client, startTime time.Time, msgTyp return msgs } -func GetData(t *testing.T, client *resty.Client, startTime time.Time, expectedStatus int) (data core.DataArray) { +func (client *FireFlyClient) GetData(t *testing.T, startTime time.Time, expectedStatus int) (data core.DataArray) { path := urlGetData - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&data). Get(path) @@ -138,10 +155,10 @@ func GetData(t *testing.T, client *resty.Client, startTime time.Time, expectedSt return data } -func GetDataForMessage(t *testing.T, client *resty.Client, startTime time.Time, msgID *fftypes.UUID) (data core.DataArray) { +func (client *FireFlyClient) GetDataForMessage(t *testing.T, startTime time.Time, msgID *fftypes.UUID) (data core.DataArray) { path := urlGetMessages path += "/" + msgID.String() + "/data" - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&data). Get(path) @@ -150,9 +167,9 @@ func GetDataForMessage(t *testing.T, client *resty.Client, startTime time.Time, return data } -func GetBlob(t *testing.T, client *resty.Client, data *core.Data, expectedStatus int) []byte { +func (client *FireFlyClient) GetBlob(t *testing.T, data *core.Data, expectedStatus int) []byte { path := fmt.Sprintf(urlGetDataBlob, data.ID) - resp, err := client.R(). + resp, err := client.Client.R(). SetDoNotParseResponse(true). Get(path) require.NoError(t, err) @@ -162,9 +179,9 @@ func GetBlob(t *testing.T, client *resty.Client, data *core.Data, expectedStatus return blob } -func GetOrgs(t *testing.T, client *resty.Client, expectedStatus int) (orgs []*core.Identity) { +func (client *FireFlyClient) GetOrgs(t *testing.T, expectedStatus int) (orgs []*core.Identity) { path := urlGetOrganizations - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("sort", "created"). SetResult(&orgs). Get(path) @@ -173,9 +190,9 @@ func GetOrgs(t *testing.T, client *resty.Client, expectedStatus int) (orgs []*co return orgs } -func GetIdentityBlockchainKeys(t *testing.T, client *resty.Client, identityID *fftypes.UUID, expectedStatus int) (verifiers []*core.Verifier) { +func (client *FireFlyClient) GetIdentityBlockchainKeys(t *testing.T, identityID *fftypes.UUID, expectedStatus int) (verifiers []*core.Verifier) { path := fmt.Sprintf(urlGetOrgKeys, identityID) - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("type", fmt.Sprintf("!=%s", core.VerifierTypeFFDXPeerID)). SetResult(&verifiers). Get(path) @@ -184,10 +201,10 @@ func GetIdentityBlockchainKeys(t *testing.T, client *resty.Client, identityID *f return verifiers } -func CreateSubscription(t *testing.T, client *resty.Client, input interface{}, expectedStatus int) *core.Subscription { +func (client *FireFlyClient) CreateSubscription(t *testing.T, input interface{}, expectedStatus int) *core.Subscription { path := urlSubscriptions var sub core.Subscription - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(input). SetResult(&sub). SetHeader("Content-Type", "application/json"). @@ -197,35 +214,35 @@ func CreateSubscription(t *testing.T, client *resty.Client, input interface{}, e return &sub } -func CleanupExistingSubscription(t *testing.T, client *resty.Client, namespace, name string) { +func (client *FireFlyClient) CleanupExistingSubscription(t *testing.T, namespace, name string) { var subs []*core.Subscription path := urlSubscriptions - resp, err := client.R(). + resp, err := client.Client.R(). SetResult(&subs). Get(path) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode(), "GET %s [%d]: %s", path, resp.StatusCode(), resp.String()) for _, s := range subs { if s.Namespace == namespace && s.Name == name { - DeleteSubscription(t, client, s.ID) + client.DeleteSubscription(t, s.ID) } } } -func DeleteSubscription(t *testing.T, client *resty.Client, id *fftypes.UUID) { +func (client *FireFlyClient) DeleteSubscription(t *testing.T, id *fftypes.UUID) { path := fmt.Sprintf("%s/%s", urlSubscriptions, id) - resp, err := client.R().Delete(path) + resp, err := client.Client.R().Delete(path) require.NoError(t, err) require.Equal(t, 204, resp.StatusCode(), "DELETE %s [%d]: %s", path, resp.StatusCode(), resp.String()) } -func BroadcastMessage(t *testing.T, client *resty.Client, topic string, data *core.DataRefOrValue, confirm bool) (*resty.Response, error) { - return BroadcastMessageAsIdentity(t, client, "", topic, data, confirm) +func (client *FireFlyClient) BroadcastMessage(t *testing.T, topic string, data *core.DataRefOrValue, confirm bool) (*resty.Response, error) { + return client.BroadcastMessageAsIdentity(t, "", topic, data, confirm) } -func BroadcastMessageAsIdentity(t *testing.T, client *resty.Client, did, topic string, data *core.DataRefOrValue, confirm bool) (*resty.Response, error) { +func (client *FireFlyClient) BroadcastMessageAsIdentity(t *testing.T, did, topic string, data *core.DataRefOrValue, confirm bool) (*resty.Response, error) { var msg core.Message - res, err := client.R(). + res, err := client.Client.R(). SetBody(core.MessageInOut{ Message: core.Message{ Header: core.MessageHeader{ @@ -244,9 +261,9 @@ func BroadcastMessageAsIdentity(t *testing.T, client *resty.Client, did, topic s return res, err } -func ClaimCustomIdentity(t *testing.T, client *resty.Client, key, name, desc string, profile fftypes.JSONObject, parent *fftypes.UUID, confirm bool) *core.Identity { +func (client *FireFlyClient) ClaimCustomIdentity(t *testing.T, key, name, desc string, profile fftypes.JSONObject, parent *fftypes.UUID, confirm bool) *core.Identity { var identity core.Identity - res, err := client.R(). + res, err := client.Client.R(). SetBody(core.IdentityCreateDTO{ Name: name, Type: core.IdentityTypeCustom, @@ -266,9 +283,9 @@ func ClaimCustomIdentity(t *testing.T, client *resty.Client, key, name, desc str return &identity } -func GetIdentity(t *testing.T, client *resty.Client, id *fftypes.UUID) *core.Identity { +func (client *FireFlyClient) GetIdentity(t *testing.T, id *fftypes.UUID) *core.Identity { var identity core.Identity - res, err := client.R(). + res, err := client.Client.R(). SetResult(&identity). Get(fmt.Sprintf(urlIdentity, id)) assert.NoError(t, err) @@ -276,9 +293,9 @@ func GetIdentity(t *testing.T, client *resty.Client, id *fftypes.UUID) *core.Ide return &identity } -func GetVerifiers(t *testing.T, client *resty.Client) []*core.Verifier { +func (client *FireFlyClient) GetVerifiers(t *testing.T) []*core.Verifier { var verifiers []*core.Verifier - res, err := client.R(). + res, err := client.Client.R(). SetResult(&verifiers). Get(urlVerifiers) assert.NoError(t, err) @@ -286,7 +303,7 @@ func GetVerifiers(t *testing.T, client *resty.Client) []*core.Verifier { return verifiers } -func CreateBlob(t *testing.T, client *resty.Client, dt *core.DatatypeRef) *core.Data { +func (client *FireFlyClient) CreateBlob(t *testing.T, dt *core.DatatypeRef) *core.Data { r, _ := rand.Int(rand.Reader, big.NewInt(1024*1024)) blob := make([]byte, r.Int64()+1024*1024) for i := 0; i < len(blob); i++ { @@ -307,7 +324,7 @@ func CreateBlob(t *testing.T, client *resty.Client, dt *core.DatatypeRef) *core. formData["datatype.name"] = dt.Name formData["datatype.version"] = dt.Version } - resp, err := client.R(). + resp, err := client.Client.R(). SetFormData(formData). SetFileReader("file", "myfile.txt", bytes.NewReader(blob)). SetResult(&data). @@ -328,9 +345,9 @@ func CreateBlob(t *testing.T, client *resty.Client, dt *core.DatatypeRef) *core. return &data } -func BroadcastBlobMessage(t *testing.T, client *resty.Client, topic string) (*core.Data, *resty.Response, error) { - data := CreateBlob(t, client, nil) - res, err := client.R(). +func (client *FireFlyClient) BroadcastBlobMessage(t *testing.T, topic string) (*core.Data, *resty.Response, error) { + data := client.CreateBlob(t, nil) + res, err := client.Client.R(). SetBody(core.MessageInOut{ Message: core.Message{ Header: core.MessageHeader{ @@ -345,8 +362,8 @@ func BroadcastBlobMessage(t *testing.T, client *resty.Client, topic string) (*co return data, res, err } -func PrivateBlobMessageDatatypeTagged(ts TestState, client *resty.Client, topic string, orgNames []string) (*core.Data, *resty.Response, error) { - data := CreateBlob(ts.T(), client, &core.DatatypeRef{Name: "myblob"}) +func (client *FireFlyClient) PrivateBlobMessageDatatypeTagged(t *testing.T, topic string, orgNames []string, startTime time.Time) (*core.Data, *resty.Response, error) { + data := client.CreateBlob(t, &core.DatatypeRef{Name: "myblob"}) members := make([]core.MemberInput, len(orgNames)) for i, oName := range orgNames { // We let FireFly resolve the friendly name of the org to the identity @@ -354,7 +371,7 @@ func PrivateBlobMessageDatatypeTagged(ts TestState, client *resty.Client, topic Identity: oName, } } - res, err := client.R(). + res, err := client.Client.R(). SetBody(core.MessageInOut{ Message: core.Message{ Header: core.MessageHeader{ @@ -366,18 +383,18 @@ func PrivateBlobMessageDatatypeTagged(ts TestState, client *resty.Client, topic }, Group: &core.InputGroup{ Members: members, - Name: fmt.Sprintf("test_%d", ts.StartTime().UnixNano()), + Name: fmt.Sprintf("test_%d", startTime.UnixNano()), }, }). Post(urlPrivateMessage) return data, res, err } -func PrivateMessage(ts TestState, client *resty.Client, topic string, data *core.DataRefOrValue, orgNames []string, tag string, txType core.TransactionType, confirm bool) (*resty.Response, error) { - return PrivateMessageWithKey(ts, client, "", topic, data, orgNames, tag, txType, confirm) +func (client *FireFlyClient) PrivateMessage(topic string, data *core.DataRefOrValue, orgNames []string, tag string, txType core.TransactionType, confirm bool, startTime time.Time) (*resty.Response, error) { + return client.PrivateMessageWithKey("", topic, data, orgNames, tag, txType, confirm, startTime) } -func PrivateMessageWithKey(ts TestState, client *resty.Client, key, topic string, data *core.DataRefOrValue, orgNames []string, tag string, txType core.TransactionType, confirm bool) (*resty.Response, error) { +func (client *FireFlyClient) PrivateMessageWithKey(key, topic string, data *core.DataRefOrValue, orgNames []string, tag string, txType core.TransactionType, confirm bool, startTime time.Time) (*resty.Response, error) { members := make([]core.MemberInput, len(orgNames)) for i, oName := range orgNames { // We let FireFly resolve the friendly name of the org to the identity @@ -399,19 +416,19 @@ func PrivateMessageWithKey(ts TestState, client *resty.Client, key, topic string InlineData: core.InlineData{data}, Group: &core.InputGroup{ Members: members, - Name: fmt.Sprintf("test_%d", ts.StartTime().UnixNano()), + Name: fmt.Sprintf("test_%d", startTime.UnixNano()), }, } - res, err := client.R(). + res, err := client.Client.R(). SetBody(msg). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&msg.Message). Post(urlPrivateMessage) - ts.T().Logf("Sent private message %s to %+v", msg.Header.ID, msg.Group.Members) + client.logger.Logf("Sent private message %s to %+v", msg.Header.ID, msg.Group.Members) return res, err } -func RequestReply(ts TestState, client *resty.Client, data *core.DataRefOrValue, orgNames []string, tag string, txType core.TransactionType) *core.MessageInOut { +func (client *FireFlyClient) RequestReply(t *testing.T, data *core.DataRefOrValue, orgNames []string, tag string, txType core.TransactionType, startTime time.Time) *core.MessageInOut { members := make([]core.MemberInput, len(orgNames)) for i, oName := range orgNames { // We let FireFly resolve the friendly name of the org to the identity @@ -429,23 +446,23 @@ func RequestReply(ts TestState, client *resty.Client, data *core.DataRefOrValue, InlineData: core.InlineData{data}, Group: &core.InputGroup{ Members: members, - Name: fmt.Sprintf("test_%d", ts.StartTime().UnixNano()), + Name: fmt.Sprintf("test_%d", startTime.UnixNano()), }, } var replyMsg core.MessageInOut - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(msg). SetResult(&replyMsg). Post(urlRequestMessage) - require.NoError(ts.T(), err) - require.Equal(ts.T(), 200, resp.StatusCode(), "POST %s [%d]: %s", urlUploadData, resp.StatusCode(), resp.String()) + require.NoError(t, err) + require.Equal(t, 200, resp.StatusCode(), "POST %s [%d]: %s", urlUploadData, resp.StatusCode(), resp.String()) return &replyMsg } -func CreateDatatype(t *testing.T, client *resty.Client, datatype *core.Datatype, confirm bool) *core.Datatype { +func (client *FireFlyClient) CreateDatatype(t *testing.T, datatype *core.Datatype, confirm bool) *core.Datatype { var dtReturn core.Datatype path := urlDatatypes - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(datatype). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&dtReturn). @@ -459,10 +476,10 @@ func CreateDatatype(t *testing.T, client *resty.Client, datatype *core.Datatype, return &dtReturn } -func CreateTokenPool(t *testing.T, client *resty.Client, pool *core.TokenPool, confirm bool) *core.TokenPool { +func (client *FireFlyClient) CreateTokenPool(t *testing.T, pool *core.TokenPool, confirm bool) *core.TokenPool { var poolOut core.TokenPool path := urlTokenPools - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(pool). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&poolOut). @@ -476,9 +493,9 @@ func CreateTokenPool(t *testing.T, client *resty.Client, pool *core.TokenPool, c return &poolOut } -func GetTokenPools(t *testing.T, client *resty.Client, startTime time.Time) (pools []*core.TokenPool) { +func (client *FireFlyClient) GetTokenPools(t *testing.T, startTime time.Time) (pools []*core.TokenPool) { path := urlTokenPools - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&pools). Get(path) @@ -487,10 +504,10 @@ func GetTokenPools(t *testing.T, client *resty.Client, startTime time.Time) (poo return pools } -func MintTokens(t *testing.T, client *resty.Client, mint *core.TokenTransferInput, confirm bool) *core.TokenTransfer { +func (client *FireFlyClient) MintTokens(t *testing.T, mint *core.TokenTransferInput, confirm bool) *core.TokenTransfer { var transferOut core.TokenTransfer path := urlTokenMint - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(mint). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&transferOut). @@ -504,10 +521,10 @@ func MintTokens(t *testing.T, client *resty.Client, mint *core.TokenTransferInpu return &transferOut } -func BurnTokens(t *testing.T, client *resty.Client, burn *core.TokenTransferInput, confirm bool) *core.TokenTransfer { +func (client *FireFlyClient) BurnTokens(t *testing.T, burn *core.TokenTransferInput, confirm bool) *core.TokenTransfer { var transferOut core.TokenTransfer path := urlTokenBurn - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(burn). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&transferOut). @@ -521,10 +538,10 @@ func BurnTokens(t *testing.T, client *resty.Client, burn *core.TokenTransferInpu return &transferOut } -func TransferTokens(t *testing.T, client *resty.Client, transfer *core.TokenTransferInput, confirm bool) *core.TokenTransfer { +func (client *FireFlyClient) TransferTokens(t *testing.T, transfer *core.TokenTransferInput, confirm bool) *core.TokenTransfer { var transferOut core.TokenTransfer path := urlTokenTransfers - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(transfer). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&transferOut). @@ -538,9 +555,9 @@ func TransferTokens(t *testing.T, client *resty.Client, transfer *core.TokenTran return &transferOut } -func GetTokenTransfers(t *testing.T, client *resty.Client, poolID *fftypes.UUID) (transfers []*core.TokenTransfer) { +func (client *FireFlyClient) GetTokenTransfers(t *testing.T, poolID *fftypes.UUID) (transfers []*core.TokenTransfer) { path := urlTokenTransfers - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("pool", poolID.String()). SetResult(&transfers). Get(path) @@ -549,10 +566,10 @@ func GetTokenTransfers(t *testing.T, client *resty.Client, poolID *fftypes.UUID) return transfers } -func TokenApproval(t *testing.T, client *resty.Client, approval *core.TokenApprovalInput, confirm bool) *core.TokenApproval { +func (client *FireFlyClient) TokenApproval(t *testing.T, approval *core.TokenApprovalInput, confirm bool) *core.TokenApproval { var approvalOut core.TokenApproval path := urlTokenApprovals - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(approval). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&approvalOut). @@ -566,9 +583,9 @@ func TokenApproval(t *testing.T, client *resty.Client, approval *core.TokenAppro return &approvalOut } -func GetTokenApprovals(t *testing.T, client *resty.Client, poolID *fftypes.UUID) (approvals []*core.TokenApproval) { +func (client *FireFlyClient) GetTokenApprovals(t *testing.T, poolID *fftypes.UUID) (approvals []*core.TokenApproval) { path := urlTokenApprovals - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("pool", poolID.String()). SetQueryParam("active", "true"). SetResult(&approvals). @@ -578,9 +595,9 @@ func GetTokenApprovals(t *testing.T, client *resty.Client, poolID *fftypes.UUID) return approvals } -func GetTokenAccounts(t *testing.T, client *resty.Client, poolID *fftypes.UUID) (accounts []*core.TokenAccount) { +func (client *FireFlyClient) GetTokenAccounts(t *testing.T, poolID *fftypes.UUID) (accounts []*core.TokenAccount) { path := urlTokenAccounts - resp, err := client.R(). + resp, err := client.Client.R(). SetResult(&accounts). Get(path) require.NoError(t, err) @@ -588,9 +605,9 @@ func GetTokenAccounts(t *testing.T, client *resty.Client, poolID *fftypes.UUID) return accounts } -func GetTokenAccountPools(t *testing.T, client *resty.Client, identity string) (pools []*core.TokenAccountPool) { +func (client *FireFlyClient) GetTokenAccountPools(t *testing.T, identity string) (pools []*core.TokenAccountPool) { path := urlTokenAccounts + "/" + identity + "/pools" - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("sort", "-updated"). SetResult(&pools). Get(path) @@ -599,10 +616,10 @@ func GetTokenAccountPools(t *testing.T, client *resty.Client, identity string) ( return pools } -func GetTokenBalance(t *testing.T, client *resty.Client, poolID *fftypes.UUID, tokenIndex, key string) (account *core.TokenBalance) { +func (client *FireFlyClient) GetTokenBalance(t *testing.T, poolID *fftypes.UUID, tokenIndex, key string) (account *core.TokenBalance) { var accounts []*core.TokenBalance path := urlTokenBalances - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("pool", poolID.String()). SetQueryParam("tokenIndex", tokenIndex). SetQueryParam("key", key). @@ -614,7 +631,7 @@ func GetTokenBalance(t *testing.T, client *resty.Client, poolID *fftypes.UUID, t return accounts[0] } -func CreateContractListener(t *testing.T, client *resty.Client, event *fftypes.FFIEvent, location *fftypes.JSONObject) *core.ContractListener { +func (client *FireFlyClient) CreateContractListener(t *testing.T, event *fftypes.FFIEvent, location *fftypes.JSONObject) *core.ContractListener { body := core.ContractListenerInput{ ContractListener: core.ContractListener{ Location: fftypes.JSONAnyPtr(location.String()), @@ -626,7 +643,7 @@ func CreateContractListener(t *testing.T, client *resty.Client, event *fftypes.F } var sub core.ContractListener path := urlContractListeners - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(&body). SetResult(&sub). Post(path) @@ -635,7 +652,7 @@ func CreateContractListener(t *testing.T, client *resty.Client, event *fftypes.F return &sub } -func CreateFFIContractListener(t *testing.T, client *resty.Client, ffiReference *fftypes.FFIReference, eventPath string, location *fftypes.JSONObject) *core.ContractListener { +func (client *FireFlyClient) CreateFFIContractListener(t *testing.T, ffiReference *fftypes.FFIReference, eventPath string, location *fftypes.JSONObject) *core.ContractListener { body := core.ContractListenerInput{ ContractListener: core.ContractListener{ Location: fftypes.JSONAnyPtr(location.String()), @@ -646,7 +663,7 @@ func CreateFFIContractListener(t *testing.T, client *resty.Client, ffiReference } var listener core.ContractListener path := urlContractListeners - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(&body). SetResult(&listener). Post(path) @@ -655,9 +672,9 @@ func CreateFFIContractListener(t *testing.T, client *resty.Client, ffiReference return &listener } -func GetContractListeners(t *testing.T, client *resty.Client, startTime time.Time) (subs []*core.ContractListener) { +func (client *FireFlyClient) GetContractListeners(t *testing.T, startTime time.Time) (subs []*core.ContractListener) { path := urlContractListeners - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&subs). Get(path) @@ -666,9 +683,9 @@ func GetContractListeners(t *testing.T, client *resty.Client, startTime time.Tim return subs } -func GetContractEvents(t *testing.T, client *resty.Client, startTime time.Time, subscriptionID *fftypes.UUID) (events []*core.BlockchainEvent) { +func (client *FireFlyClient) GetContractEvents(t *testing.T, startTime time.Time, subscriptionID *fftypes.UUID) (events []*core.BlockchainEvent) { path := urlBlockchainEvents - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("timestamp", fmt.Sprintf(">%d", startTime.UnixNano())). SetQueryParam("subscriptionId", subscriptionID.String()). SetResult(&events). @@ -678,17 +695,17 @@ func GetContractEvents(t *testing.T, client *resty.Client, startTime time.Time, return events } -func DeleteContractListener(t *testing.T, client *resty.Client, id *fftypes.UUID) { +func (client *FireFlyClient) DeleteContractListener(t *testing.T, id *fftypes.UUID) { path := urlContractListeners + "/" + id.String() - resp, err := client.R().Delete(path) + resp, err := client.Client.R().Delete(path) require.NoError(t, err) require.Equal(t, 204, resp.StatusCode(), "DELETE %s [%d]: %s", path, resp.StatusCode(), resp.String()) } -func InvokeContractMethod(t *testing.T, client *resty.Client, req *core.ContractCallRequest) (interface{}, error) { +func (client *FireFlyClient) InvokeContractMethod(t *testing.T, req *core.ContractCallRequest) (interface{}, error) { var res interface{} path := urlContractInvoke - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(req). SetResult(&res). Post(path) @@ -697,10 +714,10 @@ func InvokeContractMethod(t *testing.T, client *resty.Client, req *core.Contract return res, err } -func QueryContractMethod(t *testing.T, client *resty.Client, req *core.ContractCallRequest) (interface{}, error) { +func (client *FireFlyClient) QueryContractMethod(t *testing.T, req *core.ContractCallRequest) (interface{}, error) { var res interface{} path := urlContractQuery - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(req). SetResult(&res). Post(path) @@ -709,10 +726,10 @@ func QueryContractMethod(t *testing.T, client *resty.Client, req *core.ContractC return res, err } -func CreateFFI(t *testing.T, client *resty.Client, ffi *fftypes.FFI) (interface{}, error) { +func (client *FireFlyClient) CreateFFI(t *testing.T, ffi *fftypes.FFI) (interface{}, error) { var res interface{} path := urlContractInterface - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(ffi). SetResult(&res). SetQueryParam("confirm", "true"). @@ -722,7 +739,7 @@ func CreateFFI(t *testing.T, client *resty.Client, ffi *fftypes.FFI) (interface{ return res, err } -func CreateContractAPI(t *testing.T, client *resty.Client, name string, ffiReference *fftypes.FFIReference, location *fftypes.JSONAny) (interface{}, error) { +func (client *FireFlyClient) CreateContractAPI(t *testing.T, name string, ffiReference *fftypes.FFIReference, location *fftypes.JSONAny) (interface{}, error) { apiReqBody := &core.ContractAPI{ Name: name, Interface: ffiReference, @@ -731,7 +748,7 @@ func CreateContractAPI(t *testing.T, client *resty.Client, name string, ffiRefer var res interface{} path := urlContractAPI - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&res). SetQueryParam("confirm", "true"). @@ -741,13 +758,13 @@ func CreateContractAPI(t *testing.T, client *resty.Client, name string, ffiRefer return res, err } -func InvokeContractAPIMethod(t *testing.T, client *resty.Client, apiName string, methodName string, input *fftypes.JSONAny) (interface{}, error) { +func (client *FireFlyClient) InvokeContractAPIMethod(t *testing.T, apiName string, methodName string, input *fftypes.JSONAny) (interface{}, error) { apiReqBody := map[string]interface{}{ "input": input, } var res interface{} path := fmt.Sprintf("%s/%s/invoke/%s", urlContractAPI, apiName, methodName) - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&res). SetQueryParam("confirm", "true"). @@ -757,13 +774,13 @@ func InvokeContractAPIMethod(t *testing.T, client *resty.Client, apiName string, return res, err } -func QueryContractAPIMethod(t *testing.T, client *resty.Client, apiName string, methodName string, input *fftypes.JSONAny) (interface{}, error) { +func (client *FireFlyClient) QueryContractAPIMethod(t *testing.T, apiName string, methodName string, input *fftypes.JSONAny) (interface{}, error) { apiReqBody := map[string]interface{}{ "input": input, } var res interface{} path := fmt.Sprintf("%s/%s/query/%s", urlContractAPI, apiName, methodName) - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&res). Post(path) @@ -772,13 +789,13 @@ func QueryContractAPIMethod(t *testing.T, client *resty.Client, apiName string, return res, err } -func CreateContractAPIListener(t *testing.T, client *resty.Client, apiName, eventName, topic string) (*core.ContractListener, error) { +func (client *FireFlyClient) CreateContractAPIListener(t *testing.T, apiName, eventName, topic string) (*core.ContractListener, error) { apiReqBody := map[string]interface{}{ "topic": topic, } var listener core.ContractListener path := fmt.Sprintf("%s/%s/listeners/%s", urlContractAPI, apiName, eventName) - resp, err := client.R(). + resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&listener). Post(path) @@ -787,10 +804,10 @@ func CreateContractAPIListener(t *testing.T, client *resty.Client, apiName, even return &listener, err } -func GetEvent(t *testing.T, client *resty.Client, eventID string) (interface{}, error) { +func (client *FireFlyClient) GetEvent(t *testing.T, eventID string) (interface{}, error) { var res interface{} path := fmt.Sprintf("%s/%s", urlGetEvents, eventID) - resp, err := client.R(). + resp, err := client.Client.R(). SetResult(&res). Get(path) require.NoError(t, err) @@ -798,10 +815,10 @@ func GetEvent(t *testing.T, client *resty.Client, eventID string) (interface{}, return res, err } -func GetBlockchainEvent(t *testing.T, client *resty.Client, eventID string) (interface{}, error) { +func (client *FireFlyClient) GetBlockchainEvent(t *testing.T, eventID string) (interface{}, error) { var res interface{} path := fmt.Sprintf("%s/%s", urlBlockchainEvents, eventID) - resp, err := client.R(). + resp, err := client.Client.R(). SetResult(&res). Get(path) require.NoError(t, err) @@ -809,9 +826,9 @@ func GetBlockchainEvent(t *testing.T, client *resty.Client, eventID string) (int return res, err } -func GetOperations(t *testing.T, client *resty.Client, startTime time.Time) (operations []*core.Operation) { +func (client *FireFlyClient) GetOperations(t *testing.T, startTime time.Time) (operations []*core.Operation) { path := urlOperations - resp, err := client.R(). + resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&operations). Get(path) diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index e84cc1a0e..759e4bc09 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -29,6 +29,7 @@ import ( "github.com/gorilla/websocket" "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -57,11 +58,11 @@ var WidgetSchemaJSON = []byte(`{ "additionalProperties": false }`) -func PollForUp(t *testing.T, client *resty.Client) { +func PollForUp(t *testing.T, client *client.FireFlyClient) { var resp *resty.Response var err error for i := 0; i < 3; i++ { - resp, err = GetNamespaces(client) + resp, err = client.GetNamespaces() if err == nil && resp.StatusCode() == 200 { break } @@ -71,9 +72,9 @@ func PollForUp(t *testing.T, client *resty.Client) { assert.Equal(t, 200, resp.StatusCode()) } -func ValidateAccountBalances(t *testing.T, client *resty.Client, poolID *fftypes.UUID, tokenIndex string, balances map[string]int64) { +func ValidateAccountBalances(t *testing.T, client *client.FireFlyClient, poolID *fftypes.UUID, tokenIndex string, balances map[string]int64) { for key, balance := range balances { - account := GetTokenBalance(t, client, poolID, tokenIndex, key) + account := client.GetTokenBalance(t, poolID, tokenIndex, key) assert.Equal(t, balance, account.Balance.Int().Int64()) } } @@ -163,11 +164,11 @@ func WaitForIdentityConfirmed(t *testing.T, c chan *core.EventDelivery) *core.Ev } } -func WaitForContractEvent(t *testing.T, client *resty.Client, c chan *core.EventDelivery, match map[string]interface{}) map[string]interface{} { +func WaitForContractEvent(t *testing.T, client *client.FireFlyClient, c chan *core.EventDelivery, match map[string]interface{}) map[string]interface{} { for { eventDelivery := <-c if eventDelivery.Type == core.EventTypeBlockchainEventReceived { - event, err := GetBlockchainEvent(t, client, eventDelivery.Event.Reference.String()) + event, err := client.GetBlockchainEvent(t, eventDelivery.Event.Reference.String()) if err != nil { t.Logf("WARN: unable to get event: %v", err.Error()) continue @@ -225,7 +226,7 @@ func checkObject(t *testing.T, expected interface{}, actual interface{}) bool { return match } -func VerifyAllOperationsSucceeded(t *testing.T, clients []*resty.Client, startTime time.Time) { +func VerifyAllOperationsSucceeded(t *testing.T, clients []*client.FireFlyClient, startTime time.Time) { tries := 3 delay := 2 * time.Second @@ -233,9 +234,9 @@ func VerifyAllOperationsSucceeded(t *testing.T, clients []*resty.Client, startTi for i := 0; i < tries; i++ { pending = "" for _, client := range clients { - for _, op := range GetOperations(t, client, startTime) { + for _, op := range client.GetOperations(t, startTime) { if op.Status != core.OpStatusSucceeded { - pending += fmt.Sprintf("Operation '%s' (%s) on '%s' is not successful\n", op.ID, op.Type, client.BaseURL) + pending += fmt.Sprintf("Operation '%s' (%s) on '%s' is not successful\n", op.ID, op.Type, client.Client.BaseURL) } } } diff --git a/test/e2e/gateway/ethereum_contract_test.go b/test/e2e/gateway/ethereum_contract_test.go index a189b2833..06a6d247d 100644 --- a/test/e2e/gateway/ethereum_contract_test.go +++ b/test/e2e/gateway/ethereum_contract_test.go @@ -27,6 +27,7 @@ import ( "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -132,13 +133,13 @@ func (suite *EthereumContractTestSuite) SetupSuite() { suite.testState = beforeE2ETest(suite.T()) stack := e2e.ReadStack(suite.T()) stackState := e2e.ReadStackState(suite.T()) - suite.ethClient = e2e.NewResty(suite.T()) + suite.ethClient = client.NewResty(suite.T()) suite.ethClient.SetBaseURL(fmt.Sprintf("http://localhost:%d", stack.Members[0].ExposedConnectorPort)) account := stackState.Accounts[0].(map[string]interface{}) suite.ethIdentity = account["address"].(string) suite.contractAddress = deployContract(suite.T(), stack.Name, "simplestorage/simple_storage.json") - res, err := e2e.CreateFFI(suite.T(), suite.testState.client1, simpleStorageFFI()) + res, err := suite.testState.client1.CreateFFI(suite.T(), simpleStorageFFI()) suite.interfaceID = fftypes.MustParseUUID(res.(map[string]interface{})["id"].(string)) suite.T().Logf("interfaceID: %s", suite.interfaceID) assert.NoError(suite.T(), err) @@ -149,18 +150,18 @@ func (suite *EthereumContractTestSuite) BeforeTest(suiteName, testName string) { } func (suite *EthereumContractTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1}, suite.testState.startTime) } func (suite *EthereumContractTestSuite) TestDirectInvokeMethod() { defer suite.testState.Done() received1 := e2e.WsReader(suite.testState.ws1, true) - listener := e2e.CreateContractListener(suite.T(), suite.testState.client1, simpleStorageFFIChanged(), &fftypes.JSONObject{ + listener := suite.testState.client1.CreateContractListener(suite.T(), simpleStorageFFIChanged(), &fftypes.JSONObject{ "address": suite.contractAddress, }) - listeners := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + listeners := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(listeners)) assert.Equal(suite.T(), listener.BackendID, listeners[0].BackendID) @@ -176,7 +177,7 @@ func (suite *EthereumContractTestSuite) TestDirectInvokeMethod() { }, } - res, err := e2e.InvokeContractMethod(suite.T(), suite.testState.client1, invokeContractRequest) + res, err := suite.testState.client1.InvokeContractMethod(suite.T(), invokeContractRequest) assert.NoError(suite.T(), err) assert.NotNil(suite.T(), res) @@ -198,12 +199,12 @@ func (suite *EthereumContractTestSuite) TestDirectInvokeMethod() { Location: fftypes.JSONAnyPtrBytes(locationBytes), Method: simpleStorageFFIGet(), } - res, err = e2e.QueryContractMethod(suite.T(), suite.testState.client1, queryContractRequest) + res, err = suite.testState.client1.QueryContractMethod(suite.T(), queryContractRequest) assert.NoError(suite.T(), err) resJSON, err := json.Marshal(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), `{"output":"2"}`, string(resJSON)) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, listener.ID) + suite.testState.client1.DeleteContractListener(suite.T(), listener.ID) } func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { @@ -214,11 +215,11 @@ func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { ffiReference := &fftypes.FFIReference{ ID: suite.interfaceID, } - listener := e2e.CreateFFIContractListener(suite.T(), suite.testState.client1, ffiReference, "Changed", &fftypes.JSONObject{ + listener := suite.testState.client1.CreateFFIContractListener(suite.T(), ffiReference, "Changed", &fftypes.JSONObject{ "address": suite.contractAddress, }) - listeners := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + listeners := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(listeners)) assert.Equal(suite.T(), listener.BackendID, listeners[0].BackendID) @@ -235,7 +236,7 @@ func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { MethodPath: "set", } - res, err := e2e.InvokeContractMethod(suite.T(), suite.testState.client1, invokeContractRequest) + res, err := suite.testState.client1.InvokeContractMethod(suite.T(), invokeContractRequest) assert.NoError(suite.T(), err) assert.NotNil(suite.T(), res) @@ -257,12 +258,12 @@ func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { Interface: suite.interfaceID, MethodPath: "get", } - res, err = e2e.QueryContractMethod(suite.T(), suite.testState.client1, queryContractRequest) + res, err = suite.testState.client1.QueryContractMethod(suite.T(), queryContractRequest) assert.NoError(suite.T(), err) resJSON, err := json.Marshal(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), `{"output":"42"}`, string(resJSON)) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, listener.ID) + suite.testState.client1.DeleteContractListener(suite.T(), listener.ID) } func (suite *EthereumContractTestSuite) TestContractAPIMethod() { @@ -280,19 +281,19 @@ func (suite *EthereumContractTestSuite) TestContractAPIMethod() { } locationBytes, _ := json.Marshal(location) - createContractAPIResult, err := e2e.CreateContractAPI(suite.T(), suite.testState.client1, APIName, ffiReference, fftypes.JSONAnyPtr(string(locationBytes))) + createContractAPIResult, err := suite.testState.client1.CreateContractAPI(suite.T(), APIName, ffiReference, fftypes.JSONAnyPtr(string(locationBytes))) assert.NotNil(suite.T(), createContractAPIResult) assert.NoError(suite.T(), err) - listener, err := e2e.CreateContractAPIListener(suite.T(), suite.testState.client1, APIName, "Changed", "firefly_e2e") + listener, err := suite.testState.client1.CreateContractAPIListener(suite.T(), APIName, "Changed", "firefly_e2e") assert.NoError(suite.T(), err) - listeners := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + listeners := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(listeners)) assert.Equal(suite.T(), listener.BackendID, listeners[0].BackendID) input := fftypes.JSONAny(`{"newValue": 42}`) - invokeResult, err := e2e.InvokeContractAPIMethod(suite.T(), suite.testState.client1, APIName, "set", &input) + invokeResult, err := suite.testState.client1.InvokeContractAPIMethod(suite.T(), APIName, "set", &input) assert.NoError(suite.T(), err) assert.NotNil(suite.T(), invokeResult) @@ -310,11 +311,11 @@ func (suite *EthereumContractTestSuite) TestContractAPIMethod() { assert.NotNil(suite.T(), event) assert.NoError(suite.T(), err) - res, err := e2e.QueryContractAPIMethod(suite.T(), suite.testState.client1, APIName, "get", fftypes.JSONAnyPtr("{}")) + res, err := suite.testState.client1.QueryContractAPIMethod(suite.T(), APIName, "get", fftypes.JSONAnyPtr("{}")) assert.NoError(suite.T(), err) resJSON, err := json.Marshal(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), `{"output":"42"}`, string(resJSON)) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, listener.ID) + suite.testState.client1.DeleteContractListener(suite.T(), listener.ID) } diff --git a/test/e2e/gateway/fabric_contract_test.go b/test/e2e/gateway/fabric_contract_test.go index ff2c5d85e..6aac55739 100644 --- a/test/e2e/gateway/fabric_contract_test.go +++ b/test/e2e/gateway/fabric_contract_test.go @@ -28,6 +28,7 @@ import ( "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -131,7 +132,7 @@ func (suite *FabricContractTestSuite) SetupSuite() { stack := e2e.ReadStack(suite.T()) suite.chaincodeName = deployChaincode(suite.T(), stack.Name) - suite.fabClient = e2e.NewResty(suite.T()) + suite.fabClient = client.NewResty(suite.T()) suite.fabClient.SetBaseURL(fmt.Sprintf("http://localhost:%d", stack.Members[0].ExposedConnectorPort)) } @@ -140,7 +141,7 @@ func (suite *FabricContractTestSuite) BeforeTest(suiteName, testName string) { } func (suite *FabricContractTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1}, suite.testState.startTime) } func (suite *FabricContractTestSuite) TestE2EContractEvents() { @@ -148,12 +149,12 @@ func (suite *FabricContractTestSuite) TestE2EContractEvents() { received1 := e2e.WsReader(suite.testState.ws1, true) - sub := e2e.CreateContractListener(suite.T(), suite.testState.client1, assetCreatedEvent, &fftypes.JSONObject{ + sub := suite.testState.client1.CreateContractListener(suite.T(), assetCreatedEvent, &fftypes.JSONObject{ "channel": "firefly", "chaincode": suite.chaincodeName, }) - subs := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + subs := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(subs)) assert.Equal(suite.T(), sub.BackendID, subs[0].BackendID) @@ -171,13 +172,13 @@ func (suite *FabricContractTestSuite) TestE2EContractEvents() { }, } - res, err := e2e.InvokeContractMethod(suite.testState.t, suite.testState.client1, invokeContractRequest) + res, err := suite.testState.client1.InvokeContractMethod(suite.testState.t, invokeContractRequest) suite.T().Log(res) assert.NoError(suite.T(), err) <-received1 - events := e2e.GetContractEvents(suite.T(), suite.testState.client1, suite.testState.startTime, sub.ID) + events := suite.testState.client1.GetContractEvents(suite.T(), suite.testState.startTime, sub.ID) assert.Equal(suite.T(), 1, len(events)) assert.Equal(suite.T(), "AssetCreated", events[0].Name) assert.Equal(suite.T(), assetName, events[0].Output.GetString("name")) @@ -190,13 +191,13 @@ func (suite *FabricContractTestSuite) TestE2EContractEvents() { }, } - res, err = e2e.QueryContractMethod(suite.testState.t, suite.testState.client1, queryContractRequest) + res, err = suite.testState.client1.QueryContractMethod(suite.testState.t, queryContractRequest) suite.T().Log(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), assetName, res.(map[string]interface{})["name"]) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, subs[0].ID) - subs = e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + suite.testState.client1.DeleteContractListener(suite.T(), subs[0].ID) + subs = suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 0, len(subs)) } diff --git a/test/e2e/gateway/gateway_test.go b/test/e2e/gateway/gateway_test.go index 81143efb9..4296eb0f9 100644 --- a/test/e2e/gateway/gateway_test.go +++ b/test/e2e/gateway/gateway_test.go @@ -25,9 +25,9 @@ import ( "testing" "time" - "github.com/go-resty/resty/v2" "github.com/gorilla/websocket" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/require" ) @@ -36,7 +36,7 @@ type testState struct { startTime time.Time done func() ws1 *websocket.Conn - client1 *resty.Client + client1 *client.FireFlyClient unregisteredAccounts []interface{} namespace string } @@ -60,14 +60,6 @@ func beforeE2ETest(t *testing.T) *testState { var authHeader1 http.Header - ts := &testState{ - t: t, - startTime: time.Now(), - client1: e2e.NewResty(t), - unregisteredAccounts: stackState.Accounts[2:], - namespace: namespace, - } - httpProtocolClient1 := "http" websocketProtocolClient1 := "ws" if stack.Members[0].UseHTTPS { @@ -80,13 +72,21 @@ func beforeE2ETest(t *testing.T) *testState { member0WithPort = fmt.Sprintf(":%d", stack.Members[0].ExposedFireflyPort) } - ts.client1.SetBaseURL(fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort)) + baseURL := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) + + ts := &testState{ + t: t, + startTime: time.Now(), + client1: client.NewFireFly(t, baseURL), + unregisteredAccounts: stackState.Accounts[2:], + namespace: namespace, + } t.Logf("Blockchain provider: %s", stack.BlockchainProvider) if stack.Members[0].Username != "" && stack.Members[0].Password != "" { t.Log("Setting auth for user 1") - ts.client1.SetBasicAuth(stack.Members[0].Username, stack.Members[0].Password) + ts.client1.Client.SetBasicAuth(stack.Members[0].Username, stack.Members[0].Password) authHeader1 = http.Header{ "Authorization": []string{fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", stack.Members[0].Username, stack.Members[0].Password))))}, } @@ -98,7 +98,7 @@ func beforeE2ETest(t *testing.T) *testState { ts.namespace = namespace } - t.Logf("Client 1: " + ts.client1.HostURL) + t.Logf("Client 1: " + ts.client1.Client.HostURL) e2e.PollForUp(t, ts.client1) eventNames := "message_confirmed|token_pool_confirmed|token_transfer_confirmed|blockchain_event_received|token_approval_confirmed|identity_confirmed" diff --git a/test/e2e/gateway/tokens_test.go b/test/e2e/gateway/tokens_test.go index d5c89cf8c..196d49de9 100644 --- a/test/e2e/gateway/tokens_test.go +++ b/test/e2e/gateway/tokens_test.go @@ -21,10 +21,10 @@ import ( "math/rand" "time" - "github.com/go-resty/resty/v2" "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) @@ -50,7 +50,7 @@ func (suite *TokensTestSuite) BeforeTest(suiteName, testName string) { } func (suite *TokensTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1}, suite.testState.startTime) } func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { @@ -58,7 +58,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { received1 := e2e.WsReader(suite.testState.ws1, false) - pools := e2e.GetTokenPools(suite.T(), suite.testState.client1, time.Unix(0, 0)) + pools := suite.testState.client1.GetTokenPools(suite.T(), time.Unix(0, 0)) rand.Seed(time.Now().UnixNano()) poolName := fmt.Sprintf("pool%d", rand.Intn(10000)) suite.T().Logf("Pool name: %s", poolName) @@ -69,11 +69,11 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { Config: fftypes.JSONObject{}, } - poolResp := e2e.CreateTokenPool(suite.T(), suite.testState.client1, pool, false) + poolResp := suite.testState.client1.CreateTokenPool(suite.T(), pool, false) poolID := poolResp.ID e2e.WaitForEvent(suite.T(), received1, core.EventTypePoolConfirmed, poolID) - pools = e2e.GetTokenPools(suite.T(), suite.testState.client1, suite.testState.startTime) + pools = suite.testState.client1.GetTokenPools(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(pools)) assert.Equal(suite.T(), suite.testState.namespace, pools[0].Namespace) assert.Equal(suite.T(), suite.connector, pools[0].Connector) @@ -85,7 +85,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { TokenTransfer: core.TokenTransfer{Amount: *fftypes.NewFFBigInt(1)}, Pool: poolName, } - transferOut := e2e.MintTokens(suite.T(), suite.testState.client1, transfer, false) + transferOut := suite.testState.client1.MintTokens(suite.T(), transfer, false) e2e.WaitForEvent(suite.T(), received1, core.EventTypeTransferConfirmed, transferOut.LocalID) e2e.ValidateAccountBalances(suite.T(), suite.testState.client1, poolID, "", map[string]int64{ suite.key: 1, @@ -95,7 +95,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { TokenTransfer: core.TokenTransfer{Amount: *fftypes.NewFFBigInt(1)}, Pool: poolName, } - transferOut = e2e.BurnTokens(suite.T(), suite.testState.client1, transfer, false) + transferOut = suite.testState.client1.BurnTokens(suite.T(), transfer, false) e2e.WaitForEvent(suite.T(), received1, core.EventTypeTransferConfirmed, transferOut.LocalID) e2e.ValidateAccountBalances(suite.T(), suite.testState.client1, poolID, "", map[string]int64{ suite.key: 0, diff --git a/test/e2e/multiparty/ethereum_contract_test.go b/test/e2e/multiparty/ethereum_contract_test.go index bf1cfbcf2..8613a2323 100644 --- a/test/e2e/multiparty/ethereum_contract_test.go +++ b/test/e2e/multiparty/ethereum_contract_test.go @@ -27,6 +27,7 @@ import ( "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -131,12 +132,12 @@ type EthereumContractTestSuite struct { func (suite *EthereumContractTestSuite) SetupSuite() { suite.testState = beforeE2ETest(suite.T()) stack := e2e.ReadStack(suite.T()) - suite.ethClient = e2e.NewResty(suite.T()) + suite.ethClient = client.NewResty(suite.T()) suite.ethClient.SetBaseURL(fmt.Sprintf("http://localhost:%d", stack.Members[0].ExposedConnectorPort)) suite.ethIdentity = suite.testState.org1key.Value suite.contractAddress = deployContract(suite.T(), stack.Name, "simplestorage/simple_storage.json") - res, err := e2e.CreateFFI(suite.T(), suite.testState.client1, simpleStorageFFI()) + res, err := suite.testState.client1.CreateFFI(suite.T(), simpleStorageFFI()) suite.interfaceID = fftypes.MustParseUUID(res.(map[string]interface{})["id"].(string)) suite.T().Logf("interfaceID: %s", suite.interfaceID) assert.NoError(suite.T(), err) @@ -147,18 +148,18 @@ func (suite *EthereumContractTestSuite) BeforeTest(suiteName, testName string) { } func (suite *EthereumContractTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) } func (suite *EthereumContractTestSuite) TestDirectInvokeMethod() { defer suite.testState.Done() received1 := e2e.WsReader(suite.testState.ws1, true) - listener := e2e.CreateContractListener(suite.T(), suite.testState.client1, simpleStorageFFIChanged(), &fftypes.JSONObject{ + listener := suite.testState.client1.CreateContractListener(suite.T(), simpleStorageFFIChanged(), &fftypes.JSONObject{ "address": suite.contractAddress, }) - listeners := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + listeners := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(listeners)) assert.Equal(suite.T(), listener.BackendID, listeners[0].BackendID) @@ -174,7 +175,7 @@ func (suite *EthereumContractTestSuite) TestDirectInvokeMethod() { }, } - res, err := e2e.InvokeContractMethod(suite.T(), suite.testState.client1, invokeContractRequest) + res, err := suite.testState.client1.InvokeContractMethod(suite.T(), invokeContractRequest) assert.NoError(suite.T(), err) assert.NotNil(suite.T(), res) @@ -196,12 +197,12 @@ func (suite *EthereumContractTestSuite) TestDirectInvokeMethod() { Location: fftypes.JSONAnyPtrBytes(locationBytes), Method: simpleStorageFFIGet(), } - res, err = e2e.QueryContractMethod(suite.T(), suite.testState.client1, queryContractRequest) + res, err = suite.testState.client1.QueryContractMethod(suite.T(), queryContractRequest) assert.NoError(suite.T(), err) resJSON, err := json.Marshal(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), `{"output":"2"}`, string(resJSON)) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, listener.ID) + suite.testState.client1.DeleteContractListener(suite.T(), listener.ID) } func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { @@ -212,11 +213,11 @@ func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { ffiReference := &fftypes.FFIReference{ ID: suite.interfaceID, } - listener := e2e.CreateFFIContractListener(suite.T(), suite.testState.client1, ffiReference, "Changed", &fftypes.JSONObject{ + listener := suite.testState.client1.CreateFFIContractListener(suite.T(), ffiReference, "Changed", &fftypes.JSONObject{ "address": suite.contractAddress, }) - listeners := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + listeners := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(listeners)) assert.Equal(suite.T(), listener.BackendID, listeners[0].BackendID) @@ -233,7 +234,7 @@ func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { MethodPath: "set", } - res, err := e2e.InvokeContractMethod(suite.T(), suite.testState.client1, invokeContractRequest) + res, err := suite.testState.client1.InvokeContractMethod(suite.T(), invokeContractRequest) assert.NoError(suite.T(), err) assert.NotNil(suite.T(), res) @@ -255,12 +256,12 @@ func (suite *EthereumContractTestSuite) TestFFIInvokeMethod() { Interface: suite.interfaceID, MethodPath: "get", } - res, err = e2e.QueryContractMethod(suite.T(), suite.testState.client1, queryContractRequest) + res, err = suite.testState.client1.QueryContractMethod(suite.T(), queryContractRequest) assert.NoError(suite.T(), err) resJSON, err := json.Marshal(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), `{"output":"42"}`, string(resJSON)) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, listener.ID) + suite.testState.client1.DeleteContractListener(suite.T(), listener.ID) } func (suite *EthereumContractTestSuite) TestContractAPIMethod() { @@ -278,19 +279,19 @@ func (suite *EthereumContractTestSuite) TestContractAPIMethod() { } locationBytes, _ := json.Marshal(location) - createContractAPIResult, err := e2e.CreateContractAPI(suite.T(), suite.testState.client1, APIName, ffiReference, fftypes.JSONAnyPtr(string(locationBytes))) + createContractAPIResult, err := suite.testState.client1.CreateContractAPI(suite.T(), APIName, ffiReference, fftypes.JSONAnyPtr(string(locationBytes))) assert.NotNil(suite.T(), createContractAPIResult) assert.NoError(suite.T(), err) - listener, err := e2e.CreateContractAPIListener(suite.T(), suite.testState.client1, APIName, "Changed", "firefly_e2e") + listener, err := suite.testState.client1.CreateContractAPIListener(suite.T(), APIName, "Changed", "firefly_e2e") assert.NoError(suite.T(), err) - listeners := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + listeners := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(listeners)) assert.Equal(suite.T(), listener.BackendID, listeners[0].BackendID) input := fftypes.JSONAny(`{"newValue": 42}`) - invokeResult, err := e2e.InvokeContractAPIMethod(suite.T(), suite.testState.client1, APIName, "set", &input) + invokeResult, err := suite.testState.client1.InvokeContractAPIMethod(suite.T(), APIName, "set", &input) assert.NoError(suite.T(), err) assert.NotNil(suite.T(), invokeResult) @@ -308,11 +309,11 @@ func (suite *EthereumContractTestSuite) TestContractAPIMethod() { assert.NotNil(suite.T(), event) assert.NoError(suite.T(), err) - res, err := e2e.QueryContractAPIMethod(suite.T(), suite.testState.client1, APIName, "get", fftypes.JSONAnyPtr("{}")) + res, err := suite.testState.client1.QueryContractAPIMethod(suite.T(), APIName, "get", fftypes.JSONAnyPtr("{}")) assert.NoError(suite.T(), err) resJSON, err := json.Marshal(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), `{"output":"42"}`, string(resJSON)) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, listener.ID) + suite.testState.client1.DeleteContractListener(suite.T(), listener.ID) } diff --git a/test/e2e/multiparty/fabric_contract_test.go b/test/e2e/multiparty/fabric_contract_test.go index 35e817bec..572da8a1e 100644 --- a/test/e2e/multiparty/fabric_contract_test.go +++ b/test/e2e/multiparty/fabric_contract_test.go @@ -28,6 +28,7 @@ import ( "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -131,7 +132,7 @@ func (suite *FabricContractTestSuite) SetupSuite() { stack := e2e.ReadStack(suite.T()) suite.chaincodeName = deployChaincode(suite.T(), stack.Name) - suite.fabClient = e2e.NewResty(suite.T()) + suite.fabClient = client.NewResty(suite.T()) suite.fabClient.SetBaseURL(fmt.Sprintf("http://localhost:%d", stack.Members[0].ExposedConnectorPort)) } @@ -140,7 +141,7 @@ func (suite *FabricContractTestSuite) BeforeTest(suiteName, testName string) { } func (suite *FabricContractTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) } func (suite *FabricContractTestSuite) TestE2EContractEvents() { @@ -148,12 +149,12 @@ func (suite *FabricContractTestSuite) TestE2EContractEvents() { received1 := e2e.WsReader(suite.testState.ws1, true) - sub := e2e.CreateContractListener(suite.T(), suite.testState.client1, assetCreatedEvent, &fftypes.JSONObject{ + sub := suite.testState.client1.CreateContractListener(suite.T(), assetCreatedEvent, &fftypes.JSONObject{ "channel": "firefly", "chaincode": suite.chaincodeName, }) - subs := e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + subs := suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(subs)) assert.Equal(suite.T(), sub.BackendID, subs[0].BackendID) @@ -171,13 +172,13 @@ func (suite *FabricContractTestSuite) TestE2EContractEvents() { }, } - res, err := e2e.InvokeContractMethod(suite.testState.t, suite.testState.client1, invokeContractRequest) + res, err := suite.testState.client1.InvokeContractMethod(suite.testState.t, invokeContractRequest) suite.T().Log(res) assert.NoError(suite.T(), err) <-received1 - events := e2e.GetContractEvents(suite.T(), suite.testState.client1, suite.testState.startTime, sub.ID) + events := suite.testState.client1.GetContractEvents(suite.T(), suite.testState.startTime, sub.ID) assert.Equal(suite.T(), 1, len(events)) assert.Equal(suite.T(), "AssetCreated", events[0].Name) assert.Equal(suite.T(), assetName, events[0].Output.GetString("name")) @@ -190,13 +191,13 @@ func (suite *FabricContractTestSuite) TestE2EContractEvents() { }, } - res, err = e2e.QueryContractMethod(suite.testState.t, suite.testState.client1, queryContractRequest) + res, err = suite.testState.client1.QueryContractMethod(suite.testState.t, queryContractRequest) suite.T().Log(res) assert.NoError(suite.T(), err) assert.Equal(suite.T(), assetName, res.(map[string]interface{})["name"]) - e2e.DeleteContractListener(suite.T(), suite.testState.client1, subs[0].ID) - subs = e2e.GetContractListeners(suite.T(), suite.testState.client1, suite.testState.startTime) + suite.testState.client1.DeleteContractListener(suite.T(), subs[0].ID) + subs = suite.testState.client1.GetContractListeners(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 0, len(subs)) } diff --git a/test/e2e/multiparty/identity_test.go b/test/e2e/multiparty/identity_test.go index 38c5ddc94..162e14a33 100644 --- a/test/e2e/multiparty/identity_test.go +++ b/test/e2e/multiparty/identity_test.go @@ -22,10 +22,10 @@ import ( "strings" "time" - "github.com/go-resty/resty/v2" "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -41,7 +41,7 @@ func (suite *IdentityTestSuite) BeforeTest(suiteName, testName string) { } func (suite *IdentityTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) } func (suite *IdentityTestSuite) TestCustomChildIdentityBroadcasts() { @@ -55,8 +55,7 @@ func (suite *IdentityTestSuite) TestCustomChildIdentityBroadcasts() { ts := time.Now().Unix() for i := 0; i < totalIdentities; i++ { key := getUnregisteredAccount(suite, suite.testState.org1.Name) - e2e.ClaimCustomIdentity(suite.T(), - suite.testState.client1, + suite.testState.client1.ClaimCustomIdentity(suite.T(), key, fmt.Sprintf("custom_%d_%d", ts, i), fmt.Sprintf("Description %d", i), @@ -78,15 +77,15 @@ func (suite *IdentityTestSuite) TestCustomChildIdentityBroadcasts() { identities := make(map[string]*core.Identity) for identityID := range identityIDs { - identityNode1 := e2e.GetIdentity(suite.T(), suite.testState.client1, &identityID) - identityNode2 := e2e.GetIdentity(suite.T(), suite.testState.client1, &identityID) + identityNode1 := suite.testState.client1.GetIdentity(suite.T(), &identityID) + identityNode2 := suite.testState.client2.GetIdentity(suite.T(), &identityID) assert.True(suite.T(), identityNode1.IdentityBase.Equals(ctx, &identityNode2.IdentityBase)) identities[identityNode1.DID] = identityNode1 } // Send a broadcast from each custom identity for did := range identities { - resp, err := e2e.BroadcastMessageAsIdentity(suite.T(), suite.testState.client1, did, "identitytest", &core.DataRefOrValue{ + resp, err := suite.testState.client1.BroadcastMessageAsIdentity(suite.T(), did, "identitytest", &core.DataRefOrValue{ Value: fftypes.JSONAnyPtr(`{"some": "data"}`), }, false) require.NoError(suite.T(), err) @@ -109,16 +108,14 @@ func (suite *IdentityTestSuite) TestCustomChildIdentityPrivate() { org2key := getUnregisteredAccount(suite, suite.testState.org2.Name) ts := time.Now().Unix() - custom1 := e2e.ClaimCustomIdentity(suite.T(), - suite.testState.client1, + custom1 := suite.testState.client1.ClaimCustomIdentity(suite.T(), org1key, fmt.Sprintf("custom_%d_org1priv", ts), fmt.Sprintf("Description org1priv"), nil, suite.testState.org1.ID, true) - custom2 := e2e.ClaimCustomIdentity(suite.T(), - suite.testState.client2, + custom2 := suite.testState.client2.ClaimCustomIdentity(suite.T(), org2key, fmt.Sprintf("custom_%d_org2priv", ts), fmt.Sprintf("Description org2priv"), @@ -130,9 +127,9 @@ func (suite *IdentityTestSuite) TestCustomChildIdentityPrivate() { e2e.WaitForIdentityConfirmed(suite.T(), received2) } - resp, err := e2e.PrivateMessageWithKey(suite.testState, suite.testState.client1, org1key, "topic1", &core.DataRefOrValue{ + resp, err := suite.testState.client1.PrivateMessageWithKey(org1key, "topic1", &core.DataRefOrValue{ Value: fftypes.JSONAnyPtr(`"test private custom identity"`), - }, []string{custom1.DID, custom2.DID}, "tag1", core.TransactionTypeBatchPin, true) + }, []string{custom1.DID, custom2.DID}, "tag1", core.TransactionTypeBatchPin, true, suite.testState.startTime) require.NoError(suite.T(), err) assert.Equal(suite.T(), 200, resp.StatusCode()) @@ -141,7 +138,7 @@ func (suite *IdentityTestSuite) TestCustomChildIdentityPrivate() { } func getUnregisteredAccount(suite *IdentityTestSuite, orgName string) string { - verifiers := e2e.GetVerifiers(suite.T(), suite.testState.client1) + verifiers := suite.testState.client1.GetVerifiers(suite.T()) suite.T().Logf("checking for account with orgName: %s", orgName) for i, account := range suite.testState.unregisteredAccounts { alreadyRegistered := false diff --git a/test/e2e/multiparty/multiparty_test.go b/test/e2e/multiparty/multiparty_test.go index 93cd99295..a8108ab59 100644 --- a/test/e2e/multiparty/multiparty_test.go +++ b/test/e2e/multiparty/multiparty_test.go @@ -27,11 +27,11 @@ import ( "testing" "time" - "github.com/go-resty/resty/v2" "github.com/gorilla/websocket" "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -46,8 +46,8 @@ type testState struct { org1key *core.Verifier org2 *core.Identity org2key *core.Verifier - client1 *resty.Client - client2 *resty.Client + client1 *client.FireFlyClient + client2 *client.FireFlyClient unregisteredAccounts []interface{} namespace string } @@ -72,15 +72,6 @@ func beforeE2ETest(t *testing.T) *testState { var authHeader1 http.Header var authHeader2 http.Header - ts := &testState{ - t: t, - startTime: time.Now(), - client1: e2e.NewResty(t), - client2: e2e.NewResty(t), - unregisteredAccounts: stackState.Accounts[2:], - namespace: namespace, - } - httpProtocolClient1 := "http" websocketProtocolClient1 := "ws" httpProtocolClient2 := "http" @@ -103,14 +94,23 @@ func beforeE2ETest(t *testing.T) *testState { member1WithPort = fmt.Sprintf(":%d", stack.Members[1].ExposedFireflyPort) } - ts.client1.SetBaseURL(fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort)) - ts.client2.SetBaseURL(fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient2, stack.Members[1].FireflyHostname, member1WithPort)) + base1 := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) + base2 := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient2, stack.Members[1].FireflyHostname, member1WithPort) + + ts := &testState{ + t: t, + startTime: time.Now(), + client1: client.NewFireFly(t, base1), + client2: client.NewFireFly(t, base2), + unregisteredAccounts: stackState.Accounts[2:], + namespace: namespace, + } t.Logf("Blockchain provider: %s", stack.BlockchainProvider) if stack.Members[0].Username != "" && stack.Members[0].Password != "" { t.Log("Setting auth for user 1") - ts.client1.SetBasicAuth(stack.Members[0].Username, stack.Members[0].Password) + ts.client1.Client.SetBasicAuth(stack.Members[0].Username, stack.Members[0].Password) authHeader1 = http.Header{ "Authorization": []string{fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", stack.Members[0].Username, stack.Members[0].Password))))}, } @@ -118,7 +118,7 @@ func beforeE2ETest(t *testing.T) *testState { if stack.Members[1].Username != "" && stack.Members[1].Password != "" { t.Log("Setting auth for user 2") - ts.client2.SetBasicAuth(stack.Members[1].Username, stack.Members[1].Password) + ts.client2.Client.SetBasicAuth(stack.Members[1].Username, stack.Members[1].Password) authHeader2 = http.Header{ "Authorization": []string{fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", stack.Members[1].Username, stack.Members[1].Password))))}, } @@ -130,14 +130,14 @@ func beforeE2ETest(t *testing.T) *testState { ts.namespace = namespace } - t.Logf("Client 1: " + ts.client1.HostURL) - t.Logf("Client 2: " + ts.client2.HostURL) + t.Logf("Client 1: " + ts.client1.Client.HostURL) + t.Logf("Client 2: " + ts.client2.Client.HostURL) e2e.PollForUp(t, ts.client1) e2e.PollForUp(t, ts.client2) for { - orgsC1 := e2e.GetOrgs(t, ts.client1, 200) - orgsC2 := e2e.GetOrgs(t, ts.client2, 200) + orgsC1 := ts.client1.GetOrgs(t, 200) + orgsC2 := ts.client2.GetOrgs(t, 200) if len(orgsC1) >= 2 && len(orgsC2) >= 2 { // in case there are more than two orgs in the network we need to ensure // we select the same two that were provided in the first two elements @@ -156,8 +156,8 @@ func beforeE2ETest(t *testing.T) *testState { t.Logf("Waiting for 2 orgs to appear. Currently have: node1=%d node2=%d", len(orgsC1), len(orgsC2)) time.Sleep(3 * time.Second) } - ts.org1key = e2e.GetIdentityBlockchainKeys(t, ts.client1, ts.org1.ID, 200)[0] - ts.org2key = e2e.GetIdentityBlockchainKeys(t, ts.client2, ts.org2.ID, 200)[0] + ts.org1key = ts.client1.GetIdentityBlockchainKeys(t, ts.org1.ID, 200)[0] + ts.org2key = ts.client2.GetIdentityBlockchainKeys(t, ts.org2.ID, 200)[0] t.Logf("Org1: ID=%s DID=%s Key=%s", ts.org1.DID, ts.org1.ID, ts.org1key.Value) t.Logf("Org2: ID=%s DID=%s Key=%s", ts.org2.DID, ts.org2.ID, ts.org2key.Value) @@ -198,10 +198,10 @@ func beforeE2ETest(t *testing.T) *testState { return ts } -func validateReceivedMessages(ts *testState, client *resty.Client, topic string, msgType core.MessageType, txtype core.TransactionType, count int) (data core.DataArray) { +func validateReceivedMessages(ts *testState, client *client.FireFlyClient, topic string, msgType core.MessageType, txtype core.TransactionType, count int) (data core.DataArray) { var group *fftypes.Bytes32 var messages []*core.Message - events := e2e.GetMessageEvents(ts.t, client, ts.startTime, topic, 200) + events := client.GetMessageEvents(ts.t, ts.startTime, topic, 200) for i, event := range events { if event.Message != nil { message := event.Message @@ -224,7 +224,7 @@ func validateReceivedMessages(ts *testState, client *resty.Client, topic string, assert.Equal(ts.t, core.FFStringArray{topic}, (messages)[idx].Header.Topics) assert.Equal(ts.t, topic, (messages)[idx].Header.Topics[0]) - data := e2e.GetDataForMessage(ts.t, client, ts.startTime, (messages)[idx].Header.ID) + data := client.GetDataForMessage(ts.t, ts.startTime, (messages)[idx].Header.ID) var msgData *core.Data for i, d := range data { ts.t.Logf("Data %d: %+v", i, *d) @@ -244,7 +244,7 @@ func validateReceivedMessages(ts *testState, client *resty.Client, topic string, assert.Equal(ts.t, *expectedHash, *msgData.Hash) if msgData.Blob != nil { - blob := e2e.GetBlob(ts.t, client, msgData, 200) + blob := client.GetBlob(ts.t, msgData, 200) assert.NotNil(ts.t, blob) var hash fftypes.Bytes32 = sha256.Sum256(blob) assert.Equal(ts.t, *msgData.Blob.Hash, hash) diff --git a/test/e2e/multiparty/onchain_offchain_test.go b/test/e2e/multiparty/onchain_offchain_test.go index 5fb4a7df1..016ae0122 100644 --- a/test/e2e/multiparty/onchain_offchain_test.go +++ b/test/e2e/multiparty/onchain_offchain_test.go @@ -31,6 +31,7 @@ import ( "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" @@ -46,7 +47,7 @@ func (suite *OnChainOffChainTestSuite) BeforeTest(suiteName, testName string) { } func (suite *OnChainOffChainTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) } func (suite *OnChainOffChainTestSuite) TestE2EBroadcast() { @@ -68,7 +69,7 @@ func (suite *OnChainOffChainTestSuite) TestE2EBroadcast() { expectedData[topic] = append(expectedData[topic], data) - resp, err := e2e.BroadcastMessage(suite.T(), suite.testState.client1, topic, data, false) + resp, err := suite.testState.client1.BroadcastMessage(suite.T(), topic, data, false) require.NoError(suite.T(), err) assert.Equal(suite.T(), 202, resp.StatusCode()) } @@ -110,7 +111,7 @@ func (suite *OnChainOffChainTestSuite) TestStrongDatatypesBroadcast() { } // Should be rejected as datatype not known - resp, err := e2e.BroadcastMessage(suite.T(), suite.testState.client1, "topic1", &data, true) + resp, err := suite.testState.client1.BroadcastMessage(suite.T(), "topic1", &data, true) require.NoError(suite.T(), err) assert.Equal(suite.T(), 400, resp.StatusCode()) assert.Contains(suite.T(), resp.String(), "FF10195") // datatype not found @@ -120,9 +121,9 @@ func (suite *OnChainOffChainTestSuite) TestStrongDatatypesBroadcast() { Version: version, Value: fftypes.JSONAnyPtrBytes(e2e.WidgetSchemaJSON), } - dt = e2e.CreateDatatype(suite.T(), suite.testState.client1, dt, true) + dt = suite.testState.client1.CreateDatatype(suite.T(), dt, true) - resp, err = e2e.BroadcastMessage(suite.T(), suite.testState.client1, "topic1", &data, true) + resp, err = suite.testState.client1.BroadcastMessage(suite.T(), "topic1", &data, true) require.NoError(suite.T(), err) assert.Equal(suite.T(), 400, resp.StatusCode()) assert.Contains(suite.T(), resp.String(), "FF10198") // does not conform @@ -132,7 +133,7 @@ func (suite *OnChainOffChainTestSuite) TestStrongDatatypesBroadcast() { "name": "mywidget" }`) - resp, err = e2e.BroadcastMessage(suite.T(), suite.testState.client1, "topic1", &data, true) + resp, err = suite.testState.client1.BroadcastMessage(suite.T(), "topic1", &data, true) require.NoError(suite.T(), err) assert.Equal(suite.T(), 200, resp.StatusCode()) @@ -159,10 +160,10 @@ func (suite *OnChainOffChainTestSuite) TestStrongDatatypesPrivate() { } // Should be rejected as datatype not known - resp, err := e2e.PrivateMessage(suite.testState, suite.testState.client1, "topic1", &data, []string{ + resp, err := suite.testState.client1.PrivateMessage("topic1", &data, []string{ suite.testState.org1.Name, suite.testState.org2.Name, - }, "", core.TransactionTypeBatchPin, true) + }, "", core.TransactionTypeBatchPin, true, suite.testState.startTime) require.NoError(suite.T(), err) assert.Equal(suite.T(), 400, resp.StatusCode()) assert.Contains(suite.T(), resp.String(), "FF10195") // datatype not found @@ -172,12 +173,12 @@ func (suite *OnChainOffChainTestSuite) TestStrongDatatypesPrivate() { Version: version, Value: fftypes.JSONAnyPtrBytes(e2e.WidgetSchemaJSON), } - dt = e2e.CreateDatatype(suite.T(), suite.testState.client1, dt, true) + dt = suite.testState.client1.CreateDatatype(suite.T(), dt, true) - resp, err = e2e.PrivateMessage(suite.testState, suite.testState.client1, "topic1", &data, []string{ + resp, err = suite.testState.client1.PrivateMessage("topic1", &data, []string{ suite.testState.org1.Name, suite.testState.org2.Name, - }, "", core.TransactionTypeBatchPin, false) + }, "", core.TransactionTypeBatchPin, false, suite.testState.startTime) require.NoError(suite.T(), err) assert.Equal(suite.T(), 400, resp.StatusCode()) assert.Contains(suite.T(), resp.String(), "FF10198") // does not conform @@ -187,10 +188,10 @@ func (suite *OnChainOffChainTestSuite) TestStrongDatatypesPrivate() { "name": "mywidget" }`) - resp, err = e2e.PrivateMessage(suite.testState, suite.testState.client1, "topic1", &data, []string{ + resp, err = suite.testState.client1.PrivateMessage("topic1", &data, []string{ suite.testState.org1.Name, suite.testState.org2.Name, - }, "", core.TransactionTypeBatchPin, true) + }, "", core.TransactionTypeBatchPin, true, suite.testState.startTime) require.NoError(suite.T(), err) assert.Equal(suite.T(), 200, resp.StatusCode()) @@ -218,10 +219,10 @@ func (suite *OnChainOffChainTestSuite) TestE2EPrivate() { expectedData[topic] = append(expectedData[topic], data) - resp, err := e2e.PrivateMessage(suite.testState, suite.testState.client1, topic, data, []string{ + resp, err := suite.testState.client1.PrivateMessage(topic, data, []string{ suite.testState.org1.Name, suite.testState.org2.Name, - }, "", core.TransactionTypeBatchPin, false) + }, "", core.TransactionTypeBatchPin, false, suite.testState.startTime) require.NoError(suite.T(), err) assert.Equal(suite.T(), 202, resp.StatusCode()) } @@ -252,7 +253,7 @@ func (suite *OnChainOffChainTestSuite) TestE2EBroadcastBlob() { var resp *resty.Response - data, resp, err := e2e.BroadcastBlobMessage(suite.T(), suite.testState.client1, "topic1") + data, resp, err := suite.testState.client1.BroadcastBlobMessage(suite.T(), "topic1") require.NoError(suite.T(), err) assert.Equal(suite.T(), 202, resp.StatusCode()) @@ -278,10 +279,10 @@ func (suite *OnChainOffChainTestSuite) TestE2EPrivateBlobDatatypeTagged() { var resp *resty.Response - data, resp, err := e2e.PrivateBlobMessageDatatypeTagged(suite.testState, suite.testState.client1, "topic1", []string{ + data, resp, err := suite.testState.client1.PrivateBlobMessageDatatypeTagged(suite.T(), "topic1", []string{ suite.testState.org1.Name, suite.testState.org2.Name, - }) + }, suite.testState.startTime) require.NoError(suite.T(), err) assert.Equal(suite.T(), 202, resp.StatusCode()) assert.Empty(suite.T(), data.Blob.Name) @@ -321,8 +322,8 @@ func (suite *OnChainOffChainTestSuite) TestE2EWebhookExchange() { "tag": "myrequest" } }`, suite.testState.namespace) - e2e.CleanupExistingSubscription(suite.T(), suite.testState.client2, suite.testState.namespace, "myhook") - sub := e2e.CreateSubscription(suite.T(), suite.testState.client2, subJSON, 201) + suite.testState.client2.CleanupExistingSubscription(suite.T(), suite.testState.namespace, "myhook") + sub := suite.testState.client2.CreateSubscription(suite.T(), subJSON, 201) assert.NotNil(suite.T(), sub.ID) data := core.DataRefOrValue{ @@ -330,10 +331,10 @@ func (suite *OnChainOffChainTestSuite) TestE2EWebhookExchange() { } var resp *resty.Response - resp, err := e2e.PrivateMessage(suite.testState, suite.testState.client1, "topic1", &data, []string{ + resp, err := suite.testState.client1.PrivateMessage("topic1", &data, []string{ suite.testState.org1.Name, suite.testState.org2.Name, - }, "myrequest", core.TransactionTypeBatchPin, false) + }, "myrequest", core.TransactionTypeBatchPin, false, suite.testState.startTime) require.NoError(suite.T(), err) assert.Equal(suite.T(), 202, resp.StatusCode()) @@ -377,18 +378,18 @@ func (suite *OnChainOffChainTestSuite) TestE2EWebhookRequestReplyNoTx() { "tag": "myrequest" } }`, suite.testState.namespace) - e2e.CleanupExistingSubscription(suite.T(), suite.testState.client2, suite.testState.namespace, "myhook") - sub := e2e.CreateSubscription(suite.T(), suite.testState.client2, subJSON, 201) + suite.testState.client2.CleanupExistingSubscription(suite.T(), suite.testState.namespace, "myhook") + sub := suite.testState.client2.CreateSubscription(suite.T(), subJSON, 201) assert.NotNil(suite.T(), sub.ID) data := core.DataRefOrValue{ Value: fftypes.JSONAnyPtr(`{}`), } - reply := e2e.RequestReply(suite.testState, suite.testState.client1, &data, []string{ + reply := suite.testState.client1.RequestReply(suite.T(), &data, []string{ suite.testState.org1.Name, suite.testState.org2.Name, - }, "myrequest", core.TransactionTypeUnpinned) + }, "myrequest", core.TransactionTypeUnpinned, suite.testState.startTime) assert.NotNil(suite.T(), reply) bodyData := reply.InlineData[0].Value.JSONObject().GetString("body") diff --git a/test/e2e/multiparty/tokens_test.go b/test/e2e/multiparty/tokens_test.go index a4247cf29..d882d4e06 100644 --- a/test/e2e/multiparty/tokens_test.go +++ b/test/e2e/multiparty/tokens_test.go @@ -21,10 +21,10 @@ import ( "math/rand" "time" - "github.com/go-resty/resty/v2" "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/hyperledger/firefly/test/e2e" + "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" ) @@ -46,7 +46,7 @@ func (suite *TokensTestSuite) BeforeTest(suiteName, testName string) { } func (suite *TokensTestSuite) AfterTest(suiteName, testName string) { - e2e.VerifyAllOperationsSucceeded(suite.T(), []*resty.Client{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) + e2e.VerifyAllOperationsSucceeded(suite.T(), []*client.FireFlyClient{suite.testState.client1, suite.testState.client2}, suite.testState.startTime) } func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { @@ -55,7 +55,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { received1 := e2e.WsReader(suite.testState.ws1, false) received2 := e2e.WsReader(suite.testState.ws2, false) - pools := e2e.GetTokenPools(suite.T(), suite.testState.client1, time.Unix(0, 0)) + pools := suite.testState.client1.GetTokenPools(suite.T(), time.Unix(0, 0)) rand.Seed(time.Now().UnixNano()) poolName := fmt.Sprintf("pool%d", rand.Intn(10000)) suite.T().Logf("Pool name: %s", poolName) @@ -66,11 +66,11 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { Config: fftypes.JSONObject{}, } - poolResp := e2e.CreateTokenPool(suite.T(), suite.testState.client1, pool, false) + poolResp := suite.testState.client1.CreateTokenPool(suite.T(), pool, false) poolID := poolResp.ID e2e.WaitForEvent(suite.T(), received1, core.EventTypePoolConfirmed, poolID) - pools = e2e.GetTokenPools(suite.T(), suite.testState.client1, suite.testState.startTime) + pools = suite.testState.client1.GetTokenPools(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(pools)) assert.Equal(suite.T(), suite.testState.namespace, pools[0].Namespace) assert.Equal(suite.T(), suite.connector, pools[0].Connector) @@ -79,7 +79,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { assert.NotEmpty(suite.T(), pools[0].Locator) e2e.WaitForEvent(suite.T(), received2, core.EventTypePoolConfirmed, poolID) - pools = e2e.GetTokenPools(suite.T(), suite.testState.client1, suite.testState.startTime) + pools = suite.testState.client1.GetTokenPools(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(pools)) assert.Equal(suite.T(), suite.testState.namespace, pools[0].Namespace) assert.Equal(suite.T(), suite.connector, pools[0].Connector) @@ -95,10 +95,10 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { }, Pool: poolName, } - approvalOut := e2e.TokenApproval(suite.T(), suite.testState.client1, approval, false) + approvalOut := suite.testState.client1.TokenApproval(suite.T(), approval, false) e2e.WaitForEvent(suite.T(), received1, core.EventTypeApprovalConfirmed, approvalOut.LocalID) - approvals := e2e.GetTokenApprovals(suite.T(), suite.testState.client1, poolID) + approvals := suite.testState.client1.GetTokenApprovals(suite.T(), poolID) assert.Equal(suite.T(), 1, len(approvals)) assert.Equal(suite.T(), suite.connector, approvals[0].Connector) assert.Equal(suite.T(), true, approvals[0].Approved) @@ -107,10 +107,10 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { TokenTransfer: core.TokenTransfer{Amount: *fftypes.NewFFBigInt(1)}, Pool: poolName, } - transferOut := e2e.MintTokens(suite.T(), suite.testState.client1, transfer, false) + transferOut := suite.testState.client1.MintTokens(suite.T(), transfer, false) e2e.WaitForEvent(suite.T(), received1, core.EventTypeTransferConfirmed, transferOut.LocalID) - transfers := e2e.GetTokenTransfers(suite.T(), suite.testState.client1, poolID) + transfers := suite.testState.client1.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 1, len(transfers)) assert.Equal(suite.T(), suite.connector, transfers[0].Connector) assert.Equal(suite.T(), core.TokenTransferTypeMint, transfers[0].Type) @@ -120,7 +120,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { }) e2e.WaitForEvent(suite.T(), received2, core.EventTypeTransferConfirmed, nil) - transfers = e2e.GetTokenTransfers(suite.T(), suite.testState.client2, poolID) + transfers = suite.testState.client2.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 1, len(transfers)) assert.Equal(suite.T(), suite.connector, transfers[0].Connector) assert.Equal(suite.T(), core.TokenTransferTypeMint, transfers[0].Type) @@ -145,15 +145,15 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { }, }, } - transferOut = e2e.TransferTokens(suite.T(), suite.testState.client2, transfer, false) + transferOut = suite.testState.client2.TransferTokens(suite.T(), transfer, false) e2e.WaitForEvent(suite.T(), received1, core.EventTypeMessageConfirmed, transferOut.Message) - transfers = e2e.GetTokenTransfers(suite.T(), suite.testState.client1, poolID) + transfers = suite.testState.client1.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 2, len(transfers)) assert.Equal(suite.T(), suite.connector, transfers[0].Connector) assert.Equal(suite.T(), core.TokenTransferTypeTransfer, transfers[0].Type) assert.Equal(suite.T(), int64(1), transfers[0].Amount.Int().Int64()) - data := e2e.GetDataForMessage(suite.T(), suite.testState.client1, suite.testState.startTime, transfers[0].Message) + data := suite.testState.client1.GetDataForMessage(suite.T(), suite.testState.startTime, transfers[0].Message) assert.Equal(suite.T(), 1, len(data)) assert.Equal(suite.T(), `"token approval - payment for data"`, data[0].Value.String()) e2e.ValidateAccountBalances(suite.T(), suite.testState.client1, poolID, "", map[string]int64{ @@ -162,7 +162,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { }) e2e.WaitForEvent(suite.T(), received2, core.EventTypeMessageConfirmed, transferOut.Message) - transfers = e2e.GetTokenTransfers(suite.T(), suite.testState.client2, poolID) + transfers = suite.testState.client2.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 2, len(transfers)) assert.Equal(suite.T(), suite.connector, transfers[0].Connector) assert.Equal(suite.T(), core.TokenTransferTypeTransfer, transfers[0].Type) @@ -176,10 +176,10 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { TokenTransfer: core.TokenTransfer{Amount: *fftypes.NewFFBigInt(1)}, Pool: poolName, } - transferOut = e2e.BurnTokens(suite.T(), suite.testState.client2, transfer, false) + transferOut = suite.testState.client2.BurnTokens(suite.T(), transfer, false) e2e.WaitForEvent(suite.T(), received2, core.EventTypeTransferConfirmed, transferOut.LocalID) - transfers = e2e.GetTokenTransfers(suite.T(), suite.testState.client2, poolID) + transfers = suite.testState.client2.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 3, len(transfers)) assert.Equal(suite.T(), suite.connector, transfers[0].Connector) assert.Equal(suite.T(), core.TokenTransferTypeBurn, transfers[0].Type) @@ -191,7 +191,7 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { }) e2e.WaitForEvent(suite.T(), received1, core.EventTypeTransferConfirmed, nil) - transfers = e2e.GetTokenTransfers(suite.T(), suite.testState.client1, poolID) + transfers = suite.testState.client1.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 3, len(transfers)) assert.Equal(suite.T(), suite.connector, transfers[0].Connector) assert.Equal(suite.T(), core.TokenTransferTypeBurn, transfers[0].Type) @@ -202,18 +202,18 @@ func (suite *TokensTestSuite) TestE2EFungibleTokensAsync() { suite.testState.org2key.Value: 0, }) - accounts := e2e.GetTokenAccounts(suite.T(), suite.testState.client1, poolID) + accounts := suite.testState.client1.GetTokenAccounts(suite.T(), poolID) assert.Equal(suite.T(), 2, len(accounts)) assert.Equal(suite.T(), suite.testState.org2key.Value, accounts[0].Key) assert.Equal(suite.T(), suite.testState.org1key.Value, accounts[1].Key) - accounts = e2e.GetTokenAccounts(suite.T(), suite.testState.client2, poolID) + accounts = suite.testState.client2.GetTokenAccounts(suite.T(), poolID) assert.Equal(suite.T(), 2, len(accounts)) assert.Equal(suite.T(), suite.testState.org2key.Value, accounts[0].Key) assert.Equal(suite.T(), suite.testState.org1key.Value, accounts[1].Key) - accountPools := e2e.GetTokenAccountPools(suite.T(), suite.testState.client1, suite.testState.org1key.Value) + accountPools := suite.testState.client1.GetTokenAccountPools(suite.T(), suite.testState.org1key.Value) assert.Equal(suite.T(), *poolID, *accountPools[0].Pool) - accountPools = e2e.GetTokenAccountPools(suite.T(), suite.testState.client2, suite.testState.org2key.Value) + accountPools = suite.testState.client2.GetTokenAccountPools(suite.T(), suite.testState.org2key.Value) assert.Equal(suite.T(), *poolID, *accountPools[0].Pool) } @@ -223,7 +223,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { received1 := e2e.WsReader(suite.testState.ws1, false) received2 := e2e.WsReader(suite.testState.ws2, false) - pools := e2e.GetTokenPools(suite.T(), suite.testState.client1, time.Unix(0, 0)) + pools := suite.testState.client1.GetTokenPools(suite.T(), time.Unix(0, 0)) rand.Seed(time.Now().UnixNano()) poolName := fmt.Sprintf("pool%d", rand.Intn(10000)) suite.T().Logf("Pool name: %s", poolName) @@ -234,7 +234,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { Config: fftypes.JSONObject{}, } - poolOut := e2e.CreateTokenPool(suite.T(), suite.testState.client1, pool, true) + poolOut := suite.testState.client1.CreateTokenPool(suite.T(), pool, true) assert.Equal(suite.T(), suite.testState.namespace, poolOut.Namespace) assert.Equal(suite.T(), poolName, poolOut.Name) assert.Equal(suite.T(), core.TokenTypeNonFungible, poolOut.Type) @@ -244,7 +244,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { e2e.WaitForEvent(suite.T(), received1, core.EventTypePoolConfirmed, poolID) e2e.WaitForEvent(suite.T(), received2, core.EventTypePoolConfirmed, poolID) - pools = e2e.GetTokenPools(suite.T(), suite.testState.client1, suite.testState.startTime) + pools = suite.testState.client1.GetTokenPools(suite.T(), suite.testState.startTime) assert.Equal(suite.T(), 1, len(pools)) assert.Equal(suite.T(), suite.testState.namespace, pools[0].Namespace) assert.Equal(suite.T(), poolName, pools[0].Name) @@ -259,10 +259,10 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { }, Pool: poolName, } - approvalOut := e2e.TokenApproval(suite.T(), suite.testState.client1, approval, true) + approvalOut := suite.testState.client1.TokenApproval(suite.T(), approval, true) e2e.WaitForEvent(suite.T(), received1, core.EventTypeApprovalConfirmed, approvalOut.LocalID) - approvals := e2e.GetTokenApprovals(suite.T(), suite.testState.client1, poolID) + approvals := suite.testState.client1.GetTokenApprovals(suite.T(), poolID) assert.Equal(suite.T(), 1, len(approvals)) assert.Equal(suite.T(), suite.connector, approvals[0].Connector) assert.Equal(suite.T(), true, approvals[0].Approved) @@ -274,7 +274,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { }, Pool: poolName, } - transferOut := e2e.MintTokens(suite.T(), suite.testState.client1, transfer, true) + transferOut := suite.testState.client1.MintTokens(suite.T(), transfer, true) assert.Equal(suite.T(), core.TokenTransferTypeMint, transferOut.Type) assert.Equal(suite.T(), "1", transferOut.TokenIndex) assert.Equal(suite.T(), int64(1), transferOut.Amount.Int().Int64()) @@ -284,7 +284,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { e2e.WaitForEvent(suite.T(), received1, core.EventTypeTransferConfirmed, transferOut.LocalID) e2e.WaitForEvent(suite.T(), received2, core.EventTypeTransferConfirmed, nil) - transfers := e2e.GetTokenTransfers(suite.T(), suite.testState.client2, poolID) + transfers := suite.testState.client2.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 1, len(transfers)) assert.Equal(suite.T(), core.TokenTransferTypeMint, transfers[0].Type) assert.Equal(suite.T(), "1", transfers[0].TokenIndex) @@ -310,11 +310,11 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { }, }, } - transferOut = e2e.TransferTokens(suite.T(), suite.testState.client1, transfer, true) + transferOut = suite.testState.client1.TransferTokens(suite.T(), transfer, true) assert.Equal(suite.T(), core.TokenTransferTypeTransfer, transferOut.Type) assert.Equal(suite.T(), "1", transferOut.TokenIndex) assert.Equal(suite.T(), int64(1), transferOut.Amount.Int().Int64()) - data := e2e.GetDataForMessage(suite.T(), suite.testState.client1, suite.testState.startTime, transferOut.Message) + data := suite.testState.client1.GetDataForMessage(suite.T(), suite.testState.startTime, transferOut.Message) assert.Equal(suite.T(), 1, len(data)) assert.Equal(suite.T(), `"ownership change"`, data[0].Value.String()) e2e.ValidateAccountBalances(suite.T(), suite.testState.client1, poolID, "1", map[string]int64{ @@ -324,7 +324,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { e2e.WaitForEvent(suite.T(), received1, core.EventTypeMessageConfirmed, transferOut.Message) e2e.WaitForEvent(suite.T(), received2, core.EventTypeMessageConfirmed, transferOut.Message) - transfers = e2e.GetTokenTransfers(suite.T(), suite.testState.client2, poolID) + transfers = suite.testState.client2.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 2, len(transfers)) assert.Equal(suite.T(), core.TokenTransferTypeTransfer, transfers[0].Type) assert.Equal(suite.T(), "1", transfers[0].TokenIndex) @@ -341,7 +341,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { }, Pool: poolName, } - transferOut = e2e.BurnTokens(suite.T(), suite.testState.client2, transfer, true) + transferOut = suite.testState.client2.BurnTokens(suite.T(), transfer, true) assert.Equal(suite.T(), core.TokenTransferTypeBurn, transferOut.Type) assert.Equal(suite.T(), "1", transferOut.TokenIndex) assert.Equal(suite.T(), int64(1), transferOut.Amount.Int().Int64()) @@ -352,7 +352,7 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { e2e.WaitForEvent(suite.T(), received2, core.EventTypeTransferConfirmed, transferOut.LocalID) e2e.WaitForEvent(suite.T(), received1, core.EventTypeTransferConfirmed, nil) - transfers = e2e.GetTokenTransfers(suite.T(), suite.testState.client1, poolID) + transfers = suite.testState.client1.GetTokenTransfers(suite.T(), poolID) assert.Equal(suite.T(), 3, len(transfers)) assert.Equal(suite.T(), core.TokenTransferTypeBurn, transfers[0].Type) assert.Equal(suite.T(), "1", transfers[0].TokenIndex) @@ -362,17 +362,17 @@ func (suite *TokensTestSuite) TestE2ENonFungibleTokensSync() { suite.testState.org2key.Value: 0, }) - accounts := e2e.GetTokenAccounts(suite.T(), suite.testState.client1, poolID) + accounts := suite.testState.client1.GetTokenAccounts(suite.T(), poolID) assert.Equal(suite.T(), 2, len(accounts)) assert.Equal(suite.T(), suite.testState.org2key.Value, accounts[0].Key) assert.Equal(suite.T(), suite.testState.org1key.Value, accounts[1].Key) - accounts = e2e.GetTokenAccounts(suite.T(), suite.testState.client2, poolID) + accounts = suite.testState.client2.GetTokenAccounts(suite.T(), poolID) assert.Equal(suite.T(), 2, len(accounts)) assert.Equal(suite.T(), suite.testState.org2key.Value, accounts[0].Key) assert.Equal(suite.T(), suite.testState.org1key.Value, accounts[1].Key) - accountPools := e2e.GetTokenAccountPools(suite.T(), suite.testState.client1, suite.testState.org1key.Value) + accountPools := suite.testState.client1.GetTokenAccountPools(suite.T(), suite.testState.org1key.Value) assert.Equal(suite.T(), *poolID, *accountPools[0].Pool) - accountPools = e2e.GetTokenAccountPools(suite.T(), suite.testState.client2, suite.testState.org2key.Value) + accountPools = suite.testState.client2.GetTokenAccountPools(suite.T(), suite.testState.org2key.Value) assert.Equal(suite.T(), *poolID, *accountPools[0].Pool) } From 8f87de5bd8c717bd0d937aa03385608360d7f49f Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Wed, 13 Jul 2022 14:30:23 -0400 Subject: [PATCH 5/8] Add namespace to FireFlyClient Signed-off-by: Andrew Richardson --- test/e2e/client/restclient.go | 177 +++++++++++++------------ test/e2e/gateway/gateway_test.go | 7 +- test/e2e/multiparty/multiparty_test.go | 9 +- 3 files changed, 101 insertions(+), 92 deletions(-) diff --git a/test/e2e/client/restclient.go b/test/e2e/client/restclient.go index b51d3ff5c..7d7626b46 100644 --- a/test/e2e/client/restclient.go +++ b/test/e2e/client/restclient.go @@ -23,9 +23,7 @@ import ( "fmt" "io/ioutil" "math/big" - "os" "strconv" - "strings" "testing" "time" @@ -38,35 +36,35 @@ import ( var ( urlGetNamespaces = "/namespaces" - urlUploadData = "/namespaces/default/data" - urlGetMessages = "/namespaces/default/messages" - urlBroadcastMessage = "/namespaces/default/messages/broadcast" - urlPrivateMessage = "/namespaces/default/messages/private" - urlRequestMessage = "/namespaces/default/messages/requestreply" - urlGetData = "/namespaces/default/data" - urlGetDataBlob = "/namespaces/default/data/%s/blob" - urlGetEvents = "/namespaces/default/events" - urlSubscriptions = "/namespaces/default/subscriptions" - urlDatatypes = "/namespaces/default/datatypes" - urlIdentities = "/namespaces/default/identities" - urlIdentity = "/namespaces/default/identities/%s" - urlVerifiers = "/namespaces/default/verifiers" - urlTokenPools = "/namespaces/default/tokens/pools" - urlTokenMint = "/namespaces/default/tokens/mint" - urlTokenBurn = "/namespaces/default/tokens/burn" - urlTokenTransfers = "/namespaces/default/tokens/transfers" - urlTokenApprovals = "/namespaces/default/tokens/approvals" - urlTokenAccounts = "/namespaces/default/tokens/accounts" - urlTokenBalances = "/namespaces/default/tokens/balances" - urlContractInvoke = "/namespaces/default/contracts/invoke" - urlContractQuery = "/namespaces/default/contracts/query" - urlContractInterface = "/namespaces/default/contracts/interfaces" - urlContractListeners = "/namespaces/default/contracts/listeners" - urlContractAPI = "/namespaces/default/apis" - urlBlockchainEvents = "/namespaces/default/blockchainevents" - urlOperations = "/namespaces/default/operations" - urlGetOrganizations = "/namespaces/default/network/organizations" - urlGetOrgKeys = "/namespaces/default/identities/%s/verifiers" + urlUploadData = "/data" + urlGetMessages = "/messages" + urlBroadcastMessage = "/messages/broadcast" + urlPrivateMessage = "/messages/private" + urlRequestMessage = "/messages/requestreply" + urlGetData = "/data" + urlGetDataBlob = "/data/%s/blob" + urlGetEvents = "/events" + urlSubscriptions = "/subscriptions" + urlDatatypes = "/datatypes" + urlIdentities = "/identities" + urlIdentity = "/identities/%s" + urlVerifiers = "/verifiers" + urlTokenPools = "/tokens/pools" + urlTokenMint = "/tokens/mint" + urlTokenBurn = "/tokens/burn" + urlTokenTransfers = "/tokens/transfers" + urlTokenApprovals = "/tokens/approvals" + urlTokenAccounts = "/tokens/accounts" + urlTokenBalances = "/tokens/balances" + urlContractInvoke = "/contracts/invoke" + urlContractQuery = "/contracts/query" + urlContractInterface = "/contracts/interfaces" + urlContractListeners = "/contracts/listeners" + urlContractAPI = "/apis" + urlBlockchainEvents = "/blockchainevents" + urlOperations = "/operations" + urlGetOrganizations = "/network/organizations" + urlGetOrgKeys = "/identities/%s/verifiers" ) type Logger interface { @@ -74,25 +72,24 @@ type Logger interface { } type FireFlyClient struct { - logger Logger - Client *resty.Client + logger Logger + Namespace string + Client *resty.Client } -func NewFireFly(l Logger, baseURL string) *FireFlyClient { +func NewFireFly(l Logger, baseURL, namespace string) *FireFlyClient { client := NewResty(l) client.SetBaseURL(baseURL) return &FireFlyClient{ - logger: l, - Client: client, + logger: l, + Namespace: namespace, + Client: client, } } func NewResty(l Logger) *resty.Client { client := resty.New() client.OnBeforeRequest(func(c *resty.Client, req *resty.Request) error { - if os.Getenv("NAMESPACE") != "" { - req.URL = strings.Replace(req.URL, "/namespaces/default", "/namespaces/"+os.Getenv("NAMESPACE"), 1) - } l.Logf("==> %s %s %s", req.Method, req.URL, req.QueryParam) return nil }) @@ -110,6 +107,10 @@ func NewResty(l Logger) *resty.Client { return client } +func (client *FireFlyClient) namespaced(url string) string { + return "/namespaces/" + client.Namespace + url +} + func (client *FireFlyClient) GetNamespaces() (*resty.Response, error) { return client.Client.R(). SetResult(&[]core.Namespace{}). @@ -117,7 +118,7 @@ func (client *FireFlyClient) GetNamespaces() (*resty.Response, error) { } func (client *FireFlyClient) GetMessageEvents(t *testing.T, startTime time.Time, topic string, expectedStatus int) (events []*core.EnrichedEvent) { - path := urlGetEvents + path := client.namespaced(urlGetEvents) resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetQueryParam("topic", topic). @@ -131,7 +132,7 @@ func (client *FireFlyClient) GetMessageEvents(t *testing.T, startTime time.Time, } func (client *FireFlyClient) GetMessages(t *testing.T, startTime time.Time, msgType core.MessageType, topic string, expectedStatus int) (msgs []*core.Message) { - path := urlGetMessages + path := client.namespaced(urlGetMessages) resp, err := client.Client.R(). SetQueryParam("type", string(msgType)). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). @@ -145,7 +146,7 @@ func (client *FireFlyClient) GetMessages(t *testing.T, startTime time.Time, msgT } func (client *FireFlyClient) GetData(t *testing.T, startTime time.Time, expectedStatus int) (data core.DataArray) { - path := urlGetData + path := client.namespaced(urlGetData) resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&data). @@ -156,7 +157,7 @@ func (client *FireFlyClient) GetData(t *testing.T, startTime time.Time, expected } func (client *FireFlyClient) GetDataForMessage(t *testing.T, startTime time.Time, msgID *fftypes.UUID) (data core.DataArray) { - path := urlGetMessages + path := client.namespaced(urlGetMessages) path += "/" + msgID.String() + "/data" resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). @@ -168,7 +169,7 @@ func (client *FireFlyClient) GetDataForMessage(t *testing.T, startTime time.Time } func (client *FireFlyClient) GetBlob(t *testing.T, data *core.Data, expectedStatus int) []byte { - path := fmt.Sprintf(urlGetDataBlob, data.ID) + path := client.namespaced(fmt.Sprintf(urlGetDataBlob, data.ID)) resp, err := client.Client.R(). SetDoNotParseResponse(true). Get(path) @@ -180,7 +181,7 @@ func (client *FireFlyClient) GetBlob(t *testing.T, data *core.Data, expectedStat } func (client *FireFlyClient) GetOrgs(t *testing.T, expectedStatus int) (orgs []*core.Identity) { - path := urlGetOrganizations + path := client.namespaced(urlGetOrganizations) resp, err := client.Client.R(). SetQueryParam("sort", "created"). SetResult(&orgs). @@ -191,7 +192,7 @@ func (client *FireFlyClient) GetOrgs(t *testing.T, expectedStatus int) (orgs []* } func (client *FireFlyClient) GetIdentityBlockchainKeys(t *testing.T, identityID *fftypes.UUID, expectedStatus int) (verifiers []*core.Verifier) { - path := fmt.Sprintf(urlGetOrgKeys, identityID) + path := client.namespaced(fmt.Sprintf(urlGetOrgKeys, identityID)) resp, err := client.Client.R(). SetQueryParam("type", fmt.Sprintf("!=%s", core.VerifierTypeFFDXPeerID)). SetResult(&verifiers). @@ -202,7 +203,7 @@ func (client *FireFlyClient) GetIdentityBlockchainKeys(t *testing.T, identityID } func (client *FireFlyClient) CreateSubscription(t *testing.T, input interface{}, expectedStatus int) *core.Subscription { - path := urlSubscriptions + path := client.namespaced(urlSubscriptions) var sub core.Subscription resp, err := client.Client.R(). SetBody(input). @@ -216,7 +217,7 @@ func (client *FireFlyClient) CreateSubscription(t *testing.T, input interface{}, func (client *FireFlyClient) CleanupExistingSubscription(t *testing.T, namespace, name string) { var subs []*core.Subscription - path := urlSubscriptions + path := client.namespaced(urlSubscriptions) resp, err := client.Client.R(). SetResult(&subs). Get(path) @@ -230,7 +231,7 @@ func (client *FireFlyClient) CleanupExistingSubscription(t *testing.T, namespace } func (client *FireFlyClient) DeleteSubscription(t *testing.T, id *fftypes.UUID) { - path := fmt.Sprintf("%s/%s", urlSubscriptions, id) + path := client.namespaced(fmt.Sprintf("%s/%s", urlSubscriptions, id)) resp, err := client.Client.R().Delete(path) require.NoError(t, err) require.Equal(t, 204, resp.StatusCode(), "DELETE %s [%d]: %s", path, resp.StatusCode(), resp.String()) @@ -256,7 +257,7 @@ func (client *FireFlyClient) BroadcastMessageAsIdentity(t *testing.T, did, topic }). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&msg). - Post(urlBroadcastMessage) + Post(client.namespaced(urlBroadcastMessage)) t.Logf("Sent broadcast msg: %s", msg.Header.ID) return res, err } @@ -276,7 +277,7 @@ func (client *FireFlyClient) ClaimCustomIdentity(t *testing.T, key, name, desc s }). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&identity). - Post(urlIdentities) + Post(client.namespaced(urlIdentities)) assert.NoError(t, err) assert.True(t, res.IsSuccess()) t.Logf("Identity creation initiated with key %s: %s (%s)", key, identity.ID, identity.DID) @@ -287,7 +288,7 @@ func (client *FireFlyClient) GetIdentity(t *testing.T, id *fftypes.UUID) *core.I var identity core.Identity res, err := client.Client.R(). SetResult(&identity). - Get(fmt.Sprintf(urlIdentity, id)) + Get(client.namespaced(fmt.Sprintf(urlIdentity, id))) assert.NoError(t, err) assert.True(t, res.IsSuccess()) return &identity @@ -297,7 +298,7 @@ func (client *FireFlyClient) GetVerifiers(t *testing.T) []*core.Verifier { var verifiers []*core.Verifier res, err := client.Client.R(). SetResult(&verifiers). - Get(urlVerifiers) + Get(client.namespaced(urlVerifiers)) assert.NoError(t, err) assert.True(t, res.IsSuccess()) return verifiers @@ -324,13 +325,14 @@ func (client *FireFlyClient) CreateBlob(t *testing.T, dt *core.DatatypeRef) *cor formData["datatype.name"] = dt.Name formData["datatype.version"] = dt.Version } + path := client.namespaced(urlUploadData) resp, err := client.Client.R(). SetFormData(formData). SetFileReader("file", "myfile.txt", bytes.NewReader(blob)). SetResult(&data). - Post(urlUploadData) + Post(path) require.NoError(t, err) - require.Equal(t, 201, resp.StatusCode(), "POST %s [%d]: %s", urlUploadData, resp.StatusCode(), resp.String()) + require.Equal(t, 201, resp.StatusCode(), "POST %s [%d]: %s", path, resp.StatusCode(), resp.String()) t.Logf("Data created: %s", data.ID) if dt == nil { assert.Equal(t, "data", data.Value.JSONObject().GetString("mymeta")) @@ -358,7 +360,7 @@ func (client *FireFlyClient) BroadcastBlobMessage(t *testing.T, topic string) (* {DataRef: core.DataRef{ID: data.ID}}, }, }). - Post(urlBroadcastMessage) + Post(client.namespaced(urlBroadcastMessage)) return data, res, err } @@ -386,7 +388,7 @@ func (client *FireFlyClient) PrivateBlobMessageDatatypeTagged(t *testing.T, topi Name: fmt.Sprintf("test_%d", startTime.UnixNano()), }, }). - Post(urlPrivateMessage) + Post(client.namespaced(urlPrivateMessage)) return data, res, err } @@ -423,7 +425,7 @@ func (client *FireFlyClient) PrivateMessageWithKey(key, topic string, data *core SetBody(msg). SetQueryParam("confirm", strconv.FormatBool(confirm)). SetResult(&msg.Message). - Post(urlPrivateMessage) + Post(client.namespaced(urlPrivateMessage)) client.logger.Logf("Sent private message %s to %+v", msg.Header.ID, msg.Group.Members) return res, err } @@ -449,19 +451,20 @@ func (client *FireFlyClient) RequestReply(t *testing.T, data *core.DataRefOrValu Name: fmt.Sprintf("test_%d", startTime.UnixNano()), }, } + path := client.namespaced(urlRequestMessage) var replyMsg core.MessageInOut resp, err := client.Client.R(). SetBody(msg). SetResult(&replyMsg). - Post(urlRequestMessage) + Post(path) require.NoError(t, err) - require.Equal(t, 200, resp.StatusCode(), "POST %s [%d]: %s", urlUploadData, resp.StatusCode(), resp.String()) + require.Equal(t, 200, resp.StatusCode(), "POST %s [%d]: %s", path, resp.StatusCode(), resp.String()) return &replyMsg } func (client *FireFlyClient) CreateDatatype(t *testing.T, datatype *core.Datatype, confirm bool) *core.Datatype { var dtReturn core.Datatype - path := urlDatatypes + path := client.namespaced(urlDatatypes) resp, err := client.Client.R(). SetBody(datatype). SetQueryParam("confirm", strconv.FormatBool(confirm)). @@ -478,7 +481,7 @@ func (client *FireFlyClient) CreateDatatype(t *testing.T, datatype *core.Datatyp func (client *FireFlyClient) CreateTokenPool(t *testing.T, pool *core.TokenPool, confirm bool) *core.TokenPool { var poolOut core.TokenPool - path := urlTokenPools + path := client.namespaced(urlTokenPools) resp, err := client.Client.R(). SetBody(pool). SetQueryParam("confirm", strconv.FormatBool(confirm)). @@ -494,7 +497,7 @@ func (client *FireFlyClient) CreateTokenPool(t *testing.T, pool *core.TokenPool, } func (client *FireFlyClient) GetTokenPools(t *testing.T, startTime time.Time) (pools []*core.TokenPool) { - path := urlTokenPools + path := client.namespaced(urlTokenPools) resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&pools). @@ -506,7 +509,7 @@ func (client *FireFlyClient) GetTokenPools(t *testing.T, startTime time.Time) (p func (client *FireFlyClient) MintTokens(t *testing.T, mint *core.TokenTransferInput, confirm bool) *core.TokenTransfer { var transferOut core.TokenTransfer - path := urlTokenMint + path := client.namespaced(urlTokenMint) resp, err := client.Client.R(). SetBody(mint). SetQueryParam("confirm", strconv.FormatBool(confirm)). @@ -523,7 +526,7 @@ func (client *FireFlyClient) MintTokens(t *testing.T, mint *core.TokenTransferIn func (client *FireFlyClient) BurnTokens(t *testing.T, burn *core.TokenTransferInput, confirm bool) *core.TokenTransfer { var transferOut core.TokenTransfer - path := urlTokenBurn + path := client.namespaced(urlTokenBurn) resp, err := client.Client.R(). SetBody(burn). SetQueryParam("confirm", strconv.FormatBool(confirm)). @@ -540,7 +543,7 @@ func (client *FireFlyClient) BurnTokens(t *testing.T, burn *core.TokenTransferIn func (client *FireFlyClient) TransferTokens(t *testing.T, transfer *core.TokenTransferInput, confirm bool) *core.TokenTransfer { var transferOut core.TokenTransfer - path := urlTokenTransfers + path := client.namespaced(urlTokenTransfers) resp, err := client.Client.R(). SetBody(transfer). SetQueryParam("confirm", strconv.FormatBool(confirm)). @@ -556,7 +559,7 @@ func (client *FireFlyClient) TransferTokens(t *testing.T, transfer *core.TokenTr } func (client *FireFlyClient) GetTokenTransfers(t *testing.T, poolID *fftypes.UUID) (transfers []*core.TokenTransfer) { - path := urlTokenTransfers + path := client.namespaced(urlTokenTransfers) resp, err := client.Client.R(). SetQueryParam("pool", poolID.String()). SetResult(&transfers). @@ -568,7 +571,7 @@ func (client *FireFlyClient) GetTokenTransfers(t *testing.T, poolID *fftypes.UUI func (client *FireFlyClient) TokenApproval(t *testing.T, approval *core.TokenApprovalInput, confirm bool) *core.TokenApproval { var approvalOut core.TokenApproval - path := urlTokenApprovals + path := client.namespaced(urlTokenApprovals) resp, err := client.Client.R(). SetBody(approval). SetQueryParam("confirm", strconv.FormatBool(confirm)). @@ -584,7 +587,7 @@ func (client *FireFlyClient) TokenApproval(t *testing.T, approval *core.TokenApp } func (client *FireFlyClient) GetTokenApprovals(t *testing.T, poolID *fftypes.UUID) (approvals []*core.TokenApproval) { - path := urlTokenApprovals + path := client.namespaced(urlTokenApprovals) resp, err := client.Client.R(). SetQueryParam("pool", poolID.String()). SetQueryParam("active", "true"). @@ -596,7 +599,7 @@ func (client *FireFlyClient) GetTokenApprovals(t *testing.T, poolID *fftypes.UUI } func (client *FireFlyClient) GetTokenAccounts(t *testing.T, poolID *fftypes.UUID) (accounts []*core.TokenAccount) { - path := urlTokenAccounts + path := client.namespaced(urlTokenAccounts) resp, err := client.Client.R(). SetResult(&accounts). Get(path) @@ -606,7 +609,7 @@ func (client *FireFlyClient) GetTokenAccounts(t *testing.T, poolID *fftypes.UUID } func (client *FireFlyClient) GetTokenAccountPools(t *testing.T, identity string) (pools []*core.TokenAccountPool) { - path := urlTokenAccounts + "/" + identity + "/pools" + path := client.namespaced(urlTokenAccounts + "/" + identity + "/pools") resp, err := client.Client.R(). SetQueryParam("sort", "-updated"). SetResult(&pools). @@ -618,7 +621,7 @@ func (client *FireFlyClient) GetTokenAccountPools(t *testing.T, identity string) func (client *FireFlyClient) GetTokenBalance(t *testing.T, poolID *fftypes.UUID, tokenIndex, key string) (account *core.TokenBalance) { var accounts []*core.TokenBalance - path := urlTokenBalances + path := client.namespaced(urlTokenBalances) resp, err := client.Client.R(). SetQueryParam("pool", poolID.String()). SetQueryParam("tokenIndex", tokenIndex). @@ -642,7 +645,7 @@ func (client *FireFlyClient) CreateContractListener(t *testing.T, event *fftypes }, } var sub core.ContractListener - path := urlContractListeners + path := client.namespaced(urlContractListeners) resp, err := client.Client.R(). SetBody(&body). SetResult(&sub). @@ -662,7 +665,7 @@ func (client *FireFlyClient) CreateFFIContractListener(t *testing.T, ffiReferenc EventPath: eventPath, } var listener core.ContractListener - path := urlContractListeners + path := client.namespaced(urlContractListeners) resp, err := client.Client.R(). SetBody(&body). SetResult(&listener). @@ -673,7 +676,7 @@ func (client *FireFlyClient) CreateFFIContractListener(t *testing.T, ffiReferenc } func (client *FireFlyClient) GetContractListeners(t *testing.T, startTime time.Time) (subs []*core.ContractListener) { - path := urlContractListeners + path := client.namespaced(urlContractListeners) resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&subs). @@ -684,7 +687,7 @@ func (client *FireFlyClient) GetContractListeners(t *testing.T, startTime time.T } func (client *FireFlyClient) GetContractEvents(t *testing.T, startTime time.Time, subscriptionID *fftypes.UUID) (events []*core.BlockchainEvent) { - path := urlBlockchainEvents + path := client.namespaced(urlBlockchainEvents) resp, err := client.Client.R(). SetQueryParam("timestamp", fmt.Sprintf(">%d", startTime.UnixNano())). SetQueryParam("subscriptionId", subscriptionID.String()). @@ -696,7 +699,7 @@ func (client *FireFlyClient) GetContractEvents(t *testing.T, startTime time.Time } func (client *FireFlyClient) DeleteContractListener(t *testing.T, id *fftypes.UUID) { - path := urlContractListeners + "/" + id.String() + path := client.namespaced(urlContractListeners + "/" + id.String()) resp, err := client.Client.R().Delete(path) require.NoError(t, err) require.Equal(t, 204, resp.StatusCode(), "DELETE %s [%d]: %s", path, resp.StatusCode(), resp.String()) @@ -704,7 +707,7 @@ func (client *FireFlyClient) DeleteContractListener(t *testing.T, id *fftypes.UU func (client *FireFlyClient) InvokeContractMethod(t *testing.T, req *core.ContractCallRequest) (interface{}, error) { var res interface{} - path := urlContractInvoke + path := client.namespaced(urlContractInvoke) resp, err := client.Client.R(). SetBody(req). SetResult(&res). @@ -716,7 +719,7 @@ func (client *FireFlyClient) InvokeContractMethod(t *testing.T, req *core.Contra func (client *FireFlyClient) QueryContractMethod(t *testing.T, req *core.ContractCallRequest) (interface{}, error) { var res interface{} - path := urlContractQuery + path := client.namespaced(urlContractQuery) resp, err := client.Client.R(). SetBody(req). SetResult(&res). @@ -728,7 +731,7 @@ func (client *FireFlyClient) QueryContractMethod(t *testing.T, req *core.Contrac func (client *FireFlyClient) CreateFFI(t *testing.T, ffi *fftypes.FFI) (interface{}, error) { var res interface{} - path := urlContractInterface + path := client.namespaced(urlContractInterface) resp, err := client.Client.R(). SetBody(ffi). SetResult(&res). @@ -747,7 +750,7 @@ func (client *FireFlyClient) CreateContractAPI(t *testing.T, name string, ffiRef } var res interface{} - path := urlContractAPI + path := client.namespaced(urlContractAPI) resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&res). @@ -763,7 +766,7 @@ func (client *FireFlyClient) InvokeContractAPIMethod(t *testing.T, apiName strin "input": input, } var res interface{} - path := fmt.Sprintf("%s/%s/invoke/%s", urlContractAPI, apiName, methodName) + path := client.namespaced(fmt.Sprintf("%s/%s/invoke/%s", urlContractAPI, apiName, methodName)) resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&res). @@ -779,7 +782,7 @@ func (client *FireFlyClient) QueryContractAPIMethod(t *testing.T, apiName string "input": input, } var res interface{} - path := fmt.Sprintf("%s/%s/query/%s", urlContractAPI, apiName, methodName) + path := client.namespaced(fmt.Sprintf("%s/%s/query/%s", urlContractAPI, apiName, methodName)) resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&res). @@ -794,7 +797,7 @@ func (client *FireFlyClient) CreateContractAPIListener(t *testing.T, apiName, ev "topic": topic, } var listener core.ContractListener - path := fmt.Sprintf("%s/%s/listeners/%s", urlContractAPI, apiName, eventName) + path := client.namespaced(fmt.Sprintf("%s/%s/listeners/%s", urlContractAPI, apiName, eventName)) resp, err := client.Client.R(). SetBody(apiReqBody). SetResult(&listener). @@ -806,7 +809,7 @@ func (client *FireFlyClient) CreateContractAPIListener(t *testing.T, apiName, ev func (client *FireFlyClient) GetEvent(t *testing.T, eventID string) (interface{}, error) { var res interface{} - path := fmt.Sprintf("%s/%s", urlGetEvents, eventID) + path := client.namespaced(fmt.Sprintf("%s/%s", urlGetEvents, eventID)) resp, err := client.Client.R(). SetResult(&res). Get(path) @@ -817,7 +820,7 @@ func (client *FireFlyClient) GetEvent(t *testing.T, eventID string) (interface{} func (client *FireFlyClient) GetBlockchainEvent(t *testing.T, eventID string) (interface{}, error) { var res interface{} - path := fmt.Sprintf("%s/%s", urlBlockchainEvents, eventID) + path := client.namespaced(fmt.Sprintf("%s/%s", urlBlockchainEvents, eventID)) resp, err := client.Client.R(). SetResult(&res). Get(path) @@ -827,7 +830,7 @@ func (client *FireFlyClient) GetBlockchainEvent(t *testing.T, eventID string) (i } func (client *FireFlyClient) GetOperations(t *testing.T, startTime time.Time) (operations []*core.Operation) { - path := urlOperations + path := client.namespaced(urlOperations) resp, err := client.Client.R(). SetQueryParam("created", fmt.Sprintf(">%d", startTime.UnixNano())). SetResult(&operations). diff --git a/test/e2e/gateway/gateway_test.go b/test/e2e/gateway/gateway_test.go index 4296eb0f9..8bafda31d 100644 --- a/test/e2e/gateway/gateway_test.go +++ b/test/e2e/gateway/gateway_test.go @@ -56,7 +56,6 @@ func (m *testState) Done() func() { func beforeE2ETest(t *testing.T) *testState { stack := e2e.ReadStack(t) stackState := e2e.ReadStackState(t) - namespace := "default" var authHeader1 http.Header @@ -73,11 +72,15 @@ func beforeE2ETest(t *testing.T) *testState { } baseURL := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) + namespace := os.Getenv("NAMESPACE") + if namespace == "" { + namespace = "default" + } ts := &testState{ t: t, startTime: time.Now(), - client1: client.NewFireFly(t, baseURL), + client1: client.NewFireFly(t, baseURL, namespace), unregisteredAccounts: stackState.Accounts[2:], namespace: namespace, } diff --git a/test/e2e/multiparty/multiparty_test.go b/test/e2e/multiparty/multiparty_test.go index a8108ab59..eeb03d7ed 100644 --- a/test/e2e/multiparty/multiparty_test.go +++ b/test/e2e/multiparty/multiparty_test.go @@ -67,7 +67,6 @@ func (m *testState) Done() func() { func beforeE2ETest(t *testing.T) *testState { stack := e2e.ReadStack(t) stackState := e2e.ReadStackState(t) - namespace := "default" var authHeader1 http.Header var authHeader2 http.Header @@ -96,12 +95,16 @@ func beforeE2ETest(t *testing.T) *testState { base1 := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) base2 := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient2, stack.Members[1].FireflyHostname, member1WithPort) + namespace := os.Getenv("NAMESPACE") + if namespace == "" { + namespace = "default" + } ts := &testState{ t: t, startTime: time.Now(), - client1: client.NewFireFly(t, base1), - client2: client.NewFireFly(t, base2), + client1: client.NewFireFly(t, base1, namespace), + client2: client.NewFireFly(t, base2, namespace), unregisteredAccounts: stackState.Accounts[2:], namespace: namespace, } From abe53e81e5b66b9a2136facaf923f4292a0ba0a8 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Wed, 13 Jul 2022 15:44:02 -0400 Subject: [PATCH 6/8] Add websocket to FireFlyClient Signed-off-by: Andrew Richardson --- test/e2e/client/restclient.go | 30 ++++++++++++++++++-- test/e2e/gateway/gateway_test.go | 23 ++-------------- test/e2e/multiparty/multiparty_test.go | 38 +++----------------------- 3 files changed, 34 insertions(+), 57 deletions(-) diff --git a/test/e2e/client/restclient.go b/test/e2e/client/restclient.go index 7d7626b46..9fca08af8 100644 --- a/test/e2e/client/restclient.go +++ b/test/e2e/client/restclient.go @@ -23,11 +23,15 @@ import ( "fmt" "io/ioutil" "math/big" + "net/http" + "net/url" "strconv" + "strings" "testing" "time" "github.com/go-resty/resty/v2" + "github.com/gorilla/websocket" "github.com/hyperledger/firefly-common/pkg/fftypes" "github.com/hyperledger/firefly/pkg/core" "github.com/stretchr/testify/assert" @@ -73,15 +77,17 @@ type Logger interface { type FireFlyClient struct { logger Logger + Hostname string Namespace string Client *resty.Client } -func NewFireFly(l Logger, baseURL, namespace string) *FireFlyClient { +func NewFireFly(l Logger, hostname, namespace string) *FireFlyClient { client := NewResty(l) - client.SetBaseURL(baseURL) + client.SetBaseURL(hostname + "/api/v1") return &FireFlyClient{ logger: l, + Hostname: hostname, Namespace: namespace, Client: client, } @@ -111,6 +117,26 @@ func (client *FireFlyClient) namespaced(url string) string { return "/namespaces/" + client.Namespace + url } +func (client *FireFlyClient) WebSocket(t *testing.T, query string, authHeader http.Header) *websocket.Conn { + u, _ := url.Parse(client.Hostname) + scheme := "ws" + if strings.Contains(client.Hostname, "https") { + scheme = "wss" + } + wsURL := url.URL{ + Scheme: scheme, + Host: u.Host, + Path: "/ws", + RawQuery: query, + } + ws, resp, err := websocket.DefaultDialer.Dial(wsURL.String(), authHeader) + require.NoError(t, err) + if resp != nil { + resp.Body.Close() + } + return ws +} + func (client *FireFlyClient) GetNamespaces() (*resty.Response, error) { return client.Client.R(). SetResult(&[]core.Namespace{}). diff --git a/test/e2e/gateway/gateway_test.go b/test/e2e/gateway/gateway_test.go index 8bafda31d..764a5afa5 100644 --- a/test/e2e/gateway/gateway_test.go +++ b/test/e2e/gateway/gateway_test.go @@ -20,7 +20,6 @@ import ( "encoding/base64" "fmt" "net/http" - "net/url" "os" "testing" "time" @@ -28,7 +27,6 @@ import ( "github.com/gorilla/websocket" "github.com/hyperledger/firefly/test/e2e" "github.com/hyperledger/firefly/test/e2e/client" - "github.com/stretchr/testify/require" ) type testState struct { @@ -60,10 +58,8 @@ func beforeE2ETest(t *testing.T) *testState { var authHeader1 http.Header httpProtocolClient1 := "http" - websocketProtocolClient1 := "ws" if stack.Members[0].UseHTTPS { httpProtocolClient1 = "https" - websocketProtocolClient1 = "wss" } member0WithPort := "" @@ -71,7 +67,7 @@ func beforeE2ETest(t *testing.T) *testState { member0WithPort = fmt.Sprintf(":%d", stack.Members[0].ExposedFireflyPort) } - baseURL := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) + baseURL := fmt.Sprintf("%s://%s%s", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) namespace := os.Getenv("NAMESPACE") if namespace == "" { namespace = "default" @@ -106,22 +102,7 @@ func beforeE2ETest(t *testing.T) *testState { eventNames := "message_confirmed|token_pool_confirmed|token_transfer_confirmed|blockchain_event_received|token_approval_confirmed|identity_confirmed" queryString := fmt.Sprintf("namespace=%s&ephemeral&autoack&filter.events=%s&changeevents=.*", ts.namespace, eventNames) - - wsUrl1 := url.URL{ - Scheme: websocketProtocolClient1, - Host: fmt.Sprintf("%s%s", stack.Members[0].FireflyHostname, member0WithPort), - Path: "/ws", - RawQuery: queryString, - } - - t.Logf("Websocket 1: " + wsUrl1.String()) - - var err error - ts.ws1, _, err = websocket.DefaultDialer.Dial(wsUrl1.String(), authHeader1) - if err != nil { - t.Logf(err.Error()) - } - require.NoError(t, err) + ts.ws1 = ts.client1.WebSocket(t, queryString, authHeader1) ts.done = func() { ts.ws1.Close() diff --git a/test/e2e/multiparty/multiparty_test.go b/test/e2e/multiparty/multiparty_test.go index eeb03d7ed..1da5aa624 100644 --- a/test/e2e/multiparty/multiparty_test.go +++ b/test/e2e/multiparty/multiparty_test.go @@ -22,7 +22,6 @@ import ( "encoding/base64" "fmt" "net/http" - "net/url" "os" "testing" "time" @@ -33,7 +32,6 @@ import ( "github.com/hyperledger/firefly/test/e2e" "github.com/hyperledger/firefly/test/e2e/client" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) type testState struct { @@ -72,16 +70,12 @@ func beforeE2ETest(t *testing.T) *testState { var authHeader2 http.Header httpProtocolClient1 := "http" - websocketProtocolClient1 := "ws" httpProtocolClient2 := "http" - websocketProtocolClient2 := "ws" if stack.Members[0].UseHTTPS { httpProtocolClient1 = "https" - websocketProtocolClient1 = "wss" } if stack.Members[1].UseHTTPS { httpProtocolClient2 = "https" - websocketProtocolClient2 = "wss" } member0WithPort := "" @@ -93,8 +87,8 @@ func beforeE2ETest(t *testing.T) *testState { member1WithPort = fmt.Sprintf(":%d", stack.Members[1].ExposedFireflyPort) } - base1 := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) - base2 := fmt.Sprintf("%s://%s%s/api/v1", httpProtocolClient2, stack.Members[1].FireflyHostname, member1WithPort) + base1 := fmt.Sprintf("%s://%s%s", httpProtocolClient1, stack.Members[0].FireflyHostname, member0WithPort) + base2 := fmt.Sprintf("%s://%s%s", httpProtocolClient2, stack.Members[1].FireflyHostname, member1WithPort) namespace := os.Getenv("NAMESPACE") if namespace == "" { namespace = "default" @@ -166,32 +160,8 @@ func beforeE2ETest(t *testing.T) *testState { eventNames := "message_confirmed|token_pool_confirmed|token_transfer_confirmed|blockchain_event_received|token_approval_confirmed|identity_confirmed" queryString := fmt.Sprintf("namespace=%s&ephemeral&autoack&filter.events=%s&changeevents=.*", ts.namespace, eventNames) - - wsUrl1 := url.URL{ - Scheme: websocketProtocolClient1, - Host: fmt.Sprintf("%s%s", stack.Members[0].FireflyHostname, member0WithPort), - Path: "/ws", - RawQuery: queryString, - } - wsUrl2 := url.URL{ - Scheme: websocketProtocolClient2, - Host: fmt.Sprintf("%s%s", stack.Members[1].FireflyHostname, member1WithPort), - Path: "/ws", - RawQuery: queryString, - } - - t.Logf("Websocket 1: " + wsUrl1.String()) - t.Logf("Websocket 2: " + wsUrl2.String()) - - var err error - ts.ws1, _, err = websocket.DefaultDialer.Dial(wsUrl1.String(), authHeader1) - if err != nil { - t.Logf(err.Error()) - } - require.NoError(t, err) - - ts.ws2, _, err = websocket.DefaultDialer.Dial(wsUrl2.String(), authHeader2) - require.NoError(t, err) + ts.ws1 = ts.client1.WebSocket(t, queryString, authHeader1) + ts.ws2 = ts.client2.WebSocket(t, queryString, authHeader2) ts.done = func() { ts.ws1.Close() From 7f2a4141d551010103e25502d08368a212f7a864 Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Fri, 15 Jul 2022 13:46:27 -0400 Subject: [PATCH 7/8] Remove extra caching of root org identity There is now a general-purpose identityCache for all identities, which takes the namespace into account (particularly important when resolving V1 identities between the current namespace and ff_system). Signed-off-by: Andrew Richardson --- internal/identity/identitymanager.go | 5 ----- internal/identity/identitymanager_test.go | 11 ----------- 2 files changed, 16 deletions(-) diff --git a/internal/identity/identitymanager.go b/internal/identity/identitymanager.go index 89ef88cf6..78d44b510 100644 --- a/internal/identity/identitymanager.go +++ b/internal/identity/identitymanager.go @@ -61,7 +61,6 @@ type identityManager struct { namespace string defaultKey string multipartyRootVerifier *core.VerifierRef - multipartyRootOrg *core.Identity identityCacheTTL time.Duration identityCache *ccache.Cache signingKeyCacheTTL time.Duration @@ -303,9 +302,6 @@ func (im *identityManager) FindIdentityForVerifier(ctx context.Context, iTypes [ // GetMultipartyRootOrg returns the identity of the organization that owns the node, if fully registered within the given namespace func (im *identityManager) GetMultipartyRootOrg(ctx context.Context) (*core.Identity, error) { - if im.multipartyRootOrg != nil { - return im.multipartyRootOrg, nil - } verifierRef, err := im.GetMultipartyRootVerifier(ctx) if err != nil { return nil, err @@ -320,7 +316,6 @@ func (im *identityManager) GetMultipartyRootOrg(ctx context.Context) (*core.Iden if identity.Type != core.IdentityTypeOrg || identity.Name != orgName { return nil, i18n.NewError(ctx, coremsgs.MsgLocalOrgLookupFailed, orgName, verifierRef.Value) } - im.multipartyRootOrg = identity return identity, nil } diff --git a/internal/identity/identitymanager_test.go b/internal/identity/identitymanager_test.go index dfa08f612..a99c911a7 100644 --- a/internal/identity/identitymanager_test.go +++ b/internal/identity/identitymanager_test.go @@ -738,17 +738,6 @@ func TestNormalizeKeyViaBlockchainPluginCached(t *testing.T) { } -func TestGetMultipartyRootOrgCached(t *testing.T) { - - ctx, im := newTestIdentityManager(t) - im.multipartyRootOrg = &core.Identity{} - - id, err := im.GetMultipartyRootOrg(ctx) - assert.NoError(t, err) - assert.NotNil(t, id) - -} - func TestGetMultipartyRootVerifierNotSet(t *testing.T) { ctx, im := newTestIdentityManager(t) From d295062c48fcff6d7c7894068f48e8d2e9b3451d Mon Sep 17 00:00:00 2001 From: Andrew Richardson Date: Fri, 15 Jul 2022 22:48:56 -0400 Subject: [PATCH 8/8] Clean up comment on SetHandler Signed-off-by: Andrew Richardson --- pkg/blockchain/plugin.go | 2 +- pkg/database/plugin.go | 2 +- pkg/dataexchange/plugin.go | 2 +- pkg/identity/plugin.go | 2 +- pkg/sharedstorage/plugin.go | 2 +- pkg/tokens/plugin.go | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pkg/blockchain/plugin.go b/pkg/blockchain/plugin.go index 59993011c..895e8288a 100644 --- a/pkg/blockchain/plugin.go +++ b/pkg/blockchain/plugin.go @@ -36,7 +36,7 @@ type Plugin interface { Init(ctx context.Context, config config.Section, metrics metrics.Manager) error // SetHandler registers a handler to receive callbacks - // If namespace is set, plugin will attempt to deliver only events for that namespace + // Plugin will attempt (but is not guaranteed) to deliver events only for the given namespace SetHandler(namespace string, handler Callbacks) // SetOperationHandler registers a handler to receive async operation status diff --git a/pkg/database/plugin.go b/pkg/database/plugin.go index abb1b85ce..1110d55b0 100644 --- a/pkg/database/plugin.go +++ b/pkg/database/plugin.go @@ -59,7 +59,7 @@ type Plugin interface { Init(ctx context.Context, config config.Section) error // SetHandler registers a handler to receive callbacks - // If namespace is set, plugin will attempt to deliver only events for that namespace + // Plugin will attempt (but is not guaranteed) to deliver events only for the given namespace SetHandler(namespace string, handler Callbacks) // Capabilities returns capabilities - not called until after Init diff --git a/pkg/dataexchange/plugin.go b/pkg/dataexchange/plugin.go index 285ff13af..097d4776c 100644 --- a/pkg/dataexchange/plugin.go +++ b/pkg/dataexchange/plugin.go @@ -67,7 +67,7 @@ type Plugin interface { SetNodes(nodes []fftypes.JSONObject) // SetHandler registers a handler to receive callbacks - // If namespace is set, plugin will attempt to deliver only events for that namespace + // Plugin will attempt (but is not guaranteed) to deliver events only for the given namespace SetHandler(namespace string, handler Callbacks) // Data exchange interface must not deliver any events until start is called diff --git a/pkg/identity/plugin.go b/pkg/identity/plugin.go index 7fa46d944..c6c13d407 100644 --- a/pkg/identity/plugin.go +++ b/pkg/identity/plugin.go @@ -34,7 +34,7 @@ type Plugin interface { Init(ctx context.Context, config config.Section) error // SetHandler registers a handler to receive callbacks - // If namespace is set, plugin will attempt to deliver only events for that namespace + // Plugin will attempt (but is not guaranteed) to deliver events only for the given namespace SetHandler(namespace string, handler Callbacks) // Blockchain interface must not deliver any events until start is called diff --git a/pkg/sharedstorage/plugin.go b/pkg/sharedstorage/plugin.go index 49ab0ef44..4f98046c0 100644 --- a/pkg/sharedstorage/plugin.go +++ b/pkg/sharedstorage/plugin.go @@ -35,7 +35,7 @@ type Plugin interface { Init(ctx context.Context, config config.Section) error // SetHandler registers a handler to receive callbacks - // If namespace is set, plugin will attempt to deliver only events for that namespace + // Plugin will attempt (but is not guaranteed) to deliver events only for the given namespace SetHandler(namespace string, handler Callbacks) // Capabilities returns capabilities - not called until after Init diff --git a/pkg/tokens/plugin.go b/pkg/tokens/plugin.go index 7982a58c9..d4783391e 100644 --- a/pkg/tokens/plugin.go +++ b/pkg/tokens/plugin.go @@ -36,7 +36,7 @@ type Plugin interface { Init(ctx context.Context, name string, config config.Section) error // SetHandler registers a handler to receive callbacks - // If namespace is set, plugin will attempt to deliver only events for that namespace + // Plugin will attempt (but is not guaranteed) to deliver events only for the given namespace SetHandler(namespace string, handler Callbacks) error // SetOperationHandler registers a handler to receive async operation status