For Android Studio usage:
- Put the Maven local or remote repository inside the project's build.gradle. Example with Maven local repository:
Status | ||||
---|---|---|---|---|
|
Table of Contents |
---|
You can include Meter Android API in your automated tests (UI Automator or Espresso for example) so that you can measure your application without modifying the code of your application.
Note : You can also include it in an android application directly if the goal is not to measure this application (Prefer not using this way)
API reference
init
Code Block | ||||
---|---|---|---|---|
| ||||
buildscript {
repositories {
jcenter()
mavenLocal()
}
} |
...
public void init(Context context) |
Init the probe with the Context.
context
: Context of your Instumentation or Android's application.
init
Code Block | ||||
---|---|---|---|---|
| ||||
dependencies {
compile ('com.greenspector.probe.android:greenspector-probe-android:[version]')
} |
- In the Manifest:
To use Internet, put:
Code Block | ||
---|---|---|
| ||
<uses-permission android:name="android.permission.INTERNET"/> |
To write results in sdcard
, put:
Code Block | ||
---|---|---|
| ||
<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:
[source,bash]
----
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
[source,java]
----
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.
...
public void init(Context context, String[] packageName, int[] lstPid, String appName, String version, String url, String privateToken, boolean online) |
Sets up the probe with all the needed data.
context
: Context of your Instumentation or Android's application.packageName
: Package name of the application to monitor (for examplecom.android.chrome
). If it is blank (""), the probe does not monitor any particular process.lstPid
: In case of system applications, the probe can't get the PID by package name so you need to precise the PID list matching the package name. (Optional)appName
: GREENSPECTOR's application name.version
: GREENSPECTOR's application version.url
: GREENSPECTOR's server URL. For SaaS: https://api.greenspector.com/api. For on premises servers, replace api.greenspector.com by your URL.privateToken
: Your private token.online
: Setfalse
to write the results on your device. Use this case if you launch your automated tests (UI Automator or Espresso for example) with the Test Runner or the Power Test Cloud/Bench. Settrue
to send the measures immediately to your GREENSPECTOR server. Use this case if you launch your tests with Android Studio (i.e. you do not use the Test Runner or the Power Test Cloud / Bench).
setUpMeasure (Deprecated)
Code Block | ||
---|---|---|
| ||
public void setUpMeasure(Context context, String[] packageName, int[] lstPid, String appName, String version, String url, String privateToken, int timeout, int interval, boolean online) |
Sets up the probe with all the needed data. This method is deprecated.
context
: Context of your Instumentation or Android's application.packageName
: Package name of the application to monitor (for examplecom.android.chrome
). If it is blank (""), the probe does not
...
- monitor any particular process.
...
lstPid
:
...
- In case of system
...
- applications, the probe can't get the
...
- PID by package name so you need to precise the PID list matching the package name
...
- . (Optional)
...
appName
: GREENSPECTOR's application name.
...
version
:
...
- GREENSPECTOR's application version.
...
url
: GREENSPECTOR's server URL. For
...
- SaaS: https://api.greenspector.com/api. For on premises
...
- servers, replace api.greenspector.com
...
- by your URL.
...
privateToken
:
...
- Your private token.
...
timeout
: Test time in seconds. The measure stops when the measure time reaches this timeout. deprecated
...
interval
: Measure interval in milliseconds. The interval must be greater than 100 ms or can be 0
...
[source,java]
----
startMeasure()
----
Starts the measure.
[source,java]
----
stopMeasure(String testName)
----
Stops the measure and write the results on the phone or send it to the GREENSPECTOR Server.
...
- if you do not want to set it. deprecated
online
: Setfalse
to write the results on your device. Use this case if you launch your automated tests (UI Automator or Espresso for example) with the Test Runner or the Power Test Cloud/Bench. Settrue
to send the measures immediately to your GREENSPECTOR server. Use this case if you launch your tests with Android Studio (i.e. you do not use the Test Runner or the Power Test Cloud / Bench).
startMeasure
Code Block | ||
---|---|---|
| ||
public boolean startMeasure() |
Starts the measure.
Returns a boolean indicating whether the measure was successfully started or not.
stopMeasure
Code Block | ||
---|---|---|
| ||
public boolean stopMeasure(String testName) |
Stops the measure and writes the results on the device or sends them to your GREENSPECTOR Server.
testName
: Name of the current test.
[source,java]
----
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
[source,java]
----
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
[source,java]
----
setProxy(String url, int port) (Optional)
----
Sets the proxy URL and port
If never set it, no proxy will be used.
[source,java]
----
setProxy(String url, int port, String login, String password) (Optional)
----
Sets the proxy URL, port and authentication informations
If never set itReturns a boolean indicating whether the measure was successfully stopped or not.
setProxy (optional)
Code Block | ||
---|---|---|
| ||
public void setProxy(String url, int port)
public void setProxy(String url, int port, String login, String password |
Sets the proxy URL and port.
If never set, no proxy will be used.[source,java]
----
int
cpt_test
Code Block | ||
---|---|---|
| ||
public int cpt_test |
----Sends Use this counter to set 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
[source,java]
----
package iterations (default: 1 iteration). This counter must be uptaded before calling the method stopMeasure()
to be taken into account.
If you set a number of iterations for your test case, measures and data displayed on GREENSPECTOR Web Interface will refer to the mean value for one iteration.
Usage
Example of a Test Instrumentation
Code Block | ||||
---|---|---|---|---|
| ||||
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 |
...
private Api gsptpp;
...
final boolean ONLINE = true; private Api gsptApi; public void testBasicExample() { gsptApi = new Api(); gsptApi.init(getInstrumentation().getTargetContext(), new String[]{BASIC_SAMPLE_PACKAGE}, null, APPLICATION, VERSION, URL, PRIVATETOKEN, |
...
ONLINE); |
...
gsptApi.startMeasure(); |
...
try { |
...
Thread.sleep(10000); |
...
} catch (InterruptedException e) |
...
{ gsptApi.stopMeasure("test_Idle_Failed"); |
...
return; |
...
} gsptApi.stopMeasure("test_Idle"); |
...
} |
...
} |
...
...
Usage with
...
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.
[source,xml]
----
<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
[source,java]
.greenspector-coverage.gradle
----
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
}
}
----
[source,xml]
.greenspector-coverage-ant.xml
----
<?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
...
Android Studio
If you launch your automated tests (UI Automator or Espresso for example) with Android Studio, if you have set all parameters, especially online
to true,
the measure is sent to your instance. Use this method :
Code Block | ||
---|---|---|
| ||
public void init(Context context, String[] packageName, int[] lstPid, String appName, String version, String url, String privateToken, boolean online) |
Usage with GREENSPECTOR Test Runnner or Power Test Cloud/Bench
If you launch your automated tests (UI Automator or Espresso for example) with the Test Runner or the Power Test Cloud/Bench, the probe configuration is not important. All fields are not taken into account because they are directly handled by Test Runner Or Test Bench job parameters.
Use this method.
Code Block | ||
---|---|---|
| ||
public void init(Context context) |
or this method (all arguments except context are not taken into account). So you do not need to change your code if you launch with Test Runner or with Android Studio
Code Block | ||
---|---|---|
| ||
public void init(Context context, String[] packageName, int[] lstPid, String appName, String version, String url, String privateToken, boolean online) |
Related articles
Filter by label (Content by label) | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|