Skip to content
This repository has been archived by the owner on May 14, 2021. It is now read-only.

Commit

Permalink
Merge pull request #41 from kinecosystem/code_coverage
Browse files Browse the repository at this point in the history
Code coverage
  • Loading branch information
yosriz authored May 14, 2018
2 parents 4e7bce7 + 6f2339d commit 2f91f69
Show file tree
Hide file tree
Showing 11 changed files with 156 additions and 44 deletions.
8 changes: 4 additions & 4 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ before_script:

script:
- ./gradlew :sample:assembleDebug
- ./gradlew :kin-core:test
- ./gradlew kin-core:assembleDebugAndroidTest
- adb install -r ./kin-core/build/outputs/apk/androidTest/debug/kin-core-debug-androidTest.apk
- ./run_android_test_ci.sh
#skip large network related test in KinAccountIntegrationTest class
- ./gradlew jacocoTestReport -Pandroid.testInstrumentationRunnerArguments.notClass=kin.core.KinAccountIntegrationTest

after_success:
- bash <(curl -s https://codecov.io/bash)
7 changes: 4 additions & 3 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ ext {
}

buildscript {

repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath "com.android.tools.build:gradle:3.0.1"
classpath 'org.jacoco:org.jacoco.core:0.8.1'

}
}

