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