android_test.go 6.8 KB

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