Expand Down
1 change: 1 addition & 0 deletions dependencies.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ ext {
robolectricVersion = '3.6.1'
hamcrestVersion = '1.3'
gsonVersion = '2.4'
jacocoVersion = '0.8.0'

//Packages
supportPackage = 'com.android.support'
Expand Down
40 changes: 40 additions & 0 deletions kin-core/build.gradle
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
apply plugin: 'com.android.library'
apply plugin: 'jacoco'

// maven plugin and group definition
// needed for jitpack support
Expand All @@ -17,6 +18,18 @@ android {
consumerProguardFiles 'proguard-rules.pro'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

buildTypes {
debug {
testCoverageEnabled true
}
}

testOptions {
unitTests {
includeAndroidResources = true
}
}
}

dependencies {
Expand Down Expand Up @@ -53,4 +66,31 @@ task sourcesJar(type: Jar) {
}
artifacts {
archives sourcesJar
}

//jacoco unified code coverage
jacoco {
toolVersion = '0.8.1'
}

tasks.withType(Test) {
jacoco.includeNoLocationClasses = true
}

task jacocoTestReport(type: JacocoReport, dependsOn: ['testDebugUnitTest', 'createDebugCoverageReport']) {

reports {
xml.enabled = true
html.enabled = true
}

def fileFilter = ['**/R.class', '**/R$*.class', '**/BuildConfig.*', '**/Manifest*.*', '**/*Test*.*', 'android/**/*.*']
def debugTree = fileTree(dir: "$project.buildDir/intermediates/classes/debug", excludes: fileFilter)
def mainSrc = "$project.projectDir/src/main/java"

sourceDirectories = files([mainSrc])
classDirectories = files([debugTree])
executionData = fileTree(dir: project.buildDir, includes: [
'jacoco/testDebugUnitTest.exec', 'outputs/code-coverage/connected/*coverage.ec'
])
}
16 changes: 3 additions & 13 deletions kin-core/src/androidTest/java/kin/core/FakeKinIssuer.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@


import static junit.framework.Assert.assertTrue;
import static kin.core.IntegConsts.TEST_NETWORK_URL;
import static kin.core.IntegConsts.URL_CREATE_ACCOUNT;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import org.stellar.sdk.Asset;
Expand All @@ -23,11 +24,6 @@
class FakeKinIssuer {

private static final int TIMEOUT_SEC = 20;
private static final String TEST_NETWORK_URL = "https://horizon-testnet.stellar.org";
private static final String TEST_NETWORK_SCHEME = "https";
private static final String TEST_NETWORK_HOST = "horizon-testnet.stellar.org";
private static final String TEST_NETWORK_PATH_SEGMENT = "friendbot";
private static final String TEST_NETWORK_QUERY_PARAM = "addr";

private final Server server;
private final KeyPair issuerKeyPair;
Expand All @@ -45,15 +41,9 @@ String getAccountId() {
}

private void createAndFundWithLumens(String accountId) throws IOException {
HttpUrl url = new HttpUrl.Builder()
.scheme(TEST_NETWORK_SCHEME)
.host(TEST_NETWORK_HOST)
.addPathSegment(TEST_NETWORK_PATH_SEGMENT)
.addQueryParameter(TEST_NETWORK_QUERY_PARAM, accountId)
.build();
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url(url).build();
.url(URL_CREATE_ACCOUNT + accountId).build();
Response response = client.newCall(request).execute();
assertTrue(response != null && response.body() != null && response.code() == 200);
}
Expand Down
9 changes: 9 additions & 0 deletions kin-core/src/androidTest/java/kin/core/IntegConsts.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package kin.core;


final class IntegConsts {

static final String TEST_NETWORK_URL = "https://horizon-kik.kininfrastructure.com";
static final String TEST_NETWORK_ID = "private testnet";
static final String URL_CREATE_ACCOUNT = "http://friendbot-kik.kininfrastructure.com/?addr=";
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@


import static junit.framework.Assert.fail;
import static kin.core.IntegConsts.TEST_NETWORK_ID;
import static kin.core.IntegConsts.TEST_NETWORK_URL;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
Expand Down Expand Up @@ -32,7 +34,6 @@
@SuppressWarnings({"deprecation", "ConstantConditions"})
public class KinAccountIntegrationTest {

private static final String TEST_NETWORK_URL = "https://horizon-testnet.stellar.org";
private static FakeKinIssuer fakeKinIssuer;
private KinClient kinClient;

Expand All @@ -47,7 +48,7 @@ static public void setupKinIssuer() throws IOException {
private class TestServiceProvider extends ServiceProvider {

TestServiceProvider() {
super(TEST_NETWORK_URL, NETWORK_ID_TEST);
super(TEST_NETWORK_URL, TEST_NETWORK_ID);
}

@Override
Expand Down Expand Up @@ -265,39 +266,64 @@ public void createPaymentListener_ListenToSender_PaymentEvent() throws Exception
}

private void listenToPayments(boolean sender) throws Exception {
//create and sets 2 accounts (receiver/sender), fund one account, and then
//send transaction from the funded account to the other, observe this transaction using listeners
BigDecimal fundingAmount = new BigDecimal("100");
BigDecimal transactionAmount = new BigDecimal("21.123");

KinAccount kinAccountSender = kinClient.addAccount();
KinAccount kinAccountReceiver = kinClient.addAccount();
fakeKinIssuer.createAccount(kinAccountSender.getPublicAddress());
fakeKinIssuer.createAccount(kinAccountReceiver.getPublicAddress());

kinAccountSender.activateSync();
kinAccountReceiver.activateSync();
fakeKinIssuer.fundWithKin(kinAccountSender.getPublicAddress(), "100");

final CountDownLatch latch = new CountDownLatch(1);
final List<PaymentInfo> actualResults = new ArrayList<>();
//register listeners for testing
final List<PaymentInfo> actualPaymentsResults = new ArrayList<>();
final List<Balance> actualBalanceResults = new ArrayList<>();
KinAccount accountToListen = sender ? kinAccountSender : kinAccountReceiver;

int eventsCount = sender ? 4 : 2; ///in case of observing the sender we'll get 2 events (1 for funding 1 for the
//transaction) in case of receiver - only 1 event.
//multiply by 2, as we 2 listeners (balance and payment)
final CountDownLatch latch = new CountDownLatch(eventsCount);
accountToListen.blockchainEvents().addPaymentListener(new EventListener<PaymentInfo>() {
@Override
public void onEvent(PaymentInfo data) {
actualResults.add(data);
actualPaymentsResults.add(data);
latch.countDown();
}
});
accountToListen.blockchainEvents().addBalanceListener(new EventListener<Balance>() {
@Override
public void onEvent(Balance data) {
actualBalanceResults.add(data);
latch.countDown();
}
});

BigDecimal expectedAmount = new BigDecimal("21.123");
//send the transaction we want to observe
fakeKinIssuer.fundWithKin(kinAccountSender.getPublicAddress(), "100");
String expectedMemo = "memo";
TransactionId expectedTransactionId = kinAccountSender
.sendTransactionSync(kinAccountReceiver.getPublicAddress(), expectedAmount, expectedMemo);
.sendTransactionSync(kinAccountReceiver.getPublicAddress(), transactionAmount, expectedMemo);

//verify data notified by listeners
int transactionIndex =
sender ? 1 : 0; //in case of observing the sender we'll get 2 events (1 for funding 1 for the
//transaction) in case of receiver - only 1 event
latch.await(10, TimeUnit.SECONDS);
assertThat(actualResults.size(), equalTo(1));
PaymentInfo paymentInfo = actualResults.get(0);
assertThat(paymentInfo.amount(), equalTo(expectedAmount));
PaymentInfo paymentInfo = actualPaymentsResults.get(transactionIndex);
assertThat(paymentInfo.amount(), equalTo(transactionAmount));
assertThat(paymentInfo.destinationPublicKey(), equalTo(kinAccountReceiver.getPublicAddress()));
assertThat(paymentInfo.sourcePublicKey(), equalTo(kinAccountSender.getPublicAddress()));
assertThat(paymentInfo.memo(), equalTo(expectedMemo));
assertThat(paymentInfo.hash().id(), equalTo(expectedTransactionId.id()));

Balance balance = actualBalanceResults.get(transactionIndex);
assertThat(balance.value(),
equalTo(sender ? fundingAmount.subtract(transactionAmount) : transactionAmount));
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static kin.core.IntegConsts.TEST_NETWORK_ID;
import static kin.core.IntegConsts.TEST_NETWORK_URL;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
Expand All @@ -21,7 +23,6 @@
@SuppressWarnings("deprecation")
public class KinClientIntegrationTest {

private static final String TEST_NETWORK_URL = "https://horizon-testnet.stellar.org";
private ServiceProvider serviceProvider;
private KinClient kinClient;

Expand All @@ -30,7 +31,7 @@ public class KinClientIntegrationTest {

@Before
public void setup() {
serviceProvider = new ServiceProvider(TEST_NETWORK_URL, ServiceProvider.NETWORK_ID_TEST);
serviceProvider = new ServiceProvider(TEST_NETWORK_URL, TEST_NETWORK_ID);
kinClient = new KinClient(InstrumentationRegistry.getTargetContext(), serviceProvider);
kinClient.clearAllAccounts();
}
Expand Down
4 changes: 2 additions & 2 deletions kin-core/src/androidTest/java/kin/core/RequestTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@
@RunWith(AndroidJUnit4.class)
public class RequestTest {

private static final int TASK_DURATION_MILLIS = 10;
private static final int TIMEOUT_DURATION_MILLIS = 100;
private static final int TASK_DURATION_MILLIS = 100;
private static final int TIMEOUT_DURATION_MILLIS = 500;

public interface Consumer<T> {

Expand Down
53 changes: 53 additions & 0 deletions kin-core/src/test/java/kin/core/BlockchainEventsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import static kin.core.TestUtils.loadResource;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
Expand Down Expand Up @@ -235,6 +236,50 @@ public void onEvent(Void data) {
assertThat(eventsCount[0], equalTo(1));
}

@Test
public void addBalanceListener() throws Exception {
enqueueTransactionsResponses();

final CountDownLatch latch = new CountDownLatch(1);
final List<Balance> actualResults = new ArrayList<>();
blockchainEvents.addBalanceListener(new EventListener<Balance>() {
@Override
public void onEvent(Balance data) {
actualResults.add(data);
if (actualResults.size() == 2) {
latch.countDown();
}
}
});
latch.await(1, TimeUnit.SECONDS);

assertThat(actualResults.size(), equalTo(2));
Balance balance1 = actualResults.get(0);
Balance balance2 = actualResults.get(1);

assertThat(balance1, notNullValue());
assertThat(balance2, notNullValue());
//expected balances values are the ones encoded at transactions responses jsons (see enqueueTransactionsResponses)
assertThat(balance1.value(), equalTo(new BigDecimal("5387.216")));
assertThat(balance2.value(), equalTo(new BigDecimal("5239.89036")));
}

@Test
public void addBalanceListener_StopListener_NoEvents() throws Exception {
final int[] eventsCount = {0};
ListenerRegistration listenerRegistration = blockchainEvents
.addBalanceListener(new EventListener<Balance>() {
@Override
public void onEvent(Balance data) {
eventsCount[0]++;
}
});
listenerRegistration.remove();
enqueueCreateAccountResponses();
Thread.sleep(500);
assertThat(eventsCount[0], equalTo(0));
}

@SuppressWarnings("ConstantConditions")
@Test
public void addPaymentListener_NullListener_IllegalArgumentException() throws Exception {
Expand All @@ -250,4 +295,12 @@ public void addAccountCreationListener_NullListener_IllegalArgumentException() t
expectedEx.expectMessage("listener");
blockchainEvents.addAccountCreationListener(null);
}

@SuppressWarnings("ConstantConditions")
@Test
public void addBalanceListener_NullListener_IllegalArgumentException() throws Exception {
expectedEx.expect(IllegalArgumentException.class);
expectedEx.expectMessage("listener");
blockchainEvents.addBalanceListener(null);
}
}
9 changes: 0 additions & 9 deletions run_android_test_ci.sh

This file was deleted.

0 comments on commit 2f91f69

Please sign in to comment.