android_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  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. package geth
  17. import (
  18. "io/ioutil"
  19. "os"
  20. "os/exec"
  21. "path/filepath"
  22. "runtime"
  23. "testing"
  24. "time"
  25. "github.com/ethereum/go-ethereum/internal/build"
  26. )
  27. // androidTestClass is a Java class to do some lightweight tests against the Android
  28. // bindings. The goal is not to test each individual functionality, rather just to
  29. // catch breaking API and/or implementation changes.
  30. const androidTestClass = `
  31. package go;
  32. import android.test.InstrumentationTestCase;
  33. import android.test.MoreAsserts;
  34. import org.ethereum.geth.*;
  35. public class AndroidTest extends InstrumentationTestCase {
  36. public AndroidTest() {}
  37. public void testAccountManagement() {
  38. // Create an encrypted keystore manager with light crypto parameters.
  39. AccountManager am = new AccountManager(getInstrumentation().getContext().getFilesDir() + "/keystore", Geth.LightScryptN, Geth.LightScryptP);
  40. try {
  41. // Create a new account with the specified encryption passphrase.
  42. Account newAcc = am.newAccount("Creation password");
  43. // Export the newly created account with a different passphrase. The returned
  44. // data from this method invocation is a JSON encoded, encrypted key-file.
  45. byte[] jsonAcc = am.exportKey(newAcc, "Creation password", "Export password");
  46. // Update the passphrase on the account created above inside the local keystore.
  47. am.updateAccount(newAcc, "Creation password", "Update password");
  48. // Delete the account updated above from the local keystore.
  49. am.deleteAccount(newAcc, "Update password");
  50. // Import back the account we've exported (and then deleted) above with yet
  51. // again a fresh passphrase.
  52. Account impAcc = am.importKey(jsonAcc, "Export password", "Import password");
  53. // Create a new account to sign transactions with
  54. Account signer = am.newAccount("Signer password");
  55. Hash txHash = new Hash("0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef");
  56. // Sign a transaction with a single authorization
  57. byte[] signature = am.signWithPassphrase(signer, "Signer password", txHash.getBytes());
  58. // Sign a transaction with multiple manually cancelled authorizations
  59. am.unlock(signer, "Signer password");
  60. signature = am.sign(signer.getAddress(), txHash.getBytes());
  61. am.lock(signer.getAddress());
  62. // Sign a transaction with multiple automatically cancelled authorizations
  63. am.timedUnlock(signer, "Signer password", 1000000000);
  64. signature = am.sign(signer.getAddress(), txHash.getBytes());
  65. } catch (Exception e) {
  66. fail(e.toString());
  67. }
  68. }
  69. public void testInprocNode() {
  70. Context ctx = new Context();
  71. try {
  72. // Start up a new inprocess node
  73. Node node = new Node(getInstrumentation().getContext().getFilesDir() + "/.ethereum", new NodeConfig());
  74. node.start();
  75. // Retrieve some data via function calls (we don't really care about the results)
  76. NodeInfo info = node.getNodeInfo();
  77. info.getName();
  78. info.getListenerAddress();
  79. info.getProtocols();
  80. // Retrieve some data via the APIs (we don't really care about the results)
  81. EthereumClient ec = node.getEthereumClient();
  82. ec.getBlockByNumber(ctx, -1).getNumber();
  83. NewHeadHandler handler = new NewHeadHandler() {
  84. @Override public void onError(String error) {}
  85. @Override public void onNewHead(final Header header) {}
  86. };
  87. ec.subscribeNewHead(ctx, handler, 16);
  88. } catch (Exception e) {
  89. fail(e.toString());
  90. }
  91. }
  92. }
  93. `
  94. // TestAndroid runs the Android java test class specified above.
  95. //
  96. // This requires the gradle command in PATH and the Android SDK whose path is available
  97. // through ANDROID_HOME environment variable. To successfully run the tests, an Android
  98. // device must also be available with debugging enabled.
  99. //
  100. // This method has been adapted from golang.org/x/mobile/bind/java/seq_test.go/runTest
  101. func TestAndroid(t *testing.T) {
  102. // Skip tests on Windows altogether
  103. if runtime.GOOS == "windows" {
  104. t.Skip("cannot test Android bindings on Windows, skipping")
  105. }
  106. // Make sure all the Android tools are installed
  107. if _, err := exec.Command("which", "gradle").CombinedOutput(); err != nil {
  108. t.Skip("command gradle not found, skipping")
  109. }
  110. if sdk := os.Getenv("ANDROID_HOME"); sdk == "" {
  111. t.Skip("ANDROID_HOME environment var not set, skipping")
  112. }
  113. if _, err := exec.Command("which", "gomobile").CombinedOutput(); err != nil {
  114. t.Log("gomobile missing, installing it...")
  115. if _, err := exec.Command("go", "install", "golang.org/x/mobile/cmd/gomobile").CombinedOutput(); err != nil {
  116. t.Fatalf("install failed: %v", err)
  117. }
  118. t.Log("initializing gomobile...")
  119. start := time.Now()
  120. if _, err := exec.Command("gomobile", "init").CombinedOutput(); err != nil {
  121. t.Fatalf("initialization failed: %v", err)
  122. }
  123. t.Logf("initialization took %v", time.Since(start))
  124. }
  125. // Create and switch to a temporary workspace
  126. workspace, err := ioutil.TempDir("", "geth-android-")
  127. if err != nil {
  128. t.Fatalf("failed to create temporary workspace: %v", err)
  129. }
  130. defer os.RemoveAll(workspace)
  131. pwd, err := os.Getwd()
  132. if err != nil {
  133. t.Fatalf("failed to get current working directory: %v", err)
  134. }
  135. if err := os.Chdir(workspace); err != nil {
  136. t.Fatalf("failed to switch to temporary workspace: %v", err)
  137. }
  138. defer os.Chdir(pwd)
  139. // Create the skeleton of the Android project
  140. for _, dir := range []string{"src/main", "src/androidTest/java/org/ethereum/gethtest", "libs"} {
  141. err = os.MkdirAll(dir, os.ModePerm)
  142. if err != nil {
  143. t.Fatal(err)
  144. }
  145. }
  146. // Generate the mobile bindings for Geth and add the tester class
  147. gobind := exec.Command("gomobile", "bind", "-javapkg", "org.ethereum", "github.com/ethereum/go-ethereum/mobile")
  148. if output, err := gobind.CombinedOutput(); err != nil {
  149. t.Logf("%s", output)
  150. t.Fatalf("failed to run gomobile bind: %v", err)
  151. }
  152. build.CopyFile(filepath.Join("libs", "geth.aar"), "geth.aar", os.ModePerm)
  153. if err = ioutil.WriteFile(filepath.Join("src", "androidTest", "java", "org", "ethereum", "gethtest", "AndroidTest.java"), []byte(androidTestClass), os.ModePerm); err != nil {
  154. t.Fatalf("failed to write Android test class: %v", err)
  155. }
  156. // Finish creating the project and run the tests via gradle
  157. if err = ioutil.WriteFile(filepath.Join("src", "main", "AndroidManifest.xml"), []byte(androidManifest), os.ModePerm); err != nil {
  158. t.Fatalf("failed to write Android manifest: %v", err)
  159. }
  160. if err = ioutil.WriteFile("build.gradle", []byte(gradleConfig), os.ModePerm); err != nil {
  161. t.Fatalf("failed to write gradle build file: %v", err)
  162. }
  163. if output, err := exec.Command("gradle", "connectedAndroidTest").CombinedOutput(); err != nil {
  164. t.Logf("%s", output)
  165. t.Errorf("failed to run gradle test: %v", err)
  166. }
  167. }
  168. const androidManifest = `<?xml version="1.0" encoding="utf-8"?>
  169. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  170. package="org.ethereum.gethtest"
  171. android:versionCode="1"
  172. android:versionName="1.0">
  173. <uses-permission android:name="android.permission.INTERNET" />
  174. </manifest>`
  175. const gradleConfig = `buildscript {
  176. repositories {
  177. jcenter()
  178. }
  179. dependencies {
  180. classpath 'com.android.tools.build:gradle:1.5.0'
  181. }
  182. }
  183. allprojects {
  184. repositories { jcenter() }
  185. }
  186. apply plugin: 'com.android.library'
  187. android {
  188. compileSdkVersion 'android-19'
  189. buildToolsVersion '21.1.2'
  190. defaultConfig { minSdkVersion 15 }
  191. }
  192. repositories {
  193. flatDir { dirs 'libs' }
  194. }
  195. dependencies {
  196. compile 'com.android.support:appcompat-v7:19.0.0'
  197. compile(name: "geth", ext: "aar")
  198. }
  199. `