diff --git a/Makefile b/Makefile index 358b8f8c4..799f0e05b 100644 --- a/Makefile +++ b/Makefile @@ -49,11 +49,14 @@ statusgo-ios-simulator-mainnet: xgo ci: build/env.sh go test -v -cover ./geth + build/env.sh go test -v -cover ./geth/jail build/env.sh go test -v -cover ./extkeys -test-all: +test: @build/env.sh echo "mode: set" > coverage-all.out - build/env.sh go test -coverprofile=coverage.out -covermode=set ./geth/... + build/env.sh go test -coverprofile=coverage.out -covermode=set ./geth + @build/env.sh tail -n +2 coverage.out >> coverage-all.out + build/env.sh go test -coverprofile=coverage.out -covermode=set ./geth/jail @build/env.sh tail -n +2 coverage.out >> coverage-all.out build/env.sh go test -coverprofile=coverage.out -covermode=set ./extkeys @build/env.sh tail -n +2 coverage.out >> coverage-all.out @@ -62,10 +65,13 @@ test-all: @build/env.sh go tool cover -html=coverage-all.out -o coverage.html @build/env.sh go tool cover -func=coverage-all.out -test: test-all - test-geth: - build/env.sh go test -v -coverprofile=coverage.out ./geth/... + build/env.sh go test -v -coverprofile=coverage.out ./geth + @build/env.sh go tool cover -html=coverage.out -o coverage.html + @build/env.sh go tool cover -func=coverage.out + +test-jail: + build/env.sh go test -v -coverprofile=coverage.out ./geth/jail @build/env.sh go tool cover -html=coverage.out -o coverage.html @build/env.sh go tool cover -func=coverage.out diff --git a/cmd/status/utils.go b/cmd/status/utils.go index 176fac8ed..9a5edf831 100644 --- a/cmd/status/utils.go +++ b/cmd/status/utils.go @@ -17,15 +17,16 @@ import ( "github.com/status-im/status-go/geth" ) -const ( - testDataDir = "../../.ethereumtest" - testNodeSyncSeconds = 30 - testAddress = "0xadaf150b905cf5e6a778e553e15a139b6618bbb7" - testAddressPassword = "asdfasdf" - newAccountPassword = "badpassword" - testAddress1 = "0xadd4d1d02e71c7360c53296968e59d57fd15e2ba" - testStatusJsFile = "../../jail/testdata/status.js" -) +var testConfig *geth.TestConfig + +func init() { + // load shared test configuration + var err error + testConfig, err = geth.LoadTestConfig() + if err != nil { + panic(err) + } +} func testExportedAPI(t *testing.T, done chan struct{}) { <-startTestNode(t) @@ -110,7 +111,7 @@ func testResetChainData(t *testing.T) bool { return false } - time.Sleep(testNodeSyncSeconds * time.Second) // allow to re-sync blockchain + time.Sleep(testConfig.Node.SyncSeconds * time.Second) // allow to re-sync blockchain testCompleteTransaction(t) @@ -126,7 +127,7 @@ func testStopResumeNode(t *testing.T) bool { } // create an account - address1, pubKey1, _, err := geth.CreateAccount(newAccountPassword) + address1, pubKey1, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false @@ -140,7 +141,7 @@ func testStopResumeNode(t *testing.T) bool { // select account loginResponse := geth.JSONError{} - rawResponse := Login(C.CString(address1), C.CString(newAccountPassword)) + rawResponse := Login(C.CString(address1), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &loginResponse); err != nil { t.Errorf("cannot decode RecoverAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -265,7 +266,7 @@ func testCreateChildAccount(t *testing.T) bool { // create an account createAccountResponse := geth.AccountInfo{} - rawResponse := CreateAccount(C.CString(newAccountPassword)) + rawResponse := CreateAccount(C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &createAccountResponse); err != nil { t.Errorf("cannot decode CreateAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -286,7 +287,7 @@ func testCreateChildAccount(t *testing.T) bool { } // obtain decrypted key, and make sure that extended key (which will be used as root for sub-accounts) is present - account, key, err := keyStore.AccountDecryptedKey(account, newAccountPassword) + account, key, err := keyStore.AccountDecryptedKey(account, testConfig.Account1.Password) if err != nil { t.Errorf("can not obtain decrypted account key: %v", err) return false @@ -299,7 +300,7 @@ func testCreateChildAccount(t *testing.T) bool { // try creating sub-account, w/o selecting main account i.e. w/o login to main account createSubAccountResponse := geth.AccountInfo{} - rawResponse = CreateChildAccount(C.CString(""), C.CString(newAccountPassword)) + rawResponse = CreateChildAccount(C.CString(""), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &createSubAccountResponse); err != nil { t.Errorf("cannot decode CreateChildAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -311,7 +312,7 @@ func testCreateChildAccount(t *testing.T) bool { return false } - err = geth.SelectAccount(address, newAccountPassword) + err = geth.SelectAccount(address, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return false @@ -333,7 +334,7 @@ func testCreateChildAccount(t *testing.T) bool { // create sub-account (from implicit parent) createSubAccountResponse1 := geth.AccountInfo{} - rawResponse = CreateChildAccount(C.CString(""), C.CString(newAccountPassword)) + rawResponse = CreateChildAccount(C.CString(""), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &createSubAccountResponse1); err != nil { t.Errorf("cannot decode CreateChildAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -347,7 +348,7 @@ func testCreateChildAccount(t *testing.T) bool { // make sure that sub-account index automatically progresses createSubAccountResponse2 := geth.AccountInfo{} - rawResponse = CreateChildAccount(C.CString(""), C.CString(newAccountPassword)) + rawResponse = CreateChildAccount(C.CString(""), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &createSubAccountResponse2); err != nil { t.Errorf("cannot decode CreateChildAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -365,7 +366,7 @@ func testCreateChildAccount(t *testing.T) bool { // create sub-account (from explicit parent) createSubAccountResponse3 := geth.AccountInfo{} - rawResponse = CreateChildAccount(C.CString(createSubAccountResponse2.Address), C.CString(newAccountPassword)) + rawResponse = CreateChildAccount(C.CString(createSubAccountResponse2.Address), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &createSubAccountResponse3); err != nil { t.Errorf("cannot decode CreateChildAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -391,7 +392,7 @@ func testRecoverAccount(t *testing.T) bool { keyStore, _ := geth.NodeManagerInstance().AccountKeyStore() // create an account - address, pubKey, mnemonic, err := geth.CreateAccount(newAccountPassword) + address, pubKey, mnemonic, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false @@ -400,7 +401,7 @@ func testRecoverAccount(t *testing.T) bool { // try recovering using password + mnemonic recoverAccountResponse := geth.AccountInfo{} - rawResponse := RecoverAccount(C.CString(newAccountPassword), C.CString(mnemonic)) + rawResponse := RecoverAccount(C.CString(testConfig.Account1.Password), C.CString(mnemonic)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &recoverAccountResponse); err != nil { t.Errorf("cannot decode RecoverAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -422,19 +423,19 @@ func testRecoverAccount(t *testing.T) bool { t.Errorf("can not get account from address: %v", err) } - account, key, err := keyStore.AccountDecryptedKey(account, newAccountPassword) + account, key, err := keyStore.AccountDecryptedKey(account, testConfig.Account1.Password) if err != nil { t.Errorf("can not obtain decrypted account key: %v", err) return false } extChild2String := key.ExtendedKey.String() - if err := keyStore.Delete(account, newAccountPassword); err != nil { + if err := keyStore.Delete(account, testConfig.Account1.Password); err != nil { t.Errorf("cannot remove account: %v", err) } recoverAccountResponse = geth.AccountInfo{} - rawResponse = RecoverAccount(C.CString(newAccountPassword), C.CString(mnemonic)) + rawResponse = RecoverAccount(C.CString(testConfig.Account1.Password), C.CString(mnemonic)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &recoverAccountResponse); err != nil { t.Errorf("cannot decode RecoverAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -451,7 +452,7 @@ func testRecoverAccount(t *testing.T) bool { } // make sure that extended key exists and is imported ok too - account, key, err = keyStore.AccountDecryptedKey(account, newAccountPassword) + account, key, err = keyStore.AccountDecryptedKey(account, testConfig.Account1.Password) if err != nil { t.Errorf("can not obtain decrypted account key: %v", err) return false @@ -462,7 +463,7 @@ func testRecoverAccount(t *testing.T) bool { // make sure that calling import several times, just returns from cache (no error is expected) recoverAccountResponse = geth.AccountInfo{} - rawResponse = RecoverAccount(C.CString(newAccountPassword), C.CString(mnemonic)) + rawResponse = RecoverAccount(C.CString(testConfig.Account1.Password), C.CString(mnemonic)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &recoverAccountResponse); err != nil { t.Errorf("cannot decode RecoverAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -488,7 +489,7 @@ func testRecoverAccount(t *testing.T) bool { if whisperService.HasIdentity(crypto.ToECDSAPub(common.FromHex(pubKeyCheck))) { t.Error("identity already present in whisper") } - err = geth.SelectAccount(addressCheck, newAccountPassword) + err = geth.SelectAccount(addressCheck, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return false @@ -508,14 +509,14 @@ func testAccountSelect(t *testing.T) bool { } // create an account - address1, pubKey1, _, err := geth.CreateAccount(newAccountPassword) + address1, pubKey1, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false } t.Logf("Account created: {address: %s, key: %s}", address1, pubKey1) - address2, pubKey2, _, err := geth.CreateAccount(newAccountPassword) + address2, pubKey2, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Error("Test failed: could not create account") return false @@ -542,7 +543,7 @@ func testAccountSelect(t *testing.T) bool { } loginResponse = geth.JSONError{} - rawResponse = Login(C.CString(address1), C.CString(newAccountPassword)) + rawResponse = Login(C.CString(address1), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &loginResponse); err != nil { t.Errorf("cannot decode RecoverAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -563,7 +564,7 @@ func testAccountSelect(t *testing.T) bool { } loginResponse = geth.JSONError{} - rawResponse = Login(C.CString(address2), C.CString(newAccountPassword)) + rawResponse = Login(C.CString(address2), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &loginResponse); err != nil { t.Errorf("cannot decode RecoverAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -592,7 +593,7 @@ func testAccountLogout(t *testing.T) bool { } // create an account - address, pubKey, _, err := geth.CreateAccount(newAccountPassword) + address, pubKey, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return false @@ -605,7 +606,7 @@ func testAccountLogout(t *testing.T) bool { } // select/login - err = geth.SelectAccount(address, newAccountPassword) + err = geth.SelectAccount(address, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return false @@ -650,8 +651,8 @@ func testCompleteTransaction(t *testing.T) bool { backend.TransactionQueue().Reset() // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return false } @@ -670,11 +671,10 @@ func testCompleteTransaction(t *testing.T) bool { } if envelope.Type == geth.EventTransactionQueued { event := envelope.Event.(map[string]interface{}) - t.Logf("transaction queued (will be completed in 5 secs): {id: %s}\n", event["id"].(string)) - time.Sleep(5 * time.Second) + t.Logf("transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string)) completeTxResponse := geth.CompleteTransactionResult{} - rawResponse := CompleteTransaction(C.CString(event["id"].(string)), C.CString(testAddressPassword)) + rawResponse := CompleteTransaction(C.CString(event["id"].(string)), C.CString(testConfig.Account1.Password)) if err := json.Unmarshal([]byte(C.GoString(rawResponse)), &completeTxResponse); err != nil { t.Errorf("cannot decode RecoverAccount reponse (%s): %v", C.GoString(rawResponse), err) @@ -694,8 +694,8 @@ func testCompleteTransaction(t *testing.T) bool { // this call blocks, up until Complete Transaction is called txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != nil { @@ -735,8 +735,8 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool { backend.TransactionQueue().Reset() // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return false } @@ -765,8 +765,8 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool { // this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called sendTx := func() { txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != nil { @@ -789,7 +789,7 @@ func testCompleteMultipleQueuedTransactions(t *testing.T) bool { updatedTxIdStrings, _ := json.Marshal(parsedIds) // complete - resultsString := CompleteTransactions(C.CString(string(updatedTxIdStrings)), C.CString(testAddressPassword)) + resultsString := CompleteTransactions(C.CString(string(updatedTxIdStrings)), C.CString(testConfig.Account1.Password)) resultsStruct := geth.CompleteTransactionsResult{} json.Unmarshal([]byte(C.GoString(resultsString)), &resultsStruct) results := resultsStruct.Results @@ -870,8 +870,8 @@ func testDiscardTransaction(t *testing.T) bool { backend.TransactionQueue().Reset() // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return false } @@ -912,7 +912,7 @@ func testDiscardTransaction(t *testing.T) bool { } // try completing discarded transaction - _, err = geth.CompleteTransaction(txId, testAddressPassword) + _, err = geth.CompleteTransaction(txId, testConfig.Account1.Password) if err.Error() != "transaction hash not found" { t.Error("expects tx not found, but call to CompleteTransaction succeeded") return @@ -950,8 +950,8 @@ func testDiscardTransaction(t *testing.T) bool { // this call blocks, and should return when DiscardQueuedTransaction() is called txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != status.ErrQueuedTxDiscarded { @@ -990,8 +990,8 @@ func testDiscardMultipleQueuedTransactions(t *testing.T) bool { backend.TransactionQueue().Reset() // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return false } @@ -1049,8 +1049,8 @@ func testDiscardMultipleQueuedTransactions(t *testing.T) bool { // this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called sendTx := func() { txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != status.ErrQueuedTxDiscarded { @@ -1084,7 +1084,7 @@ func testDiscardMultipleQueuedTransactions(t *testing.T) bool { } // try completing discarded transaction - completeResultsString := CompleteTransactions(C.CString(string(updatedTxIdStrings)), C.CString(testAddressPassword)) + completeResultsString := CompleteTransactions(C.CString(string(updatedTxIdStrings)), C.CString(testConfig.Account1.Password)) completeResultsStruct := geth.CompleteTransactionsResult{} json.Unmarshal([]byte(C.GoString(completeResultsString)), &completeResultsStruct) completeResults := completeResultsStruct.Results @@ -1178,7 +1178,7 @@ func testJailFunctionCall(t *testing.T) bool { InitJail(C.CString("")) // load Status JS and add test command to it - statusJS := geth.LoadFromFile(testStatusJsFile) + `; + statusJS := geth.LoadFromFile(filepath.Join(geth.RootDir, "geth/jail/testdata/status.js")) + `; _status_catalog.commands["testCommand"] = function (params) { return params.val * params.val; };` @@ -1209,7 +1209,7 @@ func testJailFunctionCall(t *testing.T) bool { func startTestNode(t *testing.T) <-chan struct{} { syncRequired := false - if _, err := os.Stat(filepath.Join(testDataDir, "testnet")); os.IsNotExist(err) { + if _, err := os.Stat(geth.TestDataDir); os.IsNotExist(err) { syncRequired = true } @@ -1234,8 +1234,8 @@ func startTestNode(t *testing.T) <-chan struct{} { // sync if syncRequired { - t.Logf("Sync is required, it will take %d seconds", testNodeSyncSeconds) - time.Sleep(testNodeSyncSeconds * time.Second) // LES syncs headers, so that we are up do date when it is done + t.Logf("Sync is required, it will take %d seconds", testConfig.Node.SyncSeconds) + time.Sleep(testConfig.Node.SyncSeconds * time.Second) // LES syncs headers, so that we are up do date when it is done } else { time.Sleep(5 * time.Second) } @@ -1246,7 +1246,7 @@ func startTestNode(t *testing.T) <-chan struct{} { }) go func() { - response := StartNode(C.CString(testDataDir)) + response := StartNode(C.CString(geth.TestDataDir)) err := geth.JSONError{} json.Unmarshal([]byte(C.GoString(response)), &err) diff --git a/data/test-data.json b/data/test-data.json new file mode 100644 index 000000000..f5dacfee8 --- /dev/null +++ b/data/test-data.json @@ -0,0 +1,15 @@ +{ + "Node": { + "SyncSeconds": 45, + "HTTPPort": 8645, + "WSPort": 8646 + }, + "Account1": { + "Address": "0xadaf150b905cf5e6a778e553e15a139b6618bbb7", + "Password": "asdfasdf" + }, + "Account2": { + "Address": "0xadd4d1d02e71c7360c53296968e59d57fd15e2ba", + "Password": "asdfasdf" + } +} \ No newline at end of file diff --git a/geth/accounts_test.go b/geth/accounts_test.go index cfca87293..3f91f0640 100644 --- a/geth/accounts_test.go +++ b/geth/accounts_test.go @@ -31,7 +31,7 @@ func TestAccountsList(t *testing.T) { } // create an account - address, _, _, err := geth.CreateAccount(newAccountPassword) + address, _, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return @@ -45,7 +45,7 @@ func TestAccountsList(t *testing.T) { } // select account (sub-accounts will be created for this key) - err = geth.SelectAccount(address, newAccountPassword) + err = geth.SelectAccount(address, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -63,7 +63,7 @@ func TestAccountsList(t *testing.T) { } // create sub-account 1 - subAccount1, subPubKey1, err := geth.CreateChildAccount("", newAccountPassword) + subAccount1, subPubKey1, err := geth.CreateChildAccount("", testConfig.Account1.Password) if err != nil { t.Errorf("cannot create sub-account: %v", err) return @@ -86,7 +86,7 @@ func TestAccountsList(t *testing.T) { } // create sub-account 2, index automatically progresses - subAccount2, subPubKey2, err := geth.CreateChildAccount("", newAccountPassword) + subAccount2, subPubKey2, err := geth.CreateChildAccount("", testConfig.Account1.Password) if err != nil { t.Errorf("cannot create sub-account: %v", err) } @@ -120,7 +120,7 @@ func TestAccountsList(t *testing.T) { } } -func TestCreateChildAccount(t *testing.T) { +func TestAccountsCreateChildAccount(t *testing.T) { err := geth.PrepareTestNode() if err != nil { t.Error(err) @@ -136,7 +136,7 @@ func TestCreateChildAccount(t *testing.T) { } // create an account - address, pubKey, mnemonic, err := geth.CreateAccount(newAccountPassword) + address, pubKey, mnemonic, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return @@ -150,7 +150,7 @@ func TestCreateChildAccount(t *testing.T) { } // obtain decrypted key, and make sure that extended key (which will be used as root for sub-accounts) is present - account, key, err := keyStore.AccountDecryptedKey(account, newAccountPassword) + account, key, err := keyStore.AccountDecryptedKey(account, testConfig.Account1.Password) if err != nil { t.Errorf("can not obtain decrypted account key: %v", err) return @@ -162,13 +162,13 @@ func TestCreateChildAccount(t *testing.T) { } // try creating sub-account, w/o selecting main account i.e. w/o login to main account - _, _, err = geth.CreateChildAccount("", newAccountPassword) + _, _, err = geth.CreateChildAccount("", testConfig.Account1.Password) if !reflect.DeepEqual(err, geth.ErrNoAccountSelected) { t.Errorf("expected error is not returned (tried to create sub-account w/o login): %v", err) return } - err = geth.SelectAccount(address, newAccountPassword) + err = geth.SelectAccount(address, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -182,14 +182,14 @@ func TestCreateChildAccount(t *testing.T) { } // create sub-account (from implicit parent) - subAccount1, subPubKey1, err := geth.CreateChildAccount("", newAccountPassword) + subAccount1, subPubKey1, err := geth.CreateChildAccount("", testConfig.Account1.Password) if err != nil { t.Errorf("cannot create sub-account: %v", err) return } // make sure that sub-account index automatically progresses - subAccount2, subPubKey2, err := geth.CreateChildAccount("", newAccountPassword) + subAccount2, subPubKey2, err := geth.CreateChildAccount("", testConfig.Account1.Password) if err != nil { t.Errorf("cannot create sub-account: %v", err) } @@ -199,7 +199,7 @@ func TestCreateChildAccount(t *testing.T) { } // create sub-account (from explicit parent) - subAccount3, subPubKey3, err := geth.CreateChildAccount(subAccount2, newAccountPassword) + subAccount3, subPubKey3, err := geth.CreateChildAccount(subAccount2, testConfig.Account1.Password) if err != nil { t.Errorf("cannot create sub-account: %v", err) } @@ -209,7 +209,7 @@ func TestCreateChildAccount(t *testing.T) { } } -func TestRecoverAccount(t *testing.T) { +func TestAccountsRecoverAccount(t *testing.T) { err := geth.PrepareTestNode() if err != nil { t.Error(err) @@ -219,7 +219,7 @@ func TestRecoverAccount(t *testing.T) { keyStore, _ := geth.NodeManagerInstance().AccountKeyStore() // create an account - address, pubKey, mnemonic, err := geth.CreateAccount(newAccountPassword) + address, pubKey, mnemonic, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return @@ -227,7 +227,7 @@ func TestRecoverAccount(t *testing.T) { t.Logf("Account created: {address: %s, key: %s, mnemonic:%s}", address, pubKey, mnemonic) // try recovering using password + mnemonic - addressCheck, pubKeyCheck, err := geth.RecoverAccount(newAccountPassword, mnemonic) + addressCheck, pubKeyCheck, err := geth.RecoverAccount(testConfig.Account1.Password, mnemonic) if err != nil { t.Errorf("recover account failed: %v", err) return @@ -242,18 +242,18 @@ func TestRecoverAccount(t *testing.T) { t.Errorf("can not get account from address: %v", err) } - account, key, err := keyStore.AccountDecryptedKey(account, newAccountPassword) + account, key, err := keyStore.AccountDecryptedKey(account, testConfig.Account1.Password) if err != nil { t.Errorf("can not obtain decrypted account key: %v", err) return } extChild2String := key.ExtendedKey.String() - if err := keyStore.Delete(account, newAccountPassword); err != nil { + if err := keyStore.Delete(account, testConfig.Account1.Password); err != nil { t.Errorf("cannot remove account: %v", err) } - addressCheck, pubKeyCheck, err = geth.RecoverAccount(newAccountPassword, mnemonic) + addressCheck, pubKeyCheck, err = geth.RecoverAccount(testConfig.Account1.Password, mnemonic) if err != nil { t.Errorf("recover account failed (for non-cached account): %v", err) return @@ -263,7 +263,7 @@ func TestRecoverAccount(t *testing.T) { } // make sure that extended key exists and is imported ok too - account, key, err = keyStore.AccountDecryptedKey(account, newAccountPassword) + account, key, err = keyStore.AccountDecryptedKey(account, testConfig.Account1.Password) if err != nil { t.Errorf("can not obtain decrypted account key: %v", err) return @@ -273,7 +273,7 @@ func TestRecoverAccount(t *testing.T) { } // make sure that calling import several times, just returns from cache (no error is expected) - addressCheck, pubKeyCheck, err = geth.RecoverAccount(newAccountPassword, mnemonic) + addressCheck, pubKeyCheck, err = geth.RecoverAccount(testConfig.Account1.Password, mnemonic) if err != nil { t.Errorf("recover account failed (for non-cached account): %v", err) return @@ -292,7 +292,7 @@ func TestRecoverAccount(t *testing.T) { if whisperService.HasIdentity(crypto.ToECDSAPub(common.FromHex(pubKeyCheck))) { t.Error("identity already present in whisper") } - err = geth.SelectAccount(addressCheck, newAccountPassword) + err = geth.SelectAccount(addressCheck, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -317,14 +317,14 @@ func TestAccountSelect(t *testing.T) { } // create an account - address1, pubKey1, _, err := geth.CreateAccount(newAccountPassword) + address1, pubKey1, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return } t.Logf("Account created: {address: %s, key: %s}", address1, pubKey1) - address2, pubKey2, _, err := geth.CreateAccount(newAccountPassword) + address2, pubKey2, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Error("Test failed: could not create account") return @@ -342,7 +342,7 @@ func TestAccountSelect(t *testing.T) { t.Error("select account is expected to throw error: wrong password used") return } - err = geth.SelectAccount(address1, newAccountPassword) + err = geth.SelectAccount(address1, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -355,7 +355,7 @@ func TestAccountSelect(t *testing.T) { if whisperService.HasIdentity(crypto.ToECDSAPub(common.FromHex(pubKey2))) { t.Error("identity already present in whisper") } - err = geth.SelectAccount(address2, newAccountPassword) + err = geth.SelectAccount(address2, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -368,7 +368,7 @@ func TestAccountSelect(t *testing.T) { } } -func TestAccountLogout(t *testing.T) { +func TestAccountsLogout(t *testing.T) { err := geth.PrepareTestNode() if err != nil { @@ -382,7 +382,7 @@ func TestAccountLogout(t *testing.T) { } // create an account - address, pubKey, _, err := geth.CreateAccount(newAccountPassword) + address, pubKey, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return @@ -394,7 +394,7 @@ func TestAccountLogout(t *testing.T) { } // select/login - err = geth.SelectAccount(address, newAccountPassword) + err = geth.SelectAccount(address, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -414,7 +414,7 @@ func TestAccountLogout(t *testing.T) { } } -func TestSelectedAccountOnNodeRestart(t *testing.T) { +func TestAccountsSelectedAccountOnNodeRestart(t *testing.T) { err := geth.PrepareTestNode() if err != nil { t.Error(err) @@ -428,13 +428,13 @@ func TestSelectedAccountOnNodeRestart(t *testing.T) { } // create test accounts - address1, pubKey1, _, err := geth.CreateAccount(newAccountPassword) + address1, pubKey1, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return } t.Logf("account1 created: {address: %s, key: %s}", address1, pubKey1) - address2, pubKey2, _, err := geth.CreateAccount(newAccountPassword) + address2, pubKey2, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return @@ -458,7 +458,7 @@ func TestSelectedAccountOnNodeRestart(t *testing.T) { t.Error("select account is expected to throw error: wrong password used") return } - err = geth.SelectAccount(address1, newAccountPassword) + err = geth.SelectAccount(address1, testConfig.Account1.Password) if err != nil { t.Errorf("could not select account: %v", err) return @@ -471,7 +471,7 @@ func TestSelectedAccountOnNodeRestart(t *testing.T) { if whisperService.HasIdentity(crypto.ToECDSAPub(common.FromHex(pubKey2))) { t.Error("identity already present in whisper") } - err = geth.SelectAccount(address2, newAccountPassword) + err = geth.SelectAccount(address2, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -528,7 +528,7 @@ func TestSelectedAccountOnNodeRestart(t *testing.T) { } } -func TestNodeRestartWithNoSelectedAccount(t *testing.T) { +func TestAccountsNodeRestartWithNoSelectedAccount(t *testing.T) { err := geth.PrepareTestNode() if err != nil { t.Error(err) @@ -544,7 +544,7 @@ func TestNodeRestartWithNoSelectedAccount(t *testing.T) { } // create test accounts - address1, pubKey1, _, err := geth.CreateAccount(newAccountPassword) + address1, pubKey1, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return diff --git a/geth/jail/jail_test.go b/geth/jail/jail_test.go index 03908474b..9aa1ae6a0 100644 --- a/geth/jail/jail_test.go +++ b/geth/jail/jail_test.go @@ -190,7 +190,7 @@ func TestJailRPCSend(t *testing.T) { // internally (since we replaced `web3.send` with `jail.Send`) // all requests to web3 are forwarded to `jail.Send` _, err = vm.Run(` - var balance = web3.eth.getBalance("` + testConfig.Account.Address + `"); + var balance = web3.eth.getBalance("` + testConfig.Account1.Address + `"); var sendResult = web3.fromWei(balance, "ether") `) if err != nil { @@ -215,7 +215,7 @@ func TestJailRPCSend(t *testing.T) { return } - t.Logf("Balance of %.2f ETH found on '%s' account", balance, testConfig.Account.Address) + t.Logf("Balance of %.2f ETH found on '%s' account", balance, testConfig.Account1.Address) } func TestJailSendQueuedTransaction(t *testing.T) { @@ -226,13 +226,13 @@ func TestJailSendQueuedTransaction(t *testing.T) { } // log into account from which transactions will be sent - if err := geth.SelectAccount(testConfig.Account.Address, testConfig.Account.Password); err != nil { - t.Errorf("cannot select account: %v", testConfig.Account.Address) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } txParams := `{ - "from": "` + testConfig.Account.Address + `", + "from": "` + testConfig.Account1.Address + `", "to": "0xf82da7547534045b4e00442bc89e16186cf8c272", "value": "0.000001" }` @@ -270,7 +270,7 @@ func TestJailSendQueuedTransaction(t *testing.T) { t.Logf("Transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string)) var txHash common.Hash - if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account.Password); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) } else { t.Logf("Transaction complete: https://testnet.etherscan.io/tx/%s", txHash.Hex()) @@ -308,7 +308,7 @@ func TestJailSendQueuedTransaction(t *testing.T) { }, { `["commands", "getBalance"]`, - `{"address": "` + testConfig.Account.Address + `"}`, + `{"address": "` + testConfig.Account1.Address + `"}`, `{"result": {"balance":42}}`, }, }, @@ -326,7 +326,7 @@ func TestJailSendQueuedTransaction(t *testing.T) { }, { `["commands", "getBalance"]`, - `{"address": "` + testConfig.Account.Address + `"}`, + `{"address": "` + testConfig.Account1.Address + `"}`, `{"result": {"context":{},"result":{"balance":42}}}`, // note emtpy (but present) context! }, }, @@ -344,7 +344,7 @@ func TestJailSendQueuedTransaction(t *testing.T) { }, { `["commands", "getBalance"]`, - `{"address": "` + testConfig.Account.Address + `"}`, + `{"address": "` + testConfig.Account1.Address + `"}`, `{"result": {"balance":42}}`, // note emtpy context! }, }, @@ -362,7 +362,7 @@ func TestJailSendQueuedTransaction(t *testing.T) { }, { `["commands", "getBalance"]`, - `{"address": "` + testConfig.Account.Address + `"}`, + `{"address": "` + testConfig.Account1.Address + `"}`, `{"result": {"context":{"message_id":"42"},"result":{"balance":42}}}`, // message id in context, but default one is used! }, }, @@ -613,12 +613,12 @@ func TestContractDeployment(t *testing.T) { t.Logf("Transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string)) - if err := geth.SelectAccount(testConfig.Account.Address, testConfig.Account.Password); err != nil { - t.Errorf("cannot select account: %v", testConfig.Account.Address) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } - if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account.Password); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) return } else { @@ -634,7 +634,7 @@ func TestContractDeployment(t *testing.T) { var testContract = web3.eth.contract([{"constant":true,"inputs":[{"name":"a","type":"int256"}],"name":"double","outputs":[{"name":"","type":"int256"}],"payable":false,"type":"function"}]); var test = testContract.new( { - from: '` + testConfig.Account.Address + `', + from: '` + testConfig.Account1.Address + `', data: '0x6060604052341561000c57fe5b5b60a58061001b6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680636ffa1caa14603a575bfe5b3415604157fe5b60556004808035906020019091905050606b565b6040518082815260200191505060405180910390f35b60008160020290505b9190505600a165627a7a72305820ccdadd737e4ac7039963b54cee5e5afb25fa859a275252bdcf06f653155228210029', gas: '` + strconv.Itoa(geth.DefaultGas) + `' }, function (e, contract){ @@ -703,12 +703,12 @@ func TestGasEstimation(t *testing.T) { t.Logf("Transaction queued (will be completed immediately): {id: %s}\n", event["id"].(string)) - if err := geth.SelectAccount(testConfig.Account.Address, testConfig.Account.Password); err != nil { - t.Errorf("cannot select account: %v", testConfig.Account.Address) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } - if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account.Password); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) return } else { @@ -724,7 +724,7 @@ func TestGasEstimation(t *testing.T) { var testContract = web3.eth.contract([{"constant":true,"inputs":[{"name":"a","type":"int256"}],"name":"double","outputs":[{"name":"","type":"int256"}],"payable":false,"type":"function"}]); var test = testContract.new( { - from: '` + testConfig.Account.Address + `', + from: '` + testConfig.Account1.Address + `', data: '0x6060604052341561000c57fe5b5b60a58061001b6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680636ffa1caa14603a575bfe5b3415604157fe5b60556004808035906020019091905050606b565b6040518082815260200191505060405180910390f35b60008160020290505b9190505600a165627a7a72305820ccdadd737e4ac7039963b54cee5e5afb25fa859a275252bdcf06f653155228210029', }, function (e, contract){ if (!e) { diff --git a/geth/node_manager.go b/geth/node_manager.go index 7adfbab92..e3865636f 100644 --- a/geth/node_manager.go +++ b/geth/node_manager.go @@ -46,7 +46,6 @@ type NodeServiceStack struct { } var ( - ErrDataDirPreprocessingFailed = errors.New("failed to pre-process data directory") ErrInvalidGethNode = errors.New("no running geth node detected") ErrInvalidAccountManager = errors.New("could not retrieve account manager") ErrInvalidWhisperService = errors.New("whisper service is unavailable") diff --git a/geth/node_manager_test.go b/geth/node_manager_test.go index d8ca92bf2..be3d71d39 100644 --- a/geth/node_manager_test.go +++ b/geth/node_manager_test.go @@ -1,67 +1,28 @@ package geth_test import ( - "encoding/json" - "fmt" "os" - "path/filepath" "testing" "time" "github.com/status-im/status-go/geth" ) -const ( - testAddress = "0xadaf150b905cf5e6a778e553e15a139b6618bbb7" - testAddressPassword = "asdfasdf" - newAccountPassword = "badpassword" - testAddress1 = "0xadd4d1d02e71c7360c53296968e59d57fd15e2ba" - - whisperMessage1 = "test message 1 (K1 -> K1)" - whisperMessage2 = "test message 2 (K1 -> '')" - whisperMessage3 = "test message 3 ('' -> '')" - whisperMessage4 = "test message 4 ('' -> K1)" - whisperMessage5 = "test message 5 (K2 -> K1)" -) +var testConfig *geth.TestConfig func TestMain(m *testing.M) { - syncRequired := false - if _, err := os.Stat(filepath.Join(geth.TestDataDir, "testnet")); os.IsNotExist(err) { - syncRequired = true - } - // make sure you panic if node start signal is not received - signalRecieved := make(chan struct{}, 1) - abortPanic := make(chan struct{}, 1) - if syncRequired { - geth.PanicAfter(geth.TestNodeSyncSeconds*time.Second, abortPanic, "TestNodeSetup") - } else { - geth.PanicAfter(10*time.Second, abortPanic, "TestNodeSetup") - } - - geth.SetDefaultNodeNotificationHandler(func(jsonEvent string) { - var envelope geth.SignalEnvelope - if err := json.Unmarshal([]byte(jsonEvent), &envelope); err != nil { - panic(fmt.Errorf("cannot unmarshal event's JSON: %s", jsonEvent)) - } - if envelope.Type == geth.EventNodeCrashed { - geth.TriggerDefaultNodeNotificationHandler(jsonEvent) - return - } - - if jsonEvent == `{"type":"node.started","event":{}}` { - signalRecieved <- struct{}{} - } - }) - - err := geth.PrepareTestNode() + // load shared test configuration + var err error + testConfig, err = geth.LoadTestConfig() if err != nil { panic(err) } - <-signalRecieved // block and wait for either panic or successful signal - abortPanic <- struct{}{} + // run tests + retCode := m.Run() - os.Exit(m.Run()) + //time.Sleep(25 * time.Second) // to give some time to propagate txs to the rest of the network + os.Exit(retCode) } func TestResetChainData(t *testing.T) { @@ -77,7 +38,7 @@ func TestResetChainData(t *testing.T) { } // allow some time to re-sync - time.Sleep(geth.TestNodeSyncSeconds * time.Second) + time.Sleep(testConfig.Node.SyncSeconds * time.Second) // now make sure that everything is intact TestQueuedTransactions(t) diff --git a/geth/txqueue_test.go b/geth/txqueue_test.go index 26d5753bd..a58e2437c 100644 --- a/geth/txqueue_test.go +++ b/geth/txqueue_test.go @@ -30,7 +30,7 @@ func TestQueuedContracts(t *testing.T) { backend := lightEthereum.StatusBackend // create an account - sampleAddress, _, _, err := geth.CreateAccount(newAccountPassword) + sampleAddress, _, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return @@ -40,7 +40,7 @@ func TestQueuedContracts(t *testing.T) { // make sure you panic if transaction complete doesn't return completeQueuedTransaction := make(chan struct{}, 1) - geth.PanicAfter(60*time.Second, completeQueuedTransaction, "TestQueuedContracts") + geth.PanicAfter(5*time.Second, completeQueuedTransaction, "TestQueuedContracts") // replace transaction notification handler var txHash = common.Hash{} @@ -52,37 +52,36 @@ func TestQueuedContracts(t *testing.T) { } if envelope.Type == geth.EventTransactionQueued { event := envelope.Event.(map[string]interface{}) - t.Logf("transaction queued (will be completed in 5 secs): {id: %s}\n", event["id"].(string)) - time.Sleep(5 * time.Second) + t.Logf("transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string)) // the first call will fail (we are not logged in, but trying to complete tx) - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != status.ErrInvalidCompleteTxSender { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != status.ErrInvalidCompleteTxSender { t.Errorf("expected error on queued transation[%v] not thrown: expected %v, got %v", event["id"], status.ErrInvalidCompleteTxSender, err) return } // the second call will also fail (we are logged in as different user) - if err := geth.SelectAccount(sampleAddress, newAccountPassword); err != nil { + if err := geth.SelectAccount(sampleAddress, testConfig.Account1.Password); err != nil { t.Errorf("cannot select account: %v", sampleAddress) return } - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != status.ErrInvalidCompleteTxSender { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != status.ErrInvalidCompleteTxSender { t.Errorf("expected error on queued transation[%v] not thrown: expected %v, got %v", event["id"], status.ErrInvalidCompleteTxSender, err) return } // the third call will work as expected (as we are logged in with correct credentials) - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) return } t.Logf("contract transaction complete: https://testnet.etherscan.io/tx/%s", txHash.Hex()) - completeQueuedTransaction <- struct{}{} // so that timeout is aborted + close(completeQueuedTransaction) } }) @@ -93,7 +92,7 @@ func TestQueuedContracts(t *testing.T) { return } txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), + From: geth.FromAddress(testConfig.Account1.Address), To: nil, // marker, contract creation is expected //Value: (*hexutil.Big)(new(big.Int).Mul(big.NewInt(1), common.Ether)), Gas: (*hexutil.Big)(big.NewInt(geth.DefaultGas)), @@ -108,7 +107,7 @@ func TestQueuedContracts(t *testing.T) { return } - time.Sleep(10 * time.Second) + <-completeQueuedTransaction if reflect.DeepEqual(txHashCheck, common.Hash{}) { t.Error("Test failed: transaction was never queued or completed") @@ -137,7 +136,7 @@ func TestQueuedTransactions(t *testing.T) { backend := lightEthereum.StatusBackend // create an account - sampleAddress, _, _, err := geth.CreateAccount(newAccountPassword) + sampleAddress, _, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { t.Errorf("could not create account: %v", err) return @@ -147,7 +146,7 @@ func TestQueuedTransactions(t *testing.T) { // make sure you panic if transaction complete doesn't return completeQueuedTransaction := make(chan struct{}, 1) - geth.PanicAfter(60*time.Second, completeQueuedTransaction, "TestQueuedTransactions") + geth.PanicAfter(5*time.Second, completeQueuedTransaction, "TestQueuedTransactions") // replace transaction notification handler var txHash = common.Hash{} @@ -159,44 +158,43 @@ func TestQueuedTransactions(t *testing.T) { } if envelope.Type == geth.EventTransactionQueued { event := envelope.Event.(map[string]interface{}) - t.Logf("transaction queued (will be completed in 5 secs): {id: %s}\n", event["id"].(string)) - time.Sleep(5 * time.Second) + t.Logf("transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string)) // the first call will fail (we are not logged in, but trying to complete tx) - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != status.ErrInvalidCompleteTxSender { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != status.ErrInvalidCompleteTxSender { t.Errorf("expected error on queued transation[%v] not thrown: expected %v, got %v", event["id"], status.ErrInvalidCompleteTxSender, err) return } // the second call will also fail (we are logged in as different user) - if err := geth.SelectAccount(sampleAddress, newAccountPassword); err != nil { + if err := geth.SelectAccount(sampleAddress, testConfig.Account1.Password); err != nil { t.Errorf("cannot select account: %v", sampleAddress) return } - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != status.ErrInvalidCompleteTxSender { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != status.ErrInvalidCompleteTxSender { t.Errorf("expected error on queued transation[%v] not thrown: expected %v, got %v", event["id"], status.ErrInvalidCompleteTxSender, err) return } // the third call will work as expected (as we are logged in with correct credentials) - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) return } t.Logf("transaction complete: https://testnet.etherscan.io/tx/%s", txHash.Hex()) - completeQueuedTransaction <- struct{}{} // so that timeout is aborted + close(completeQueuedTransaction) } }) // this call blocks, up until Complete Transaction is called txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != nil { @@ -208,7 +206,7 @@ func TestQueuedTransactions(t *testing.T) { return } - time.Sleep(10 * time.Second) + <-completeQueuedTransaction if reflect.DeepEqual(txHashCheck, common.Hash{}) { t.Error("Test failed: transaction was never queued or completed") @@ -237,8 +235,8 @@ func TestDoubleCompleteQueuedTransactions(t *testing.T) { backend := lightEthereum.StatusBackend // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } @@ -263,21 +261,18 @@ func TestDoubleCompleteQueuedTransactions(t *testing.T) { // try with wrong password // make sure that tx is NOT removed from the queue (by re-trying with the correct password) - if _, err = geth.CompleteTransaction(txId, testAddressPassword+"wrong"); err != keystore.ErrDecrypt { + if _, err = geth.CompleteTransaction(txId, testConfig.Account1.Password+"wrong"); err != keystore.ErrDecrypt { t.Errorf("expects wrong password error, but call succeeded (or got another error: %v)", err) return } - time.Sleep(1 * time.Second) // make sure that tx complete signal propagates if txCount := backend.TransactionQueue().Count(); txCount != 1 { t.Errorf("txqueue cannot be empty, as tx has failed: expected = 1, got = %d", txCount) return } // now try to complete transaction, but with the correct password - t.Log("allow 5 seconds before sedning the second CompleteTransaction") - time.Sleep(5 * time.Second) - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) return } @@ -315,8 +310,8 @@ func TestDoubleCompleteQueuedTransactions(t *testing.T) { // this call blocks, and should return on *second* attempt to CompleteTransaction (w/ the correct password) txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != nil { @@ -343,9 +338,6 @@ func TestDoubleCompleteQueuedTransactions(t *testing.T) { t.Error("expected tx failure signal is not received") return } - - t.Log("sleep extra time, to allow sync") - time.Sleep(5 * time.Second) } func TestDiscardQueuedTransactions(t *testing.T) { @@ -367,8 +359,8 @@ func TestDiscardQueuedTransactions(t *testing.T) { backend.TransactionQueue().Reset() // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } @@ -403,7 +395,7 @@ func TestDiscardQueuedTransactions(t *testing.T) { } // try completing discarded transaction - _, err = geth.CompleteTransaction(txId, testAddressPassword) + _, err = geth.CompleteTransaction(txId, testConfig.Account1.Password) if err.Error() != "transaction hash not found" { t.Error("expects tx not found, but call to CompleteTransaction succeeded") return @@ -441,8 +433,8 @@ func TestDiscardQueuedTransactions(t *testing.T) { // this call blocks, and should return when DiscardQueuedTransaction() is called txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != status.ErrQueuedTxDiscarded { @@ -464,9 +456,6 @@ func TestDiscardQueuedTransactions(t *testing.T) { t.Error("expected tx failure signal is not received") return } - - t.Log("sleep extra time, to allow sync") - time.Sleep(5 * time.Second) } func TestCompleteMultipleQueuedTransactions(t *testing.T) { @@ -488,8 +477,8 @@ func TestCompleteMultipleQueuedTransactions(t *testing.T) { backend.TransactionQueue().Reset() // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } @@ -518,8 +507,8 @@ func TestCompleteMultipleQueuedTransactions(t *testing.T) { // this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called sendTx := func() { txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != nil { @@ -542,7 +531,7 @@ func TestCompleteMultipleQueuedTransactions(t *testing.T) { updatedTxIdStrings, _ := json.Marshal(parsedIds) // complete - results := geth.CompleteTransactions(string(updatedTxIdStrings), testAddressPassword) + results := geth.CompleteTransactions(string(updatedTxIdStrings), testConfig.Account1.Password) if len(results) != (testTxCount+1) || results["invalid-tx-id"].Error.Error() != "transaction hash not found" { t.Errorf("cannot complete txs: %v", results) return @@ -619,8 +608,8 @@ func TestDiscardMultipleQueuedTransactions(t *testing.T) { backend.TransactionQueue().Reset() // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } @@ -678,8 +667,8 @@ func TestDiscardMultipleQueuedTransactions(t *testing.T) { // this call blocks, and should return when DiscardQueuedTransaction() for a given tx id is called sendTx := func() { txHashCheck, err := backend.SendTransaction(nil, status.SendTxArgs{ - From: geth.FromAddress(testAddress), - To: geth.ToAddress(testAddress1), + From: geth.FromAddress(testConfig.Account1.Address), + To: geth.ToAddress(testConfig.Account2.Address), Value: (*hexutil.Big)(big.NewInt(1000000000000)), }) if err != status.ErrQueuedTxDiscarded { @@ -709,7 +698,7 @@ func TestDiscardMultipleQueuedTransactions(t *testing.T) { } // try completing discarded transaction - completeResults := geth.CompleteTransactions(string(updatedTxIdStrings), testAddressPassword) + completeResults := geth.CompleteTransactions(string(updatedTxIdStrings), testConfig.Account1.Password) if len(completeResults) != (testTxCount + 1) { t.Error("unexpected number of errors (call to CompleteTransaction should not succeed)") } @@ -769,8 +758,8 @@ func TestNonExistentQueuedTransactions(t *testing.T) { } // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } @@ -788,11 +777,10 @@ func TestNonExistentQueuedTransactions(t *testing.T) { } if envelope.Type == geth.EventTransactionQueued { event := envelope.Event.(map[string]interface{}) - t.Logf("Transaction queued (will be completed in 5 secs): {id: %s}\n", event["id"].(string)) - time.Sleep(5 * time.Second) + t.Logf("Transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string)) // next call is the very same one, but with the correct password - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) return } @@ -803,7 +791,7 @@ func TestNonExistentQueuedTransactions(t *testing.T) { }) // try completing non-existing transaction - if _, err = geth.CompleteTransaction("some-bad-transaction-id", testAddressPassword); err == nil { + if _, err = geth.CompleteTransaction("some-bad-transaction-id", testConfig.Account1.Password); err == nil { t.Error("error expected and not recieved") return } @@ -829,8 +817,8 @@ func TestEvictionOfQueuedTransactions(t *testing.T) { backend := lightEthereum.StatusBackend // log into account from which transactions will be sent - if err := geth.SelectAccount(testAddress, testAddressPassword); err != nil { - t.Errorf("cannot select account: %v", testAddress) + if err := geth.SelectAccount(testConfig.Account1.Address, testConfig.Account1.Password); err != nil { + t.Errorf("cannot select account: %v", testConfig.Account1.Address) return } @@ -848,11 +836,10 @@ func TestEvictionOfQueuedTransactions(t *testing.T) { } if envelope.Type == geth.EventTransactionQueued { event := envelope.Event.(map[string]interface{}) - t.Logf("Transaction queued (will be completed in 5 secs): {id: %s}\n", event["id"].(string)) - time.Sleep(5 * time.Second) + t.Logf("Transaction queued (will be completed shortly): {id: %s}\n", event["id"].(string)) // next call is the very same one, but with the correct password - if txHash, err = geth.CompleteTransaction(event["id"].(string), testAddressPassword); err != nil { + if txHash, err = geth.CompleteTransaction(event["id"].(string), testConfig.Account1.Password); err != nil { t.Errorf("cannot complete queued transation[%v]: %v", event["id"], err) return } diff --git a/geth/utils.go b/geth/utils.go index 7589b3a49..2854d64d6 100644 --- a/geth/utils.go +++ b/geth/utils.go @@ -12,7 +12,7 @@ import ( "io" "os" "path/filepath" - "runtime" + "strings" "sync" "time" @@ -22,20 +22,30 @@ import ( "github.com/ethereum/go-ethereum/logger/glog" ) -const ( - TestNodeSyncSeconds = 60 - TestNodeHTTPPort = 8645 - TestNodeWSPort = 8646 -) - var ( muPrepareTestNode sync.Mutex - _, basePath, _, _ = runtime.Caller(0) - RootDir = filepath.Join(filepath.Dir(basePath), "..") - DataDir = filepath.Join(RootDir, "data") - TestDataDir = filepath.Join(RootDir, ".ethereumtest") + RootDir string + DataDir string + TestDataDir string ) +func init() { + pwd, err := os.Getwd() + if err != nil { + panic(err) + } + + // setup root directory + RootDir = filepath.Dir(pwd) + if strings.HasSuffix(RootDir, "geth") || strings.HasSuffix(RootDir, "cmd") { // we need to hop one more level + RootDir = filepath.Join(RootDir, "..") + } + + // setup auxiliary directories + DataDir = filepath.Join(RootDir, "data") + TestDataDir = filepath.Join(RootDir, ".ethereumtest") +} + type NodeNotificationHandler func(jsonEvent string) var notificationHandler NodeNotificationHandler = TriggerDefaultNodeNotificationHandler @@ -69,11 +79,15 @@ func TriggerTestSignal() { // TestConfig contains shared (among different test packages) parameters type TestConfig struct { Node struct { - SyncSeconds int + SyncSeconds time.Duration HTTPPort int WSPort int } - Account struct { + Account1 struct { + Address string + Password string + } + Account2 struct { Address string Password string } @@ -136,6 +150,11 @@ func PrepareTestNode() (err error) { defer HaltOnPanic() + testConfig, err := LoadTestConfig() + if err != nil { + return err + } + syncRequired := false if _, err := os.Stat(filepath.Join(TestDataDir, "testnet")); os.IsNotExist(err) { syncRequired = true @@ -161,9 +180,9 @@ func PrepareTestNode() (err error) { err = CreateAndRunNode(&NodeConfig{ DataDir: TestDataDir, IPCEnabled: false, - HTTPPort: TestNodeHTTPPort, // to avoid conflicts with running app, using different port in tests + HTTPPort: testConfig.Node.HTTPPort, // to avoid conflicts with running app, using different port in tests WSEnabled: false, - WSPort: TestNodeWSPort, // ditto + WSPort: testConfig.Node.WSPort, // ditto TLSEnabled: false, }) if err != nil { @@ -185,8 +204,8 @@ func PrepareTestNode() (err error) { } if syncRequired { - glog.V(logger.Warn).Infof("Sync is required, it will take %d seconds", TestNodeSyncSeconds) - time.Sleep(TestNodeSyncSeconds * time.Second) // LES syncs headers, so that we are up do date when it is done + glog.V(logger.Warn).Infof("Sync is required, it will take %d seconds", testConfig.Node.SyncSeconds) + time.Sleep(testConfig.Node.SyncSeconds * time.Second) // LES syncs headers, so that we are up do date when it is done } else { time.Sleep(5 * time.Second) } diff --git a/geth/whisper_test.go b/geth/whisper_test.go index 003590bb5..af5df4dcf 100644 --- a/geth/whisper_test.go +++ b/geth/whisper_test.go @@ -11,6 +11,14 @@ import ( "github.com/status-im/status-go/geth" ) +const ( + whisperMessage1 = "test message 1 (K1 -> K1)" + whisperMessage2 = "test message 2 (K1 -> '')" + whisperMessage3 = "test message 3 ('' -> '')" + whisperMessage4 = "test message 4 ('' -> K1)" + whisperMessage5 = "test message 5 (K2 -> K1)" +) + func TestWhisperMessaging(t *testing.T) { err := geth.PrepareTestNode() if err != nil { @@ -35,7 +43,7 @@ func TestWhisperMessaging(t *testing.T) { } // create an accounts - address1, pubKey1, _, err := geth.CreateAccount(newAccountPassword) + address1, pubKey1, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { fmt.Println(err.Error()) t.Error("Test failed: could not create account") @@ -43,7 +51,7 @@ func TestWhisperMessaging(t *testing.T) { } t.Logf("Account created: {address: %s, key: %s}", address1, pubKey1) - address2, pubKey2, _, err := geth.CreateAccount(newAccountPassword) + address2, pubKey2, _, err := geth.CreateAccount(testConfig.Account1.Password) if err != nil { fmt.Println(err.Error()) t.Error("Test failed: could not create account") @@ -72,7 +80,7 @@ func TestWhisperMessaging(t *testing.T) { if whisperService.HasIdentity(crypto.ToECDSAPub(common.FromHex(pubKey1))) { t.Error("identity already present in whisper") } - err = geth.SelectAccount(address1, newAccountPassword) + err = geth.SelectAccount(address1, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return @@ -86,7 +94,7 @@ func TestWhisperMessaging(t *testing.T) { } // double selecting (shouldn't be a problem) - err = geth.SelectAccount(address1, newAccountPassword) + err = geth.SelectAccount(address1, testConfig.Account1.Password) if err != nil { t.Errorf("Test failed: could not select account: %v", err) return