Introduction
For Android Studio usage:
- Put the Maven local or remote repository inside the project's build.gradle. Example with Maven local repository:
buildscript { repositories { jcenter() mavenLocal() } }
- Inside the dependencies of the application build.gradle file (your application and not the build.gradle in the root project), add the library :
dependencies { compile ('com.greenspector.probe.android:greenspector-probe-android:[version]') }
- In the Manifest:
To use Internet, put:
<uses-permission android:name="android.permission.INTERNET"/>
To write results in sdcard
, put:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
IMPORTANT
Beginning in Android 6.0 (API level 23), some permissions are now considered *dangerous*.
The permissions *android.permission.READ_EXTERNAL_STORAGE* and *android.permission.WRITE_EXTERNAL_STORAGE* must be granted explicitly via ADB commands for the measures to work.
First install your application on your mobile, then launch the following commands to grant permissions:
adb shell pm grant com.example.myapp android.permission.READ_EXTERNAL_STORAGE adb shell pm grant com.example.myapp android.permission.WRITE_EXTERNAL_STORAGE
Integration
Generic Android Integration
API
setUpMeasure(Context context, String[] packageName, int[] lstPid, String Appname, String Version, String URL, String privateToken, int timeout, int interval, boolean online)
Sets up the measure with all the needed data.
- Context: We pass the context of the application.
- PackageName: Package name of the application to survey. For example, "com.android.chrome". If it is blank (""), the probe does not survey any particular process.
- lstPid: (Optional) In case of system application, the probe can't get the pid by package name so you need to precise the PID list matching the package name list.
- Appname: GREENSPECTOR's application name
- Version: Current application's version
- URL: GREENSPECTOR's server URL. For saas : https://api.greenspector.com/api. For on premises server, replace api.greenspector.com. by your URL
- privateToken: User's private token
- timeout: Test time in seconds. The measure stops when the measure time reaches timeout.
- interval: Measure interval in milliseconds. The interval must be greater than 100 ms or be 0 for not setting the interval.
- online: set false for recording the measures in phones, set true for sending it immediately to server.
startMeasure()
Starts the measure.
stopMeasure(String testName)
Stops the measure and write the results on the phone or send it to the GREENSPECTOR Server.
- testName: Name of the current test.
setCoverageFile(String fileName) (Optional)
Sets the path to coverage file.
If never set it, the default value is: /mnt/sdcard/greenspector/coverages/[Application Package]/[Test Name]-coverage.ec
setMetadataFile(String fileName) (Optional)
Sets the path to metadata file.
If never set it, the default value is: /mnt/sdcard/greenspector/coverages/[Application Package]/coverage.em
setProxy(String url, int port) (Optional)
Sets the proxy URL and port
If never set it, no proxy will be used.
setProxy(String url, int port, String login, String password) (Optional)
Sets the proxy URL, port and authentication informations
If never set it, no proxy will be used.
int cpt_test
Sends the number of the completed tests to the probe. Enables the number of tests identification and the calculation of standardized metrics.
Integration with your program
Usage example:
package com.greenspector.sample.BasicExample; import android.content.Context; import android.test.InstrumentationTestCase; import android.support.test.InstrumentationRegistry; import com.greenspector.probe.android.interfaces.Api; public class GreenspectorBasicExample extends InstrumentationTestCase { // Package to measure private static final String BASIC_SAMPLE_PACKAGE = "com.android.chrome"; /** Probe configuration **/ private static final String APPLICATION = "TestApplication"; private static final String VERSION = "1.0.2"; private static final String URL = "https://my-instance.greenspector.com/api"; private static final String PRIVATETOKEN = "123456789AZERTY"; private static final int TIMEOUT = 180; private static final int INTERVAL = 200; private static final boolean ONLINE = true; private Api gsptpp; public void testBasicExample() { gsptpp = new Api(); gsptpp.setUpMeasure(getInstrumentation().getTargetContext(), new String[]{BASIC_SAMPLE_PACKAGE}, null, APPLICATION, VERSION, URL, PRIVATETOKEN, TIMEOUT, INTERVAL, ONLINE); gsptpp.startMeasure(); try { Thread.sleep(10000); } catch (InterruptedException e) { gsptpp.stopMeasure("test_Idle_Failed"); return; } gsptpp.stopMeasure("test_Idle"); } }
Usage with Greenspector Testrunnner
You can also use the Greenspector Meter Android API in continuous integration with
the Testrunner. To do so, you have to setup your Android Espresso or UIAutomator
tests with the Greenspector Probe just like in the previous section with little changes.
Indeed, you only need to initialize the *BASIC_SAMPLE_PACKAGE* and leave default values
in the *Probe configuration* of the code sample above and the rest will be handled by
the Testrunner.
Samples
Android Test cases
Emma
.Ant
.Requirements
- Updated file ant.properties with the keystore informations
- Updated file local.properties with Android SDK informations
- Running GREENSPECTOR Server
.Folder Default Content
emma-sample-project/
├── libs/ (Libs folder)
├── junit-4.12.jar (JUnit library)
└── probe.jar (GreenSpector library)
├── src/ (Source folder)
├── AndroidManifest.xml
├── ant.properties
├── build.xml
├── custom_rules.xml
├── local.properties
├── proguard-project.txt
└── project.properties
.Custom_rules.xml default content
The file custom_rules.xml overwrites android default target "-post-compile" which is originally empty.
What it does is to copy the coverage.em file from the output folder to
/sdcard/greenspector/coverages/*[AppPackage]*/coverage.em
So the probe can send it to the GREENSPECTOR server.
If your own project does not use ant, feel free to push the coverage.em file yourself as long as it is in the same folder.
Else if you want to use the probe in offline only, you may not use this script too as the file will not be read and sent.
<project name="custom_rules"> <target name="-post-compile"> <if condition="${emma.enabled}"> <then> <echo level="info">Uploading coverage.em file into sdcard ...</echo> <if> <condition> <resourceexists> <file file="${emma.coverage.absolute.file}"/> </resourceexists> </condition> <then> <exec executable="${adb}" failonerror="true"> <arg line="${adb.device.arg}" /> <arg value="push" /> <arg value="${emma.coverage.absolute.file}" /> <arg value="/sdcard/greenspector/coverages/${project.app.package}/coverage.em" /> </exec> </then> <else> <fail message="File ${emma.coverage.absolute.file} does not exist." /> </else> </if> </then> </if> </target> </project>
.Install Sample Application
- Connect the android device (it may not be rooted)
- Check the adb connexion
- Run the following command to install the covered application:
$ ant
emma (Enables coverage)
debug install (Installs debug version)
-Demma.filter=-*test* (Removes all packages that contains "test" from coverage)
.Run Sample Test
- Connect the android device
- Check the adb connexion
- Run the following command to run the tests with coverage on:
$ adb shell am instrument -w -r
-e coverage true (Enables coverage)
-e coverageFile /sdcard/grenspector/coverages/com.kaliterre.coverage.sample.activity/test_MainActivity-coverage.ec (Sets coverage output file path)
com.kaliterre.coverage.sample.activity/android.test.InstrumentationTestRunner
The sample runs, by default, in offline mode, so the measure and coverage results are saved into the sdcard. You can now use GREENSPECTOR Command Line to send the measure and/or coverage files.
If you want to run a test using the probe in online mode, be sure to run the test a first time to write the coverage file, as it is written at the end of the test, and then run a second time to send it.
Nevertheless, if you don't want the measure to be sent twice to the server, you can run the first test in offline mode with coverage enabled to save it into the sdcard and then run in online mode without coverage as it is already done.
.Get Results
*Online Mode*
If you run the tests in Online mode, the result should be sent to GREENSPECTOR Server.
If you don't find any of the test you've run, take a look at the Troubleshooting part cause this may be a connexion error.
*Offline Mode*
If you run the test in Offline mode, your results are saved into the sdcard and you may have to use GREENSPECTOR Command Line to send them to server.
Measure file:
/mnt/sdcard/greenspector/measures/[Application Name]-[Test Name]-[Timestamp].json
Coverage default metadata file:
/mnt/sdcard/greenspector/coverages/[Package Name]/coverage.em
Coverage default coverage file:
/mnt/sdcard/greenspector/coverages/[Package Name]/[Test Name]-coverage.ec
You can now retrieve the data from the phone with the command :
adb pull /mnt/sdcard/greenspector/ /home/[user]/greenspectorData/
Gradle
.Requirements
- Gradle project
- Gradle GREENSPECTOR file: greenspector-coverage.gradle
- Ant GREENSPECTOR file: greenspector-coverage-ant.xml
- Emma Android library: emma_device.jar
NB: You can find the GREENSPECTOR files down below and the Emma Android library in: {your sdk folder}/tools/lib/
.Installation
. Put both Gradle and Ant GREENSPECTOR's files next to your project build.gradle file.
. Add the Emma Android library into your lib folder.
. Include our Gradle file to your project by simply adding the line apply from: 'greenspector-coverage.gradle' to your build.gradle file
. Compile the project
. The file coverage.em will be in your output folder
.Usage
*Online*
. Copy the file coverage.em into your phone. (By default: /sdcard/greenspector/coverages/{package name}/)
. Run the test with coverage:
$ adb shell am instrument -w -r
-e coverage true (Enables coverage)
-e coverageFile /sdcard/greenspector/coverages/{package name}/{test name}-coverage.ec (Sets coverage.ec output file path) {package name}/android.test.InstrumentationTestRunner
NB: Because the coverage file is written at the end of the test, sometimes it could have not been sent so you can run the test again to be sure that everything is OK.
*Offline*
. Run the test with the same command line than above
. Copy the file coverage.em from the output folder and coverage.ec from the phone into the same folder on the computer
. Send the coverage data with GREENSPECTOR CLI tool
NB: The coverage.ec file is located where the command -e coveraFile sets it (Here: /sdcard/greenspector/coverages/{package name}/{test-name}-coverage.ec).
.Files
def instrumented = false gradle.taskGraph.afterTask { Task task -> if(task.name.startsWith('compile') && task.name.endsWith('Sources') && !instrumented) { ant.importBuild "greenspector-coverage-ant.xml" tasks.instrument.execute() instrumented = true } }
<?xml version="1.0" encoding="UTF-8"?> <project> <property file="../local.properties" /> <!-- Emma configuration --> <property name="emma.dir" value="${sdk.dir}/tools/lib" /> <path id="emma.lib"> <pathelement location="${emma.dir}/emma.jar" /> <pathelement location="${emma.dir}/emma_ant.jar" /> </path> <taskdef resource="emma_ant.properties" classpathref="emma.lib" /> <!-- End of emma configuration --> <!-- Output directories --> <property name="out.dir" value="build" /> <property name="out.classes.absolute.dir" location="${out.dir}/intermediates/classes" /> <condition property="verbosity" value="verbose" else="quiet"> <istrue value="${verbose}" /> </condition> <!-- Instruments this project's .class files. --> <target name="instrument"> <echo message="Instrumenting classes from ${out.dir}/classes..."></echo> <property name="emma.coverage.absolute.file" location="${out.dir}/coverage.em" /> <!-- It only instruments class files, not any external libs --> <emma enabled="true"> <instr verbosity="${verbosity}" mode="overwrite" instrpath="${out.classes.absolute.dir}" outdir="${out.classes.absolute.dir}" metadatafile="${emma.coverage.absolute.file}"> </instr> </emma> </target> </project>
UIAutomator Sample Project
If you are new to GREENSPECTOR for UiAutomator, try this sample first.
This project uses the Gradle build system. You don't need an IDE to build and execute it but Android Studio is recommended.
.. Open the Android SDK Manager (Tools Menu | Android) and make sure you have installed the Android testing support library Repository under Extras.
.. In Android Studio, select File | Open... and point to the ./build.gradle file.
.. Check out the relevant code:
- Tests are in src/androidTest/java
.. Create the test configuration with a custom runner: android.support.test.runner.AndroidJUnitRunner
- Open Run menu | Edit Configurations
- Add a new Android Tests configuration
- Choose a module
- Add a Specific instrumentation runner: android.support.test.runner.AndroidJUnitRunner
.. Run the newly created configuration
The application will be started on the device/emulator and a series of actions will be performed automatically.
If you are using Android Studio, the Run window will show the test results.
Usage
Test Cases
- I can send the measures in disconnected mode to the GSPT server and then retrieve them with using a command line from my PC to the server
- The test case launch automatically sends the coverage information to GREENSPECTOR
- I can send the coverage file by command line to GREENSPECTOR
- I can have the information on the resources but also on the objects with a meter running Android
- I can develop Android probe with a SDK