github.com/blockchain-foundry/go-ethereum@v1.5.9/mobile/android_test.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package geth 18 19 import ( 20 "io/ioutil" 21 "os" 22 "os/exec" 23 "path/filepath" 24 "runtime" 25 "testing" 26 "time" 27 28 "github.com/ethereum/go-ethereum/internal/build" 29 ) 30 31 // androidTestClass is a Java class to do some lightweight tests against the Android 32 // bindings. The goal is not to test each individual functionality, rather just to 33 // catch breaking API and/or implementation changes. 34 const androidTestClass = ` 35 package go; 36 37 import android.test.InstrumentationTestCase; 38 import android.test.MoreAsserts; 39 40 import org.ethereum.geth.*; 41 42 public class AndroidTest extends InstrumentationTestCase { 43 public AndroidTest() {} 44 45 public void testAccountManagement() { 46 // Create an encrypted keystore with light crypto parameters. 47 KeyStore ks = new KeyStore(getInstrumentation().getContext().getFilesDir() + "/keystore", Geth.LightScryptN, Geth.LightScryptP); 48 49 try { 50 // Create a new account with the specified encryption passphrase. 51 Account newAcc = ks.newAccount("Creation password"); 52 53 // Export the newly created account with a different passphrase. The returned 54 // data from this method invocation is a JSON encoded, encrypted key-file. 55 byte[] jsonAcc = ks.exportKey(newAcc, "Creation password", "Export password"); 56 57 // Update the passphrase on the account created above inside the local keystore. 58 ks.updateAccount(newAcc, "Creation password", "Update password"); 59 60 // Delete the account updated above from the local keystore. 61 ks.deleteAccount(newAcc, "Update password"); 62 63 // Import back the account we've exported (and then deleted) above with yet 64 // again a fresh passphrase. 65 Account impAcc = ks.importKey(jsonAcc, "Export password", "Import password"); 66 67 // Create a new account to sign transactions with 68 Account signer = ks.newAccount("Signer password"); 69 70 Transaction tx = new Transaction( 71 1, new Address("0x0000000000000000000000000000000000000000"), 72 new BigInt(0), new BigInt(0), new BigInt(1), null); // Random empty transaction 73 BigInt chain = new BigInt(1); // Chain identifier of the main net 74 75 // Sign a transaction with a single authorization 76 Transaction signed = ks.signTxPassphrase(signer, "Signer password", tx, chain); 77 78 // Sign a transaction with multiple manually cancelled authorizations 79 ks.unlock(signer, "Signer password"); 80 signed = ks.signTx(signer, tx, chain); 81 ks.lock(signer.getAddress()); 82 83 // Sign a transaction with multiple automatically cancelled authorizations 84 ks.timedUnlock(signer, "Signer password", 1000000000); 85 signed = ks.signTx(signer, tx, chain); 86 } catch (Exception e) { 87 fail(e.toString()); 88 } 89 } 90 91 public void testInprocNode() { 92 Context ctx = new Context(); 93 94 try { 95 // Start up a new inprocess node 96 Node node = new Node(getInstrumentation().getContext().getFilesDir() + "/.ethereum", new NodeConfig()); 97 node.start(); 98 99 // Retrieve some data via function calls (we don't really care about the results) 100 NodeInfo info = node.getNodeInfo(); 101 info.getName(); 102 info.getListenerAddress(); 103 info.getProtocols(); 104 105 // Retrieve some data via the APIs (we don't really care about the results) 106 EthereumClient ec = node.getEthereumClient(); 107 ec.getBlockByNumber(ctx, -1).getNumber(); 108 109 NewHeadHandler handler = new NewHeadHandler() { 110 @Override public void onError(String error) {} 111 @Override public void onNewHead(final Header header) {} 112 }; 113 ec.subscribeNewHead(ctx, handler, 16); 114 } catch (Exception e) { 115 fail(e.toString()); 116 } 117 } 118 } 119 ` 120 121 // TestAndroid runs the Android java test class specified above. 122 // 123 // This requires the gradle command in PATH and the Android SDK whose path is available 124 // through ANDROID_HOME environment variable. To successfully run the tests, an Android 125 // device must also be available with debugging enabled. 126 // 127 // This method has been adapted from golang.org/x/mobile/bind/java/seq_test.go/runTest 128 func TestAndroid(t *testing.T) { 129 // Skip tests on Windows altogether 130 if runtime.GOOS == "windows" { 131 t.Skip("cannot test Android bindings on Windows, skipping") 132 } 133 // Make sure all the Android tools are installed 134 if _, err := exec.Command("which", "gradle").CombinedOutput(); err != nil { 135 t.Skip("command gradle not found, skipping") 136 } 137 if sdk := os.Getenv("ANDROID_HOME"); sdk == "" { 138 t.Skip("ANDROID_HOME environment var not set, skipping") 139 } 140 if _, err := exec.Command("which", "gomobile").CombinedOutput(); err != nil { 141 t.Log("gomobile missing, installing it...") 142 if _, err := exec.Command("go", "install", "golang.org/x/mobile/cmd/gomobile").CombinedOutput(); err != nil { 143 t.Fatalf("install failed: %v", err) 144 } 145 t.Log("initializing gomobile...") 146 start := time.Now() 147 if _, err := exec.Command("gomobile", "init").CombinedOutput(); err != nil { 148 t.Fatalf("initialization failed: %v", err) 149 } 150 t.Logf("initialization took %v", time.Since(start)) 151 } 152 // Create and switch to a temporary workspace 153 workspace, err := ioutil.TempDir("", "geth-android-") 154 if err != nil { 155 t.Fatalf("failed to create temporary workspace: %v", err) 156 } 157 defer os.RemoveAll(workspace) 158 159 pwd, err := os.Getwd() 160 if err != nil { 161 t.Fatalf("failed to get current working directory: %v", err) 162 } 163 if err := os.Chdir(workspace); err != nil { 164 t.Fatalf("failed to switch to temporary workspace: %v", err) 165 } 166 defer os.Chdir(pwd) 167 168 // Create the skeleton of the Android project 169 for _, dir := range []string{"src/main", "src/androidTest/java/org/ethereum/gethtest", "libs"} { 170 err = os.MkdirAll(dir, os.ModePerm) 171 if err != nil { 172 t.Fatal(err) 173 } 174 } 175 // Generate the mobile bindings for Geth and add the tester class 176 gobind := exec.Command("gomobile", "bind", "-javapkg", "org.ethereum", "github.com/ethereum/go-ethereum/mobile") 177 if output, err := gobind.CombinedOutput(); err != nil { 178 t.Logf("%s", output) 179 t.Fatalf("failed to run gomobile bind: %v", err) 180 } 181 build.CopyFile(filepath.Join("libs", "geth.aar"), "geth.aar", os.ModePerm) 182 183 if err = ioutil.WriteFile(filepath.Join("src", "androidTest", "java", "org", "ethereum", "gethtest", "AndroidTest.java"), []byte(androidTestClass), os.ModePerm); err != nil { 184 t.Fatalf("failed to write Android test class: %v", err) 185 } 186 // Finish creating the project and run the tests via gradle 187 if err = ioutil.WriteFile(filepath.Join("src", "main", "AndroidManifest.xml"), []byte(androidManifest), os.ModePerm); err != nil { 188 t.Fatalf("failed to write Android manifest: %v", err) 189 } 190 if err = ioutil.WriteFile("build.gradle", []byte(gradleConfig), os.ModePerm); err != nil { 191 t.Fatalf("failed to write gradle build file: %v", err) 192 } 193 if output, err := exec.Command("gradle", "connectedAndroidTest").CombinedOutput(); err != nil { 194 t.Logf("%s", output) 195 t.Errorf("failed to run gradle test: %v", err) 196 } 197 } 198 199 const androidManifest = `<?xml version="1.0" encoding="utf-8"?> 200 <manifest xmlns:android="http://schemas.android.com/apk/res/android" 201 package="org.ethereum.gethtest" 202 android:versionCode="1" 203 android:versionName="1.0"> 204 205 <uses-permission android:name="android.permission.INTERNET" /> 206 </manifest>` 207 208 const gradleConfig = `buildscript { 209 repositories { 210 jcenter() 211 } 212 dependencies { 213 classpath 'com.android.tools.build:gradle:1.5.0' 214 } 215 } 216 allprojects { 217 repositories { jcenter() } 218 } 219 apply plugin: 'com.android.library' 220 android { 221 compileSdkVersion 'android-19' 222 buildToolsVersion '21.1.2' 223 defaultConfig { minSdkVersion 15 } 224 } 225 repositories { 226 flatDir { dirs 'libs' } 227 } 228 dependencies { 229 compile 'com.android.support:appcompat-v7:19.0.0' 230 compile(name: "geth", ext: "aar") 231 } 232 `