src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
QuestionRepository implements QuestionDataSource { @Override public void addQuestion(Question question) { throw new UnsupportedOperationException("Unsupported operation"); } @Inject QuestionRepository(@Local QuestionDataSource localDataSource,
@Remote QuestionDataSource remoteDataSource); @Override Flowable<List... | @Test(expected = UnsupportedOperationException.class) public void addQuestion_ShouldThrowException() { repository.addQuestion(question1); } |
QuestionLocalDataSource implements QuestionDataSource { @Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { return questionDao.getAllQuestions(); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void ... | @Test public void loadQuestions_ShouldReturnFromDatabase() { List<Question> questions = Arrays.asList(new Question(), new Question()); TestSubscriber<List<Question>> subscriber = new TestSubscriber<>(); given(questionDao.getAllQuestions()).willReturn(Flowable.just(questions)); localDataSource.loadQuestions(false).subsc... |
QuestionLocalDataSource implements QuestionDataSource { @Override public void addQuestion(Question question) { questionDao.insert(question); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); ... | @Test public void addQuestion_ShouldInsertToDatabase() { Question question = new Question(); localDataSource.addQuestion(question); then(questionDao).should().insert(question); } |
QuestionLocalDataSource implements QuestionDataSource { @Override public void clearData() { questionDao.deleteAll(); } @Inject QuestionLocalDataSource(QuestionDao questionDao); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @Override void addQuestion(Question question); @Override void clearData... | @Test public void clearData_ShouldDeleteAllDataInDatabase() { localDataSource.clearData(); then(questionDao).should().deleteAll(); } |
QuestionRemoteDataSource implements QuestionDataSource { @Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { return questionService.loadQuestionsByTag(Config.ANDROID_QUESTION_TAG).map(QuestionResponse::getQuestions); } @Inject QuestionRemoteDataSource(QuestionService questionService); @Overr... | @Test public void loadQuestions_ShouldReturnFromRemoteService() { QuestionResponse questionResponse = new QuestionResponse(); TestSubscriber<List<Question>> subscriber = new TestSubscriber<>(); given(questionService.loadQuestionsByTag(Config.ANDROID_QUESTION_TAG)).willReturn(Flowable.just(questionResponse)); remoteData... |
QuestionRemoteDataSource implements QuestionDataSource { @Override public void addQuestion(Question question) { throw new UnsupportedOperationException("Unsupported operation"); } @Inject QuestionRemoteDataSource(QuestionService questionService); @Override Flowable<List<Question>> loadQuestions(boolean forceRemote); @... | @Test(expected = UnsupportedOperationException.class) public void addQuestion_NoThingToDoWithRemoteService() { Question question = mock(Question.class); remoteDataSource.addQuestion(question); then(questionService).shouldHaveZeroInteractions(); } |
PathUtil { static String getRelativeFileInternal(File canonicalBaseFile, File canonicalFileToRelativize) { ArrayList<String> basePath = getPathComponents(canonicalBaseFile); ArrayList<String> pathToRelativize = getPathComponents(canonicalFileToRelativize); if (!basePath.get(0).equals(pathToRelativize.get(0))) { return ... | @Test public void pathUtilTest1() { File[] roots = File.listRoots(); if (roots.length > 1) { File basePath = new File(roots[0] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt"); File relativePath = new File(roots[1] + "some" + File.separatorChar + "dir" + File.separatorChar + "test.txt"); String ... |
BytecodeAdapterService implements
SourceAdapterService<String, CtMethod, CtField, Annotation> { @Override public IsClass toClass(String binaryName) { int arrayCount = 0; while (binaryName.matches(".*" + X_Util.arrayRegex)) { arrayCount += 1; binaryName = binaryName.replaceFirst(X_Util.arrayRegex, ""); } IsClass cls... | @Test public void testArrayParser() { IsClass clsArray = service.toClass("java.lang.Class[]"); Assert.assertNotNull(clsArray); }
@Test public void testAnnoNoArgs() { IsClass asClass = service.toClass(OuterTestClass.NoTargetAnno.class.getName()); IsAnnotation anno = asClass.getAnnotation(Target.class.getName()); IsAnnot... |
ToStringUserInterface extends AbstractUserInterface implements Appendable { @Override public String toString() { return b.toString(); } @Override int hashCode(); @Override String toString(); @Override boolean equals(Object obj); @Override Appendable append(CharSequence csq); @Override Appendable append(CharSequence cs... | @Test public void testUserToStringNamed() { ToStringUserInterface ui = X_AutoUi.makeUi(MODEL, UserViewNamed.class, ToStringUserInterface.class); Assert.assertEquals("email: email,\nname: name,\nid: id", ui.toString()); }
@Test public void testUserToStringWrapped() { UserInterface<User> ui = X_AutoUi.makeUi(MODEL, UserV... |
JavaLexer { public static <R> int visitAnnotation (final AnnotationVisitor<R> visitor, final R receiver, final CharSequence chars, int pos) { pos = eatWhitespace(chars, pos); if (pos == chars.length()) { return pos; } int start = pos; try { while(chars.charAt(pos) == '@') { pos = eatJavaname(chars, pos + 1); final Stri... | @Test public void testAnnotationLexer() { final short[] success = new short[1]; final String annoBody = "name=\"one \\\"\\\"two\\\"\\\" three\\\\\", " + "{1, 2.0, false}, values={1, \"string\", com.test.Class.class}"; JavaLexer.visitAnnotation(new AnnotationVisitor<Void>(){ @Override public AnnotationMemberVisitor<Void... |
JavaLexer { public static TypeDef extractType(final CharSequence chars, int pos) { int start = pos = eatWhitespace(chars, pos); int lastPeriod = -1; final int max = chars.length()-1; boolean doneParsing = false; final StringBuilder pkg = new StringBuilder(); package_loop: if (Character.isLowerCase(chars.charAt(pos))) {... | @Test public void testTypeLexer() { String type = "java.lang.Class"; TypeData data = JavaLexer.extractType(type, 0); Assert.assertEquals("java.lang", data.pkgName); Assert.assertEquals("Class", data.clsName); Assert.assertEquals("Class", data.simpleName); Assert.assertEquals(type, data.toString()); String generics = "<... |
JavaLexer { public static <R> int visitMethodSignature (final MethodVisitor<R> visitor, final R receiver, final CharSequence chars, int pos) { pos = eatWhitespace(chars, pos); if (pos == chars.length()) { return pos; } pos = visitAnnotation(visitor, receiver, chars, pos); pos = visitModifier(visitor, receiver, chars, p... | @Test public void testMethodLexer() { final String methodGeneric = "<Complex, Generic extends Signature & More<Stuff>>"; final String modifiers = "public static final"; final String returnType = "Type"; final String returnGeneric = "<With<Generics>>"; final String methodName = "methodName"; final String paramGeneric = ... |
LogInjector { public Log defaultLogger() { return (level, debug) -> (level == LogLevel.ERROR ? SYS_ERR : SYS_OUT) .print(level, debug); } Log defaultLogger(); } | @Test public void testDefaultLogging() throws Throwable { final String msg = "Success! " + hashCode(); borrowSout( ()-> LogInjector.DEFAULT.log(LogLevel.INFO, msg) , lines-> Assert.assertEquals("[INFO] " + msg, lines.first()) ); assertTrue("Failed", !failed); Log.defaultLogger().log(LogInjectorTest.class, "Default Logg... |
SlideRenderer { public void renderSlide(DomBuffer into, UiContainerExpr slide) { final DomBuffer out; if ("xapi-slide".equals(into.getTagName())) { out = into; } else { out = into.makeTag("xapi-slide"); } slide.getAttribute("id") .mapNullSafe(UiAttrExpr::getExpression) .mapNullSafe(ASTHelper::extractStringValue) .readI... | @Test public void testAllSlidesCanRender() throws IOException, ParseException { items.forAll(item->{ SlideRenderer renderer = new SlideRenderer(); final DomBuffer into = new DomBuffer() .setNewLine(true) .setTrimWhitespace(false); renderer.renderSlide(into, item.out2()); X_Log.info(X_Source.pathToLogLink(item.out1().ge... |
RangePool { public boolean insert(Coord coord, T value) { ReservedNode<T> newNode = new ReservedNode<>(coord, value); if (highest.getRange().contains(coord)) { if (highest.getRange().getX() == coord.getX()) { highest.attachBelow(newNode); } else { final UnreservedNode<T> newSpace = highest.split(newNode, RangeDirection... | @Test public void testInsertAtEdges() { int cnt = 0; RangePool<Integer> pool = new RangePool<>(); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY)} ); pool.insert(coord(-2, 2), cnt++); assertPoolStructure(pool, new Coord[]{coord(Double.NEGATIVE_INFINITY, -2), coord(2, Doub... |
CacheUtils { public byte[] getBytes(@NonNull String key) { return getBytes(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils... | @Test public void getBytes() throws Exception { Assert.assertEquals(mString, new String(mCacheUtils1.getBytes("bytes1"))); Assert.assertEquals(mString, new String(mCacheUtils1.getBytes("bytes1", null))); Assert.assertNull(mCacheUtils1.getBytes("bytes2", null)); Assert.assertEquals(mString, new String(mCacheUtils2.getBy... |
CacheUtils { public String getString(@NonNull String key) { return getString(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUti... | @Test public void getString() throws Exception { Assert.assertEquals(mString, mCacheUtils1.getString("string1")); Assert.assertEquals(mString, mCacheUtils1.getString("string1", null)); Assert.assertNull(mCacheUtils1.getString("string2", null)); Assert.assertEquals(mString, mCacheUtils2.getString("string2")); Assert.ass... |
CacheUtils { public JSONObject getJSONObject(@NonNull String key) { return getJSONObject(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); sta... | @Test public void getJSONObject() throws Exception { Assert.assertEquals(mJSONObject.toString(), mCacheUtils1.getJSONObject("jsonObject1").toString()); Assert.assertEquals(mJSONObject.toString(), mCacheUtils1.getJSONObject("jsonObject1", null).toString()); Assert.assertNull(mCacheUtils1.getJSONObject("jsonObject2", nul... |
CacheUtils { public JSONArray getJSONArray(@NonNull String key) { return getJSONArray(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static... | @Test public void getJSONArray() throws Exception { Assert.assertEquals(mJSONArray.toString(), mCacheUtils1.getJSONArray("jsonArray1").toString()); Assert.assertEquals(mJSONArray.toString(), mCacheUtils1.getJSONArray("jsonArray1", null).toString()); Assert.assertNull(mCacheUtils1.getJSONArray("jsonArray2", null)); Asse... |
CacheUtils { public Bitmap getBitmap(@NonNull String key) { return getBitmap(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUti... | @Test public void getBitmap() throws Exception { Assert.assertTrue(mCacheUtils1.getString("bitmap1").equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertTrue(mCacheUtils1.getString("bitmap1", null).equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertNull(mCacheUtils... |
CacheUtils { public Drawable getDrawable(@NonNull String key) { return getDrawable(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static Ca... | @Test public void getDrawable() throws Exception { Assert.assertTrue(mCacheUtils1.getString("drawable1").equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertTrue(mCacheUtils1.getString("drawable1", null).equals("Bitmap (100 x 100) compressed as PNG with quality 100")); Assert.assertNull(mCach... |
CacheUtils { public <T> T getParcelable(@NonNull String key, @NonNull Parcelable.Creator<T> creator) { return getParcelable(key, creator, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils ... | @Test public void getParcel() throws Exception { Assert.assertTrue(mCacheUtils1.getParcelable("parcelable1", ParcelableTest.CREATOR).equals(mParcelableTest)); Assert.assertTrue(mCacheUtils1.getParcelable("parcelable1", ParcelableTest.CREATOR, null).equals(mParcelableTest)); Assert.assertNull(mCacheUtils1.getParcelable(... |
CacheUtils { public Object getSerializable(@NonNull String key) { return getSerializable(key, null); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); sta... | @Test public void getSerializable() throws Exception { Assert.assertTrue(mCacheUtils1.getSerializable("serializable1").equals(mSerializableTest)); Assert.assertTrue(mCacheUtils1.getSerializable("serializable1", null).equals(mSerializableTest)); Assert.assertNull(mCacheUtils1.getSerializable("parcelable2", null)); Asser... |
CacheUtils { public long getCacheSize() { return mCacheManager.getCacheSize(); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInst... | @Test public void getCacheSize() throws Exception { Assert.assertEquals(FileUtils.getDirLength(file1), mCacheUtils1.getCacheSize()); Assert.assertEquals(FileUtils.getDirLength(file2), mCacheUtils2.getCacheSize()); } |
CacheUtils { public int getCacheCount() { return mCacheManager.getCacheCount(); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getIns... | @Test public void getCacheCount() throws Exception { Assert.assertEquals(8, mCacheUtils1.getCacheCount()); Assert.assertEquals(8, mCacheUtils2.getCacheCount()); } |
CacheUtils { public boolean remove(@NonNull String key) { return mCacheManager.removeByKey(key); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static ... | @Test public void remove() throws Exception { Assert.assertNotNull(mCacheUtils1.getString("string1")); mCacheUtils1.remove("string1"); Assert.assertNull(mCacheUtils1.getString("string1")); Assert.assertNotNull(mCacheUtils2.getString("string2")); mCacheUtils2.remove("string2"); Assert.assertNull(mCacheUtils2.getString("... |
CacheUtils { public boolean clear() { return mCacheManager.clear(); } private CacheUtils(@NonNull File cacheDir, long maxSize, int maxCount); static CacheUtils getInstance(); static CacheUtils getInstance(String cacheName); static CacheUtils getInstance(long maxSize, int maxCount); static CacheUtils getInstance(String... | @Test public void clear() throws Exception { Assert.assertNotNull(mCacheUtils1.getBytes("bytes1")); Assert.assertNotNull(mCacheUtils1.getString("string1")); Assert.assertNotNull(mCacheUtils1.getJSONObject("jsonObject1")); Assert.assertNotNull(mCacheUtils1.getJSONArray("jsonArray1")); Assert.assertNotNull(mCacheUtils1.g... |
SPUtils { public String getString(@NonNull String key) { return getString(key, ""); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String ke... | @Test public void getString() throws Exception { Assert.assertEquals("stringVal1", spUtils1.getString("stringKey1")); Assert.assertEquals("stringVal", spUtils1.getString("stringKey", "stringVal")); Assert.assertEquals("", spUtils1.getString("stringKey")); Assert.assertEquals("stringVal2", spUtils2.getString("stringKey2... |
SPUtils { public int getInt(@NonNull String key) { return getInt(key, -1); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNu... | @Test public void getInt() throws Exception { Assert.assertEquals(1, spUtils1.getInt("intKey1")); Assert.assertEquals(2048, spUtils1.getInt("intKey", 2048)); Assert.assertEquals(-1, spUtils1.getInt("intKey")); Assert.assertEquals(2, spUtils2.getInt("intKey2")); Assert.assertEquals(2048, spUtils2.getInt("intKey", 2048))... |
SPUtils { public long getLong(@NonNull String key) { return getLong(key, -1L); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @N... | @Test public void getLong() throws Exception { Assert.assertEquals(1L, spUtils1.getLong("longKey1")); Assert.assertEquals(2048L, spUtils1.getLong("longKey", 2048)); Assert.assertEquals(-1L, spUtils1.getLong("longKey")); Assert.assertEquals(2L, spUtils2.getLong("longKey2")); Assert.assertEquals(2048L, spUtils2.getLong("... |
SPUtils { public float getFloat(@NonNull String key) { return getFloat(key, -1f); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key,... | @Test public void getFloat() throws Exception { Assert.assertEquals(1f, spUtils1.getFloat("floatKey1"), 0f); Assert.assertEquals(2048f, spUtils1.getFloat("floatKey", 2048f), 0f); Assert.assertEquals(-1f, spUtils1.getFloat("floatKey"), 0f); Assert.assertEquals(2f, spUtils2.getFloat("floatKey2"), 0f); Assert.assertEquals... |
SPUtils { public boolean getBoolean(@NonNull String key) { return getBoolean(key, false); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull Str... | @Test public void getBoolean() throws Exception { Assert.assertTrue(spUtils1.getBoolean("booleanKey1")); Assert.assertTrue(spUtils1.getBoolean("booleanKey", true)); Assert.assertFalse(spUtils1.getBoolean("booleanKey")); Assert.assertTrue(spUtils2.getBoolean("booleanKey2")); Assert.assertTrue(spUtils2.getBoolean("boolea... |
SPUtils { public Map<String, ?> getAll() { return sp.getAll(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String de... | @Test public void getAll() throws Exception { Map<String, ?> map; System.out.println("sp1 {"); map = spUtils1.getAll(); for (Map.Entry<String, ?> entry : map.entrySet()) { System.out.println(" " + entry.getKey() + ": " + entry.getValue()); } System.out.println("}"); System.out.println("sp2 {"); map = spUtils2.getAll();... |
SPUtils { public void remove(@NonNull String key) { sp.edit().remove(key).apply(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key... | @Test public void testRemove() throws Exception { Assert.assertEquals("stringVal1", spUtils1.getString("stringKey1")); spUtils1.remove("stringKey1"); Assert.assertEquals("", spUtils1.getString("stringKey1")); Assert.assertEquals("stringVal2", spUtils2.getString("stringKey2")); spUtils2.remove("stringKey2"); Assert.asse... |
SPUtils { public boolean contains(@NonNull String key) { return sp.contains(key); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key,... | @Test public void testContains() throws Exception { Assert.assertTrue(spUtils1.contains("stringKey1")); Assert.assertFalse(spUtils1.contains("stringKey")); Assert.assertTrue(spUtils2.contains("stringKey2")); Assert.assertFalse(spUtils2.contains("stringKey")); } |
SPUtils { public void clear() { sp.edit().clear().apply(); } private SPUtils(String spName); static SPUtils getInstance(); static SPUtils getInstance(String spName); void put(@NonNull String key, @NonNull String value); String getString(@NonNull String key); String getString(@NonNull String key, @NonNull String defaul... | @Test public void clear() throws Exception { spUtils1.clear(); Assert.assertEquals("", spUtils1.getString("stringKey1")); Assert.assertEquals(-1, spUtils1.getInt("intKey1")); Assert.assertEquals(-1L, spUtils1.getLong("longKey1")); Assert.assertEquals(-1f, spUtils1.getFloat("floatKey1"), 0f); Assert.assertFalse(spUtils1... |
ProxyConfig { public String getProxyHost() { return proxyHost; } ProxyConfig(PropertyLoader propertyLoader); boolean isProxyRequired(); String getProxyType(); String getProxyHost(); int getProxyPort(); String getProxyAddress(); String getProxyUsername(); String getProxyPassword(); String getNonProxyHosts(); } | @Test public void proxySettingsObtainedInOrder() { Properties properties = givenDefaultProperties(); environmentVariables.set("HTTP_PROXY", "http: ProxyConfig proxyConfig = new ProxyConfig(new DefaultPropertyLoader(properties)); assertThat(proxyConfig.getProxyHost(), is("proxyhost3")); System.setProperty("http.proxyHos... |
ConcordionBrowserFixture extends ConcordionFixture implements BrowserBasedTest { @Override public Browser getBrowser() { return getBrowser(threadBrowserId.get()); } static void setScreenshotTakerClass(Class<? extends ScreenshotTaker> screenshotTaker); @Override Browser getBrowser(); Browser getBrowser(String key); Bro... | @Test public void closesMultipleDriversForSingleBrowserProvider() throws IOException { BrowserProvider mockProvider = mock(BrowserProvider.class); WebDriver mockDriver = mock(WebDriver.class); when(mockProvider.createDriver()).thenReturn(mockDriver); Browser browser1 = test1.getBrowser("A", mockProvider); browser1.getD... |
PageHelper { public <P extends BasePageObject<P>> P newInstance(Class<P> expectedPage, Object... params) { try { if (params.length > 0) { Class<?>[] constructorArguments = new Class<?>[2]; constructorArguments[0] = BrowserBasedTest.class; constructorArguments[1] = Object[].class; return expectedPage.getDeclaredConstruc... | @Test public void canCreateInstanceOfPageObjectUsingBBTOnly() { PageHelper tpo = setUpMocks(); TestPageObject testPageObject = tpo.newInstance(TestPageObject.class); assertNotNull("Should not be null when constructing instance of " + TestPageObject.class.getName(), testPageObject); }
@Test public void canCreateInstance... |
CaselessProperties extends Properties { @Override public synchronized Object put(Object key, Object value) { lookup.put(((String) key), (String) key); return super.put(key, value); } @Override synchronized Object put(Object key, Object value); @Override String getProperty(String key); @Override String getProperty(Stri... | @Test public void propertyKeyOriginalCaseIsAvailalbe() { Properties properties = new CaselessProperties(); properties.put("a.SETTING", "value"); @SuppressWarnings("unchecked") Enumeration<String> en = (Enumeration<String>) properties.propertyNames(); String propName = en.nextElement(); assertThat(propName, is("a.SETTIN... |
DefaultPropertyLoader implements PropertyLoader { @Override public String getProperty(String key) { String value = retrieveProperty(key); if (value.isEmpty()) { throw new IllegalArgumentException(String.format("Unable to find property %s", key)); } return value; } DefaultPropertyLoader(Properties properties); String ge... | @Test public void environmentPropertiesOverrideDefaultProperties() { Properties properties = givenDefaultProperties(); given(properties.getProperty("a.setting")).willReturn("false"); given(properties.getProperty("SIT.a.setting")).willReturn("true"); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); ... |
DefaultPropertyLoader implements PropertyLoader { public String getEnvironment() { return environment; } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String getProperty(String key, String defaultValue); @Override boolean getPropertyAsBoolean(... | @Test public void systemPropertyWillOverrideEnvironment() throws Exception { Properties properties = givenDefaultProperties(); System.setProperty("environment", "SIT"); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); assertThat(loader.getEnvironment(), is("SIT")); } |
DefaultPropertyLoader implements PropertyLoader { @Override public Map<String, String> getPropertiesStartingWith(String keyPrefix) { return getPropertiesStartingWith(keyPrefix, false); } DefaultPropertyLoader(Properties properties); String getEnvironment(); @Override String getProperty(String key); @Override String get... | @Test public void canSearchForPopertiesWithPrefixMatchingCase() throws IOException { Properties properties = givenDefaultSearchProperties(); DefaultPropertyLoader loader = new DefaultPropertyLoader(properties); Map<String, String> found = loader.getPropertiesStartingWith("a.setting."); assertThat(found.values().size(),... |
DefaultPropertiesLoader implements PropertiesLoader { @Override public Properties getProperties() { return properties; } protected DefaultPropertiesLoader(String properties, String userProperties); private DefaultPropertiesLoader(); static DefaultPropertiesLoader getInstance(); @Override Properties getProperties(); ... | @Test public void userPropertiesOverrideConfigProperties() { String defaultProperties = "a.setting=false"; String userProperties = "a.setting=true"; Properties properties = new DefaultPropertiesLoader(defaultProperties, "").getProperties(); assertThat(properties.getProperty("a.setting"), is("false")); properties = new ... |
ConcordionBase implements ResourceRegistry { @Override public boolean isRegistered(Closeable resource, ResourceScope scope) { return getResourcePairFromScope(resource, scope).isPresent(); } @Override void registerCloseableResource(Closeable resource, ResourceScope scope); @Override void registerCloseableResource(Close... | @Test public void isRegisteredReturnsFalseIfNotRegistered() { assertFalse(test1.isRegistered(resource0, ResourceScope.SPECIFICATION)); } |
PrometheusMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { @Override public void reportSpan(SpanData spanData) { String[] labelValues = getLabelValues(spanData); if (labelValues != null) { this.histogram.labels(labelValues).observe(spanData.getDuration() / (double)1000000); } } private Prom... | @Test public void testReportSpan() { PrometheusMetricsReporter reporter = PrometheusMetricsReporter.newMetricsReporter() .withCollectorRegistry(collectorRegistry) .withConstLabel("span.kind", Tags.SPAN_KIND_CLIENT) .build(); Map<String,Object> spanTags = new HashMap<String,Object>(); spanTags.put(Tags.SPAN_KIND.getKey(... |
Metrics { public static Tracer decorate(Tracer tracer, MetricsReporter reporter) { return decorate(tracer, Collections.singleton(reporter)); } static Tracer decorate(Tracer tracer, MetricsReporter reporter); static Tracer decorate(Tracer tracer, Set<MetricsReporter> reporters); } | @Test public void testAsChildOf() { MetricsReporter reporter = Mockito.mock(MetricsReporter.class); MockTracer tracer = new MockTracer(); Tracer metricsTracer = Metrics.decorate(tracer, reporter); Scope parentSpan = metricsTracer.buildSpan("parent") .withTag("spanName","parent") .startActive(true); parentSpan.span().se... |
MicrometerMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { @Override public void reportSpan(SpanData spanData) { boolean skip = Arrays.stream(this.metricLabels).anyMatch(m -> m.value(spanData) == null); if (skip) { return; } List<Tag> tags = Arrays.stream(this.metricLabels) .map(m -> new Imm... | @Test public void testReportSpan() { SpanData spanData = defaultMockSpanData(); when(spanData.getTags()).thenReturn(Collections.singletonMap(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT)); MicrometerMetricsReporter reporter = MicrometerMetricsReporter.newMetricsReporter() .withConstLabel("span.kind", Tags.SPAN_KIND_C... |
PrometheusMetricsReporter extends AbstractMetricsReporter implements MetricsReporter { protected static String convertLabel(String label) { StringBuilder builder = new StringBuilder(label); for (int i=0; i < builder.length(); i++) { char ch = builder.charAt(i); if (!(ch == '_' || ch == ':' || Character.isLetter(ch) || ... | @Test public void testConvertLabel() { assertEquals("Hello9", PrometheusMetricsReporter.convertLabel("Hello9")); assertEquals("Hello_there", PrometheusMetricsReporter.convertLabel("Hello there")); assertEquals("_tag1", PrometheusMetricsReporter.convertLabel("1tag1")); assertEquals("tag_:_", PrometheusMetricsReporter.co... |
TagMetricLabel implements MetricLabel { @Override public Object value(SpanData spanData) { Object ret = spanData.getTags().get(name()); return ret == null ? defaultValue : ret; } TagMetricLabel(String name, Object defaultValue); @Override String name(); @Override Object defaultValue(); @Override Object value(SpanData s... | @Test public void testLabelFromTagWithValue() { MetricLabel label = new TagMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); Map<String,Object> tags = new HashMap<String,Object>(); tags.put(TEST_LABEL, "TagValue"); SpanData spanData = mock(SpanData.class); when(spanData.getTags()).thenReturn(tags); assertEquals("TagValue", ... |
BaggageMetricLabel implements MetricLabel { @Override public Object value(SpanData spanData) { Object ret = spanData.getBaggageItem(name()); return ret == null ? defaultValue : ret; } BaggageMetricLabel(String name, Object defaultValue); @Override String name(); @Override Object defaultValue(); @Override Object value(S... | @Test public void testLabelFromBaggage() { MetricLabel label = new BaggageMetricLabel(TEST_LABEL, TEST_LABEL_DEFAULT); SpanData spanData = mock(SpanData.class); when(spanData.getBaggageItem(anyString())).thenReturn("BaggageValue"); assertEquals("BaggageValue", label.value(spanData)); verify(spanData, times(1)).getBagga... |
AbstractMetricsReporter implements MetricsReporter { protected String[] getLabelValues(SpanData spanData) { String[] values = new String[metricLabels.length]; for (int i=0; i < values.length; i++) { Object value = metricLabels[i].value(spanData); if (value == null) { return null; } values[i] = value.toString(); } retur... | @Test public void testWithSpecifiedTagValues() { AbstractMetricsReporter reporter = new AbstractMetricsReporter( Collections.<MetricLabel>emptyList()) { @Override public void reportSpan(SpanData spanData) { } }; Map<String,Object> spanTags = new HashMap<String,Object>(); spanTags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_... |
NumberPadTimePickerPresenter implements INumberPadTimePicker.Presenter,
DigitwiseTimeModel.OnInputChangeListener { @Override public void presentState(@NonNull INumberPadTimePicker.State state) { initialize(state); if (!mIs24HourMode) { mView.setAmPmDisplayIndex(mLocaleModel.isAmPmWrittenBeforeTime() ? 0 : 1); f... | @Test public void verifyViewEnabledStatesForEmptyState() { createNewViewAndPresenter(MODE_12HR); mPresenters[MODE_12HR].presentState(NumberPadTimePickerState.EMPTY); verifyInitialization(MODE_12HR); verify(mViews[MODE_12HR]).setOkButtonEnabled(false); createNewViewAndPresenter(MODE_24HR); mPresenters[MODE_24HR].present... |
NumberPadTimePickerPresenter implements INumberPadTimePicker.Presenter,
DigitwiseTimeModel.OnInputChangeListener { @Override public void onAltKeyClick(CharSequence altKeyText) { final String altKeyString = altKeyText.toString(); final int[] altDigits = mTextModel.altDigits(altKeyString); if (count() <= 2) { ins... | @Test public void mode12Hr_VerifyOnTimeSetCallback() { for (int time = 100; time <= 1259; time++) { if (time % 100 > 59) { System.out.println("Skipping invalid time " + time); continue; } System.out.println("Testing time " + time); for (int amOrPm = 0; amOrPm < 2; amOrPm++) { createNewViewAndPresenter(MODE_12HR); if (t... |
InsertOrReplaceProxy implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (method.getName().equals("toString") && args.length == 0) { String sql = toString((String) proxy.invoke(realInsert, args)); return sql; } return proxy.... | @Test public void intercept() throws Exception { String sql = "INSERT INTO person (id, name) VALUES (1, 'KK')"; CCJSqlParserManager pm = new CCJSqlParserManager(); Insert insert = (Insert) pm.parse(new StringReader(sql)); Insert insertProxy = new InsertOrReplaceProxy().getInstance(Insert.class, insert); Table table = i... |
ShadowResources { public String getString(@StringRes int id) throws NotFoundException { return getText(id).toString(); } ShadowResources(); String getString(@StringRes int id); @NonNull String[] getStringArray(@ArrayRes int id); @NonNull int[] getIntArray(@ArrayRes int id); String getPackageName(); } | @Test public void getString() throws Exception { Assert.assertEquals("KBUnitTest", resources.getString(R.string.test_string)); } |
ShadowResources { @NonNull public String[] getStringArray(@ArrayRes int id) throws NotFoundException { Map<Integer, String> idNameMap = getArrayIdTable(); Map<String, List<String>> stringArrayMap = getResourceStringArrayMap(); if (idNameMap.containsKey(id)) { String name = idNameMap.get(id); if (stringArrayMap.contains... | @Test public void getStringArray() throws Exception { String[] array = resources.getStringArray(R.array.arrayName); Assert.assertEquals("item0", array[0]); Assert.assertEquals("item1", array[1]); } |
ShadowResources { @NonNull public int[] getIntArray(@ArrayRes int id) throws NotFoundException { Map<Integer, String> idNameMap = getArrayIdTable(); Map<String, List<Integer>> intArrayMap = getResourceIntArrayMap(); if (idNameMap.containsKey(id)) { String name = idNameMap.get(id); if (intArrayMap.containsKey(name)) { L... | @Test public void getIntArray() { int[] intArray = resources.getIntArray(R.array.intArray); Assert.assertEquals(0, intArray[0]); Assert.assertEquals(1, intArray[1]); int[] intArrayNoItem = resources.getIntArray(R.array.intArrayNoItem); Assert.assertEquals(0, intArrayNoItem.length); } |
ShadowResources { public String getPackageName() { if (!TextUtils.isEmpty(mPackageName)) { return mPackageName; } String manifestPath = "build/intermediates/bundles/debug/AndroidManifest.xml"; if (!new File(manifestPath).exists()) { manifestPath = "build/intermediates/bundles/release/AndroidManifest.xml"; } FileReader ... | @Test public void getPackageName() throws Exception { Assert.assertEquals("net.kb.test.library", resources.getPackageName()); } |
KbSqlParserManager { public Statement parse(String sql) throws JSQLParserException { sql = sql.trim(); boolean isInsertOrReplace = false; if (sql.toUpperCase().startsWith("INSERT OR REPLACE")) { isInsertOrReplace = true; String[] sqlParts = new String[2]; sqlParts[0] = sql.substring(0, "INSERT OR REPLACE".length()); sq... | @Test public void parse() throws Exception { String sql = "INSERT or replace INTO person (id, name) VALUES (?, ?)"; Insert insert = (Insert) new KbSqlParserManager().parse(sql); Assert.assertEquals("INSERT OR REPLACE INTO person (id, name) VALUES (?, ?)", insert.toString()); } |
ShadowCursor implements Cursor { @Override public String getString(int columnIndex) { Object obj = getObject(columnIndex); return obj == null ? null : obj.toString(); } ShadowCursor(List<String> columns, List<List<Object>> datas); @Override int getCount(); @Override int getPosition(); @Override boolean move(int offset)... | @Test public void getString() throws Exception { List<String> columns = Arrays.asList("first", "second", "third"); List<Object> datas = Arrays.asList("test", null, new Object()); ShadowCursor cursor = new ShadowCursor(columns, Arrays.asList(datas)); cursor.moveToNext(); Assert.assertEquals("test", cursor.getString(0));... |
KbSqlParser { public static String bindArgs(String sql, @Nullable Object[] bindArgs) { if (bindArgs == null || bindArgs.length == 0 || sql.startsWith("PRAGMA")) { return sql; } bindArgs = replaceBoolean(bindArgs); try { KbSqlParserManager pm = new KbSqlParserManager(); Statement statement = pm.parse(sql); Set<Expressio... | @Test public void bindSelectArgs() throws Exception { Object[] args = new Object[]{1, 10, 20, "test"}; String sql = "select * from person where id=? and (uid BETWEEN ? and ?) and test LIKE ? order by id"; String boundSql = KbSqlParser.bindArgs(sql, args); System.out.println(boundSql); Assert.assertEquals("SELECT * FROM... |
KbSqlParser { protected static int getBindArgsCount(String sql) { Set<Expression> expressionSet = findBindArgsExpressions(sql); int count = 0; for (Expression expression : expressionSet) { count += getBindArgsCount(expression); } return count; } static String bindArgs(String sql, @Nullable Object[] bindArgs); static O... | @Test public void getBindArgsCount() throws Exception { String sql0 = "select * from person where id=? and (uid BETWEEN ? and ?) and test LIKE ? order by id"; String sql1 = "INSERT INTO person (id, name) VALUES (?, ?)"; String sql2 = "DELETE FROM person WHERE id in (?,?)"; String sql3 = "UPDATE person SET name = ? WHER... |
KbSqlParser { protected static Set<Expression> findBindArgsExpressions(String sql) { if (sql == null || sql.startsWith("PRAGMA") || !sql.contains("?")) { return new LinkedHashSet<>(); } KbSqlParserManager pm = new KbSqlParserManager(); try { Statement statement = pm.parse(sql); Set<Expression> expressionSet = findBindA... | @Test public void findJdbcParamExpressions() throws Exception { String sql = "DELETE FROM person WHERE id = ?"; Set<Expression> expressionSet = KbSqlParser.findBindArgsExpressions(sql); System.out.println(); } |
ShadowContext implements Shadow { public static void deleteAllTempDir() { FileUtils.deletePath(DB_PATH); FileUtils.deletePath(DATA_DIR); FileUtils.deletePath(EXT_DIR); } ShadowContext(Resources resources); @NonNull final String getString(@StringRes int resId); Resources getResources(); SharedPreferences getSharedPrefer... | @Test public void deleteAllTempDir() throws Exception { ShadowContext.deleteAllTempDir(); } |
NoOpWorkflowImpl implements NoOpWorkflow { @Override public void run() { System.out.println("Run called"); run(0); } @Override void run(); } | @Test public void testRun() { context.checking( new Expectations() { { exactly(3).of(control).createDatabaseName("test"); will(returnValue("bbb")); } }); new NoOpWorkflowClientFactoryImpl().getClient("test").run(); } |
JobWorkflowImpl implements JobWorkflow { @Override public void executeCommand(final RunJobRequest request) { this.request = request; this.workflowId = contextProvider .getDecisionContext() .getWorkflowContext() .getWorkflowExecution() .getWorkflowId(); final String masterRoleName = "dm-master-role-" + workflowId; final... | @Test public void testRun() { final Identity identity = Identity.of("a", "b", "c"); WorkerOptions workerOptions = new WorkerOptions(); RunJobRequest request = new RunJobRequest(); request.setWorkerOptions(workerOptions); final Job job = new CommandLineJob(); request.setIdentity(identity); request.setJob(job); final Cre... |
UriBuilderImpl extends UriBuilder { @Override public UriBuilder replaceQueryParam(String name, Object... values) { checkSsp(); if (queryParams == null) { queryParams = UriComponent.decodeQuery(query.toString(), false); query.setLength(0); } name = encode(name, UriComponent.Type.QUERY_PARAM); queryParams.remove(name); i... | @Test public void testReplaceQueryParam() { URI uri = new UriBuilderImpl().path("http: assertEquals("http: } |
DemoAO { public void hello(String name) throws FileNotFoundException { System.out.println(demoService.sayHello(name)); } void hello(String name); } | @Test public void testHello() throws FileNotFoundException { demoAO.hello("抠逼阵儿"); } |
StackTraceHelper { public static StackFrame[] convertJsStackTrace(@Nullable ReadableArray stack) { int size = stack != null ? stack.size() : 0; StackFrame[] result = new StackFrame[size]; for (int i = 0; i < size; i++) { ReadableMap frame = stack.getMap(i); String methodName = frame.getString("methodName"); String file... | @Test public void testParseStackFrameWithMethod() { final StackFrame frame = StackTraceHelper.convertJsStackTrace( "render@Test.bundle:1:2000")[0]; assertThat(frame.getMethod()).isEqualTo("render"); assertThat(frame.getFileName()).isEqualTo("Test.bundle"); assertThat(frame.getLine()).isEqualTo(1); assertThat(frame.getC... |
MultipartStreamReader { public boolean readAllParts(ChunkCallback callback) throws IOException { ByteString delimiter = ByteString.encodeUtf8(CRLF + "--" + mBoundary + CRLF); ByteString closeDelimiter = ByteString.encodeUtf8(CRLF + "--" + mBoundary + "--" + CRLF); int bufferLen = 4 * 1024; long chunkStart = 0; long byt... | @Test public void testSimpleCase() throws IOException { ByteString response = ByteString.encodeUtf8( "preable, should be ignored\r\n" + "--sample_boundary\r\n" + "Content-Type: application/json; charset=utf-8\r\n" + "Content-Length: 2\r\n\r\n" + "{}\r\n" + "--sample_boundary--\r\n" + "epilogue, should be ignored"); Buf... |
ClipboardModule extends ContextBaseJavaModule { @SuppressLint("DeprecatedMethod") @ReactMethod public void setString(String text) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ClipData clipdata = ClipData.newPlainText(null, text); ClipboardManager clipboard = getClipboardService(); clipboard.setPrimar... | @Test public void testSetString() { mClipboardModule.setString(TEST_CONTENT); assertTrue(mClipboardManager.getText().equals(TEST_CONTENT)); mClipboardModule.setString(null); assertFalse(mClipboardManager.hasText()); mClipboardModule.setString(""); assertFalse(mClipboardManager.hasText()); mClipboardModule.setString(" "... |
NetworkingModule extends ReactContextBaseJavaModule { @ReactMethod public void sendRequest( String method, String url, final int requestId, ReadableArray headers, ReadableMap data, final String responseType, final boolean useIncrementalUpdates, int timeout, boolean withCredentials) { Request.Builder requestBuilder = ne... | @Test public void testGetWithoutHeaders() throws Exception { OkHttpClient httpClient = mock(OkHttpClient.class); when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Call callMock = mock(Call.class); return callMock... |
UIManagerModuleConstants { public static Map<String, Object> getConstants() { HashMap<String, Object> constants = new HashMap<String, Object>(); constants.put( "UIView", MapBuilder.of( "ContentMode", MapBuilder.of( "ScaleAspectFit", ImageView.ScaleType.FIT_CENTER.ordinal(), "ScaleAspectFill", ImageView.ScaleType.CENTER... | @Test public void testNoCustomConstants() { List<ViewManager> viewManagers = Arrays.asList(mock(ViewManager.class)); UIManagerModule uiManagerModule = new UIManagerModule( mReactContext, viewManagers, mUIImplementationProvider, false); Map<String, Object> constants = uiManagerModule.getConstants(); assertThat(constants... |
UIManagerModule extends ReactContextBaseJavaModule implements
OnBatchCompleteListener, LifecycleEventListener, PerformanceCounter { @ReactMethod public void replaceExistingNonRootView(int oldTag, int newTag) { mUIImplementation.replaceExistingNonRootView(oldTag, newTag); } UIManagerModule(
ReactApplicationCon... | @Test public void testReplaceExistingNonRootView() { UIManagerModule uiManager = getUIManagerModule(); TestMoveDeleteHierarchy hierarchy = createMoveDeleteHierarchy(uiManager); int newViewTag = 1234; uiManager.createView( newViewTag, ReactViewManager.REACT_CLASS, hierarchy.rootView, JavaOnlyMap.of("backgroundColor", Co... |
UIManagerModule extends ReactContextBaseJavaModule implements
OnBatchCompleteListener, LifecycleEventListener, PerformanceCounter { @ReactMethod public void removeSubviewsFromContainerWithID(int containerTag) { mUIImplementation.removeSubviewsFromContainerWithID(containerTag); } UIManagerModule(
ReactApplicat... | @Test public void testRemoveSubviewsFromContainerWithID() { UIManagerModule uiManager = getUIManagerModule(); ReactRootView rootView = new ReactRootView(RuntimeEnvironment.application.getApplicationContext()); int rootTag = uiManager.addMeasuredRootView(rootView); final int containerTag = rootTag + 1; final int contain... |
CompositeReactPackage extends ReactInstancePackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { final Map<String, NativeModule> moduleMap = new HashMap<>(); for (ReactPackage reactPackage: mChildReactPackages) { for (NativeModule nativeModule: reactPackage.createNati... | @Test public void testThatCreateNativeModulesIsCalledOnAllPackages() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2, packageNo3); composite.createNativeModules(reactContext); verify(packageNo1).createNativeModules(reactContext); verify(packageNo2).createNativeModules(reactContext);... |
CompositeReactPackage extends ReactInstancePackage { @Override public List<Class<? extends JavaScriptModule>> createJSModules() { final Set<Class<? extends JavaScriptModule>> moduleSet = new HashSet<>(); for (ReactPackage reactPackage: mChildReactPackages) { for (Class<? extends JavaScriptModule> jsModule: reactPackage... | @Test public void testThatCreateJSModulesIsCalledOnAllPackages() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2, packageNo3); composite.createJSModules(); verify(packageNo1).createJSModules(); verify(packageNo2).createJSModules(); verify(packageNo3).createJSModules(); }
@Test publi... |
CompositeReactPackage extends ReactInstancePackage { @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { final Map<String, ViewManager> viewManagerMap = new HashMap<>(); for (ReactPackage reactPackage: mChildReactPackages) { for (ViewManager viewManager: reactPackage.createView... | @Test public void testThatCreateViewManagersIsCalledOnAllPackages() { CompositeReactPackage composite = new CompositeReactPackage(packageNo1, packageNo2, packageNo3); composite.createViewManagers(reactContext); verify(packageNo1).createViewManagers(reactContext); verify(packageNo2).createViewManagers(reactContext); ver... |
JSPackagerClient implements ReconnectingWebSocket.MessageCallback { @Override public void onMessage(ResponseBody response) { if (response.contentType() != WebSocket.TEXT) { FLog.w( TAG, "Websocket received message with payload of unexpected type " + response.contentType()); return; } try { JSONObject message = new JSON... | @Test public void test_onMessage_ShouldTriggerNotification() throws IOException { RequestHandler handler = mock(RequestHandler.class); final JSPackagerClient client = new JSPackagerClient("test_client", mSettings, createRH("methodValue", handler)); client.onMessage( ResponseBody.create( WebSocket.TEXT, "{\"version\": 2... |
PdfParser { static List<String> extractTextLinesFromPdf(InputStream pdfStream) { PdfReader pdfReader = null; try { pdfReader = new PdfReader(pdfStream); List<String> textLines = new ArrayList<>(); for (int page = 1; page <= pdfReader.getNumberOfPages(); page++) { String textFromPage = PdfTextExtractor.getTextFromPage(p... | @Test public void extractTextLinesFromPdf_ffsClaims() throws IOException { try (InputStream codebookPdfStream = SupportedCodebook.FFS_CLAIMS.getCodebookPdfInputStream();) { List<String> codebookTextLines = PdfParser.extractTextLinesFromPdf(codebookPdfStream); Assert.assertNotNull(codebookTextLines); Assert.assertTrue(c... |
PdfParser { static List<List<String>> findVariableSections(List<String> codebookTextLines) { int firstVariableLine = findFirstVariableLine(codebookTextLines); int lastVariableLine = findLastVariableLine(codebookTextLines); List<List<String>> variableSectionLineGroups = new ArrayList<>(); List<String> sectionBuilder = n... | @Test public void findVariableSections() throws IOException { for (SupportedCodebook supportedCodebook : SupportedCodebook.values()) { try (InputStream codebookPdfStream = supportedCodebook.getCodebookPdfInputStream();) { LOGGER.info("Looking for sections in codebook: {}", supportedCodebook.name()); List<String> codebo... |
PdfParser { public static Codebook parseCodebookPdf(SupportedCodebook codebookSource) { try (InputStream codebookPdfStream = codebookSource.getCodebookPdfInputStream();) { List<String> codebookTextLines = extractTextLinesFromPdf(codebookPdfStream); Codebook codebook = new Codebook(codebookSource); List<List<String>> va... | @Test public void parseCodebookPdf() throws IOException { for (SupportedCodebook supportedCodebook : SupportedCodebook.values()) { LOGGER.info("Looking for sections in codebook: {}", supportedCodebook.name()); Codebook codebook = PdfParser.parseCodebookPdf(supportedCodebook); Assert.assertNotNull(codebook); Assert.asse... |
PdfParser { static String parseLabel(List<String> variableSection) { List<String> fieldText = extractFieldContent(variableSection, FIELD_NAME_LABEL, FIELD_NAME_LABEL_ALT1); List<String> fieldParagraphs = extractParagraphs(fieldText); if (fieldParagraphs.size() != 1) throw new IllegalStateException( String.format("Inval... | @Test public void parseLabel_multiline() { String[] variableSection = new String[] { "CLM_NEXT_GNRTN_ACO_IND_CD1", "LABEL: Claim Next Generation (NG) Accountable Care Organization (ACO) Indicator Code –", "Population-Based Payment (PBP)", "DESCRIPTION: The field identifies the claims that qualify for specific claims pr... |
DatabaseSchemaManager { public static void createOrUpdateSchema(DataSource dataSource) { LOGGER.info("Schema create/upgrade: running..."); Flyway flyway = new Flyway(); flyway.setCleanDisabled(true); flyway.setDataSource(dataSource); flyway.setPlaceholders(createScriptPlaceholdersMap(dataSource)); flyway.migrate(); LOG... | @Test public void createOrUpdateSchemaOnHsql() { JDBCDataSource hsqlDataSource = new JDBCDataSource(); hsqlDataSource.setUrl("jdbc:hsqldb:mem:test"); DatabaseSchemaManager.createOrUpdateSchema(hsqlDataSource); } |
CommandContext { public boolean hasFlag(char ch) { return booleanFlags.contains(ch) || valueFlags.containsKey(ch); } CommandContext(String args); CommandContext(String[] args); CommandContext(String args, Set<Character> valueFlags); CommandContext(String args, Set<Character> valueFlags, boolean allowHangingFlag); C... | @Test public void testFlagsAnywhere() { try { CommandContext context = new CommandContext("r hello -f"); assertTrue(context.hasFlag('f')); CommandContext context2 = new CommandContext("r hello -f world"); assertTrue(context2.hasFlag('f')); } catch (CommandException e) { log.warn("Error", e); fail("Error creating Comman... |
Location { public Location setY(double y) { return new Location(extent, position.withY(y), yaw, pitch); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Exte... | @Test public void testSetY() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setY(TEST_VALUE); assertEquals(0, location1.getY(), EPSILON); assertEquals(0, location2.getX(), EPSILON); assertEquals(TEST_VALUE, location2.getY(), EPS... |
Location { public double getZ() { return position.getZ(); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, double y, double z, float... | @Test public void testGetZ() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getZ(), EPSILON); } |
Location { public int getBlockZ() { return (int) Math.floor(position.getZ()); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Extent extent, double x, doubl... | @Test public void testGetBlockZ() throws Exception { World world = mock(World.class); Location location = new Location(world, Vector3.at(0, 0, TEST_VALUE)); assertEquals(TEST_VALUE, location.getBlockZ()); } |
Location { public Location setZ(double z) { return new Location(extent, position.withZ(z), yaw, pitch); } Location(Extent extent); Location(Extent extent, double x, double y, double z); Location(Extent extent, Vector3 position); Location(Extent extent, double x, double y, double z, Vector3 direction); Location(Exte... | @Test public void testSetZ() throws Exception { World world = mock(World.class); Location location1 = new Location(world, Vector3.ZERO); Location location2 = location1.setZ(TEST_VALUE); assertEquals(0, location1.getZ(), EPSILON); assertEquals(0, location2.getX(), EPSILON); assertEquals(0, location2.getY(), EPSILON); as... |
MorePaths { public static Stream<Path> iterPaths(Path path) { Deque<Path> parents = new ArrayDeque<>(path.getNameCount()); Path next = path; while (next != null) { parents.addFirst(next); next = next.getParent(); } return ImmutableList.copyOf(parents).stream(); } private MorePaths(); static Comparator<Path> oldestFirs... | @Test void testRelative() { assertEquals( paths("a", "a/b", "a/b/c"), MorePaths.iterPaths(Paths.get("a/b/c")).collect(toList()) ); }
@Test void testAbsolute() { assertEquals( paths("/", "/a", "/a/b", "/a/b/c"), MorePaths.iterPaths(Paths.get("/a/b/c")).collect(toList()) ); }
@Test void testEmpty() { assertEquals( paths(... |
EventBus { public void register(Object object) { subscribeAll(finder.findAllSubscribers(object)); } void subscribe(Class<?> clazz, EventHandler handler); void subscribeAll(Multimap<Class<?>, EventHandler> handlers); void unsubscribe(Class<?> clazz, EventHandler handler); void unsubscribeAll(Multimap<Class<?>, EventHan... | @Test public void testRegister() { Subscriber subscriber = new Subscriber(); eventBus.register(subscriber); Event e1 = new Event(); eventBus.post(e1); Event e2 = new Event(); eventBus.post(e2); assertEquals(asList(e1, e2), subscriber.events); } |
EventBus { public void unregister(Object object) { unsubscribeAll(finder.findAllSubscribers(object)); } void subscribe(Class<?> clazz, EventHandler handler); void subscribeAll(Multimap<Class<?>, EventHandler> handlers); void unsubscribe(Class<?> clazz, EventHandler handler); void unsubscribeAll(Multimap<Class<?>, Even... | @Test public void testUnregister() { Subscriber subscriber = new Subscriber(); eventBus.register(subscriber); Event e1 = new Event(); eventBus.post(e1); eventBus.unregister(subscriber); Event e2 = new Event(); eventBus.post(e2); assertEquals(singletonList(e1), subscriber.events); } |
CommandContext { public String[] getSlice(int index) { String[] slice = new String[originalArgs.length - index]; System.arraycopy(originalArgs, index, slice, 0, originalArgs.length - index); return slice; } CommandContext(String args); CommandContext(String[] args); CommandContext(String args, Set<Character> valueFla... | @Test public void testSlice() { try { CommandContext context = new CommandContext("foo bar baz"); assertArrayEquals(new String[] { "foo", "bar", "baz" }, context.getSlice(0)); } catch (CommandException e) { log.warn("Error", e); fail("Error creating CommandContext"); } } |
BlockMap extends AbstractMap<BlockVector3, V> { @Override public V get(Object key) { BlockVector3 vec = (BlockVector3) key; Int2ObjectMap<V> activeMap = maps.get(toGroupKey(vec)); if (activeMap == null) { return null; } return activeMap.get(toInnerKey(vec)); } private BlockMap(Supplier<Int2ObjectMap<V>> subMapSupplier... | @Test @DisplayName("throws ClassCastException if invalid argument to get") void throwsFromGetOnInvalidArgument() { assertThrows(ClassCastException.class, () -> map.get("")); } |
Expression { public double evaluate(double... values) throws EvaluationException { return evaluate(values, WorldEdit.getInstance().getConfiguration().calculationTimeout); } private Expression(String expression, String... variableNames); static Expression compile(String expression, String... variableNames); double eval... | @TestFactory public Stream<DynamicNode> testEvaluate() throws ExpressionException { List<ExpressionTestCase> testCases = ImmutableList.of( testCase("1 - 2 + 3", 2), testCase("2 + +4", 6), testCase("2 - -4", 6), testCase("2 * -4", -8), testCase("sin(5)", sin(5)), testCase("atan2(3, 4)", atan2(3, 4)), testCase("min(1, 2)... |
Expression { public static Expression compile(String expression, String... variableNames) throws ExpressionException { return new Expression(expression, variableNames); } private Expression(String expression, String... variableNames); static Expression compile(String expression, String... variableNames); double evalua... | @Test public void testErrors() { { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("#")); assertEquals(0, e.getPosition(), "Error position"); } { ExpressionException e = assertThrows(ExpressionException.class, () -> compile("x")); assertEquals(0, e.getPosition(), "Error position"); } { Exp... |
BlockTransformExtent extends AbstractDelegateExtent { public static <B extends BlockStateHolder<B>> B transform(B block, Transform transform) { checkNotNull(block); checkNotNull(transform); B result = block; List<? extends Property<?>> properties = block.getBlockType().getProperties(); for (Property<?> property : prope... | @Test public void testTransform() { for (BlockType type : BlockType.REGISTRY.values()) { if (ignored.contains(type)) { continue; } BlockState base = type.getDefaultState(); BlockState rotated = base; for (int i = 1; i < 4; i++) { rotated = BlockTransformExtent.transform(base, ROTATE_90); } assertEquals(base, rotated); ... |
FileSystemSnapshotDatabase implements SnapshotDatabase { public Path getRoot() { return root; } FileSystemSnapshotDatabase(Path root, ArchiveNioSupport archiveNioSupport); static ZonedDateTime tryParseDate(Path path); static URI createUri(String name); static FileSystemSnapshotDatabase maybeCreate(
Path root,
... | @DisplayName("makes the root directory absolute if needed") @Test void rootIsAbsoluteDir() throws IOException { Path root = newTempDb(); try { Path relative = root.getFileSystem().getPath("relative"); Files.createDirectories(relative); FileSystemSnapshotDatabase db2 = new FileSystemSnapshotDatabase(relative, ArchiveNio... |
DinnerPermsResolver implements PermissionsResolver { @Override @SuppressWarnings("deprecation") public boolean hasPermission(String name, String permission) { return hasPermission(server.getOfflinePlayer(name), permission); } DinnerPermsResolver(Server server); static PermissionsResolver factory(Server server, YAMLProc... | @Test public void testBasicResolving() { final TestOfflinePermissible permissible = new TestOfflinePermissible(); permissible.setPermission("testperm.test1", true); assertTrue(resolver.hasPermission(permissible, "testperm.test1")); assertFalse(resolver.hasPermission(permissible, "testperm.somethingelse")); assertFalse(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.