Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move and port tests from EventBusTest to EventBus module #283

Open
wants to merge 3 commits into
base: plain-java
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions EventBus/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,19 @@ repositories {
configurations {
provided
deployerJars
// include test classes and their dependencies
tests.extendsFrom testRuntime
}

dependencies {
provided 'com.google.android:android:4.1.1.4'
provided 'com.google.android:android-test:4.1.1.4'
provided 'com.google.android:annotations:4.1.1.4'
provided 'com.google.android:support-v4:r7'

testCompile 'junit:junit:4.12'
testCompile fileTree(dir: '../EventBusTest/libs', include: '*.jar')

// deployerJars 'org.apache.maven.wagon:wagon-webdav-jackrabbit:2.4'
deployerJars 'org.apache.maven.wagon:wagon-webdav:1.0-beta-2'
}
Expand All @@ -44,6 +50,10 @@ sourceSets {
// exclude 'de/greenrobot/event/util/**'
}
}
test {
compileClasspath += configurations.provided
java.srcDirs = ['test']
}
}

idea {
Expand All @@ -69,10 +79,20 @@ task sourcesJar(type: Jar) {
classifier = 'sources'
}

// build a jar with all test classes to allow usage as dependency in android test project
// https://discuss.gradle.org/t/how-do-i-declare-a-dependency-on-a-modules-test-code/7172/9
task testJar(type: Jar) {
classifier "test"
from sourceSets.test.output
// exclude tests which can not run on Android
exclude '**/*Jvm*'
}

artifacts {
archives jar
archives javadocJar
archives sourcesJar
tests testJar
}

signing {
Expand Down
10 changes: 9 additions & 1 deletion EventBus/src/org/greenrobot/eventbus/AsyncPoster.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
package org.greenrobot.eventbus;


import java.util.concurrent.Executor;

/**
* Posts events in background.
*
Expand All @@ -25,16 +27,22 @@ class AsyncPoster implements Runnable, Poster {

private final PendingPostQueue queue;
private final EventBus eventBus;
private final Executor executor;

AsyncPoster(EventBus eventBus) {
this(eventBus, eventBus.getExecutorService());
}

AsyncPoster(EventBus eventBus, Executor executor) {
this.eventBus = eventBus;
this.executor = executor;
queue = new PendingPostQueue();
}

public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
executor.execute(this);
}

@Override
Expand Down
6 changes: 2 additions & 4 deletions EventBus/src/org/greenrobot/eventbus/EventBus.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,9 @@ public EventBus() {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.mainThreadSupport != null ? builder.mainThreadSupport :
Logger.AndroidLogger.isAndroidLogAvailable() ?
new MainThreadSupport.AndroidHandlerMainThreadSupport(Looper.getMainLooper()) : null;
mainThreadSupport = builder.mainThreadSupport;
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
Expand All @@ -129,6 +126,7 @@ public EventBus() {
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
asyncPoster = new AsyncPoster(this);
}

/**
Expand Down
14 changes: 14 additions & 0 deletions EventBus/src/org/greenrobot/eventbus/EventBusBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/
package org.greenrobot.eventbus;

import android.os.Looper;

import org.greenrobot.eventbus.meta.SubscriberInfoIndex;

import java.util.ArrayList;
Expand Down Expand Up @@ -44,6 +46,9 @@ public class EventBusBuilder {
MainThreadSupport mainThreadSupport;

EventBusBuilder() {
if (Logger.AndroidLogger.isAndroidLogAvailable()) {
mainThreadSupport = new MainThreadSupport.AndroidHandlerMainThreadSupport(Looper.getMainLooper());
}
}

/** Default: true */
Expand All @@ -70,6 +75,15 @@ public EventBusBuilder sendNoSubscriberEvent(boolean sendNoSubscriberEvent) {
return this;
}

/**
* Interface to the "main" thread, which can be whatever you like
* Default: android main thread if running on Android, or null otherwise
*/
public EventBusBuilder mainThreadSupport(MainThreadSupport mainThreadSupport) {
this.mainThreadSupport = mainThreadSupport;
return this;
}

/**
* Fails if an subscriber throws an exception (default: false).
* <p/>
Expand Down
6 changes: 4 additions & 2 deletions EventBus/src/org/greenrobot/eventbus/Logger.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.greenrobot.eventbus;

import android.os.Looper;
import android.util.Log;

import java.util.logging.Level;
Expand All @@ -31,8 +32,9 @@ public static class AndroidLogger implements Logger {
static {
boolean android = false;
try {
android = Class.forName("android.util.Log") != null;
} catch (ClassNotFoundException e) {
// getMainLooper will throw RuntimeException if running from Android Studio on JVM
android = Class.forName("android.util.Log") != null && Looper.getMainLooper() != null;
} catch (ClassNotFoundException | RuntimeException e) {
// OK
}
ANDROID_LOG_AVAILABLE = android;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,28 @@
*/
package org.greenrobot.eventbus;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.test.runner.AndroidJUnit4;

import org.greenrobot.eventbus.EventBus;
import org.junit.Before;
import org.junit.runner.RunWith;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
* @author Markus Junginger, greenrobot
*/
@RunWith(AndroidJUnit4.class)
public abstract class AbstractEventBusTest {
/** Activates long(er) running tests e.g. testing multi-threading more thoroughly. */
protected static final boolean LONG_TESTS = false;
Expand All @@ -49,7 +49,7 @@ public abstract class AbstractEventBusTest {
protected volatile Object lastEvent;
protected volatile Thread lastThread;

private EventPostHandler mainPoster;
protected Thread mainThread;

public AbstractEventBusTest() {
this(false);
Expand All @@ -66,13 +66,33 @@ public AbstractEventBusTest(boolean collectEventsReceived) {
@Before
public void setUpBase() throws Exception {
EventBus.clearCaches();
eventBus = new EventBus();
mainPoster = new EventPostHandler(Looper.getMainLooper());
assertFalse(Looper.getMainLooper().getThread().equals(Thread.currentThread()));
}

protected void postInMainThread(Object event) {
mainPoster.post(event);
final EventBusBuilder builder = new EventBusBuilder();
if (builder.mainThreadSupport == null) {
final Executor mainExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
mainThread = new Thread(r);
return mainThread;
}
});
// running on JVM
builder.mainThreadSupport = new MainThreadSupport() {
@Override
public boolean isMainThread() {
return Thread.currentThread() == mainThread;
}

@Override
public Poster createPoster(EventBus eventBus) {
return new AsyncPoster(eventBus, mainExecutor);
}
};
} else {
mainThread = Looper.getMainLooper().getThread();
assertFalse(Looper.getMainLooper().getThread().equals(Thread.currentThread()));
}
eventBus = builder.build();
}

protected void waitForEventCount(int expectedCount, int maxMillis) {
Expand Down Expand Up @@ -104,23 +124,6 @@ protected void trackEvent(Object event) {
eventCount.incrementAndGet();
}

@SuppressLint("HandlerLeak")
class EventPostHandler extends Handler {
public EventPostHandler(Looper looper) {
super(looper);
}

@Override
public void handleMessage(Message msg) {
eventBus.post(msg.obj);
}

void post(Object event) {
sendMessage(obtainMessage(0, event));
}

}

protected void assertEventCount(int expectedEventCount) {
assertEquals(expectedEventCount, eventCount.intValue());
}
Expand All @@ -138,4 +141,7 @@ protected void awaitLatch(CountDownLatch latch, long seconds) {
}
}

public void log(String message) {
eventBus.getLogger().log(Level.FINE, message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +15,25 @@
*/
package org.greenrobot.eventbus;

import android.app.Activity;
import android.support.test.annotation.UiThreadTest;
import android.support.test.rule.UiThreadTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.util.Log;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

/**
* @author Markus Junginger, greenrobot
*/
@RunWith(AndroidJUnit4.class)
public class EventBusBasicTest {
public class EventBusBasicTest extends AbstractEventBusTest {

public static class WithIndex extends EventBusBasicTest {
@Test
public void dummy() {}

}

@Rule
public final UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();

protected EventBus eventBus;
private String lastStringEvent;
private int countStringEvent;
private int countIntEvent;
Expand All @@ -52,28 +42,6 @@ public void dummy() {}
private int countMyEvent;
private int countMyEvent2;

@Before
public void setUp() throws Exception {
eventBus = new EventBus();
}

@Test
@UiThreadTest
public void testRegisterAndPost() {
// Use an activity to test real life performance
TestActivity testActivity = new TestActivity();
String event = "Hello";

long start = System.currentTimeMillis();
eventBus.register(testActivity);
long time = System.currentTimeMillis() - start;
Log.d(EventBus.TAG, "Registered in " + time + "ms");

eventBus.post(event);

assertEquals(event, testActivity.lastStringEvent);
}

@Test
public void testPostWithoutSubscriber() {
eventBus.post("Hello");
Expand All @@ -95,7 +63,7 @@ public void testUnregisterNotLeaking() {
};
eventBus.register(subscriber);
eventBus.unregister(subscriber);
Log.d("Test", "Iteration " + i + " / max heap: " + heapMBytes);
log("Iteration " + i + " / max heap: " + heapMBytes);
}
}

Expand Down Expand Up @@ -142,7 +110,7 @@ public void testPostMultipleTimes() {
}
// Debug.stopMethodTracing();
long time = System.currentTimeMillis() - start;
Log.d(EventBus.TAG, "Posted " + count + " events in " + time + "ms");
log("Posted " + count + " events in " + time + "ms");
assertEquals(count, countMyEvent);
}

Expand Down Expand Up @@ -268,15 +236,6 @@ public void onEvent(MyEventExtended event) {
countMyEventExtended++;
}

public static class TestActivity extends Activity {
public String lastStringEvent;

@Subscribe
public void onEvent(String event) {
lastStringEvent = event;
}
}

public static class CharSequenceSubscriber {
@Subscribe
public void onEvent(CharSequence event) {
Expand Down
Loading