src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
HueServiceImpl implements HueService { @Override public List<FoundBridgeDTO> findAllBridges() { return new ArrayList<>(Arrays.asList(new TestRestTemplate().getForObject("https: } @Autowired HueServiceImpl(BridgeRepository bridgeRepository); @PostConstruct void init(); @PreDestroy void destroy(); void initListener(); @... | @Test public void testFindAllBridgesIsModifiable() { List<FoundBridgeDTO> allBridges = hueService.findAllBridges(); allBridges.add(new FoundBridgeDTO()); allBridges.add(new FoundBridgeDTO()); allBridges.remove(0); } |
JobListener { boolean isTurnOffTime(LampDTO lamp, DateTime now) { int workingStart = new DateTime(lamp.getWorkingStart()).getMillisOfDay(); int workingEnd = new DateTime(lamp.getWorkingEnd()).getMillisOfDay(); int n = now.getMillisOfDay(); return (workingStart > n) || (n > workingEnd); } @Autowired JobListener(Jenkins... | @Test public void testIsTurnOffTime() { LampDTO lampDTO = new LampDTO(); lampDTO.setWorkingStart(DateTime.now().withMillisOfDay(0).withHourOfDay(7).toDate()); lampDTO.setWorkingEnd(DateTime.now().withMillisOfDay(0).withHourOfDay(19).toDate()); DateTime beerOClock = DateTime.now().withHourOfDay(20); assertTrue(jobListen... |
JobListener { BuildState extractBuildState(JenkinsBuildDTO build) { if (build == null) { throw new IllegalArgumentException("build ist null!"); } else { if (build.isBuilding()) { return BuildState.BUILDING; } else { return BuildState.valueOf(build.getResult()); } } } @Autowired JobListener(JenkinsService jenkinsServic... | @Test public void testExtractBuildState() { JenkinsBuildDTO b1 = new JenkinsBuildDTO(false, "FAILURE", 1, null); JenkinsBuildDTO b2 = new JenkinsBuildDTO(false, "UNSTABLE", 2, null); JenkinsBuildDTO b3 = new JenkinsBuildDTO(false, "SUCCESS", 3, null); JenkinsBuildDTO b4 = new JenkinsBuildDTO(true, "", 4, null); assertE... |
HolidayServiceImpl implements HolidayService { @Override public boolean isHoliday(DateTime day) { if (day == null) { return false; } Calendar cal = GregorianCalendar.getInstance(); cal.setTime(day.toDate()); HolidayManager m = HolidayManager.getInstance(ManagerParameters.create(HolidayCalendar.GERMANY, null)); boolean ... | @Test public void testIsHoliday() { assertTrue(holidayService.isHoliday(new DateTime(2016, 1, 1, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 3, 25, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 3, 28, 0, 0))); assertTrue(holidayService.isHoliday(new DateTime(2016, 5, 1, 0, 0))); as... |
HolidayServiceImpl implements HolidayService { @Override public boolean isWeekend(DateTime day) { return day != null && (day.getDayOfWeek() == DateTimeConstants.SATURDAY || day.getDayOfWeek() == DateTimeConstants.SUNDAY); } @Override boolean isHoliday(DateTime day); @Override boolean isWeekend(DateTime day); @Override... | @Test public void testIsWeekend() { assertFalse(holidayService.isWeekend(new DateTime(2016, 1, 1, 0, 0))); assertTrue(holidayService.isWeekend(new DateTime(2016, 1, 2, 0, 0))); assertTrue(holidayService.isWeekend(new DateTime(2016, 1, 3, 0, 0))); assertFalse(holidayService.isWeekend(new DateTime(2016, 1, 4, 0, 0))); as... |
HolidayServiceImpl implements HolidayService { @Override public boolean isValidWorkingPeriod(DateTime workingStart, DateTime workingEnd) { if (workingStart == null || workingEnd == null) { return false; } else if (workingEnd.getMillisOfDay() < workingStart.getMillisOfDay()) { return false; } else { return workingStart.... | @Test public void testIsValidWorkingPeriod() { DateTime h00m14 = new DateTime(2016, 1, 1, 0, 14); DateTime h00m15 = new DateTime(2016, 1, 1, 0, 15); DateTime h00m16 = new DateTime(2016, 1, 1, 0, 16); DateTime h08m00 = new DateTime(2016, 1, 1, 8, 0); DateTime h16m00 = new DateTime(2016, 1, 1, 16, 0); DateTime h23m44 = n... |
RMSKeyUtils { int toValueIndex(final Long hashValue) { return (int) (hashValue.longValue() & 0xFFFFFFFF); } } | @Test public void valueIndexValuesCanStoreEntireIntegerRange() { long one = 1; long previous = 0; for (int bits = 0; bits < 32; bits++) { long shifted = one << bits; assertTrue("Overflow when shifting long. Previous value: " + previous + " now: " + shifted, shifted > previous); previous = shifted; int vi = keyUtils.toV... |
StringUtils { public static byte[] hexStringToByteArray(final String s) { if (s == null) { throw new NullPointerException("hexStringToByteArray was pass null string"); } final int n = s.length(); if (n % 2 != 0) { throw new IllegalArgumentException("Input string must be an even length and encoded by byteArrayToHexStrin... | @Test public void sampleBytesToHexString() { assertArrayEquals(sampleAsBytes, StringUtils.hexStringToByteArray(sampleAsHex)); }
@Test(expected = IllegalArgumentException.class) public void hexStringChecksForWrongLengthInput() { StringUtils.hexStringToByteArray("0"); }
@Test(expected = IllegalArgumentException.class) pu... |
StringUtils { public static String byteArrayToHexString(final byte[] bytes) { final StringBuffer sb = new StringBuffer(bytes.length * 2); for (int i = 0; i < bytes.length; i++) { appendHex(bytes[i], sb); } return sb.toString(); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String r... | @Test public void sampleHexStringAsBytes() { assertEquals(sampleAsHex, StringUtils.byteArrayToHexString(sampleAsBytes)); }
@Test public void toHexTestFF00() { assertEquals("FF00", StringUtils.byteArrayToHexString(byteTest1)); }
@Test public void toHexTestCD1A() { assertEquals("CD1A", StringUtils.byteArrayToHexString(by... |
StringUtils { public static String urlDecode(final String s) throws UnsupportedEncodingException, IOException { if (s == null) { throw new NullPointerException("Can not urlDecode null string"); } final int n = s.length(); final StringBuffer sb = new StringBuffer(n * 2); for (int i = 0; i < n; i++) { final char c = s.ch... | @Test public void uudecode() throws UnsupportedEncodingException, IOException { assertEquals(roundTripConversionTest, StringUtils.urlDecode(urlDecodeConversionTest)); }
@Test public void uudecodeOneChar() throws UnsupportedEncodingException, IOException { System.out.println("oneChar " + oneChar + " - length=" + oneChar... |
StringUtils { public static String urlEncode(final String s) throws IOException { if (s == null) { throw new NullPointerException("Can not urlEncode null string"); } if (s.length() == 0) { return s; } final ByteArrayInputStream bIn; final StringBuffer sb = new StringBuffer((s.length() * 5) / 4); { final ByteArrayOutput... | @Ignore @Test public void fourByteEncode() throws UnsupportedEncodingException, IOException { String fourByteString = new String(fourByteArray, "UTF-8"); assertEquals(fourByteEncoded, StringUtils.urlEncode(fourByteString)); }
@Test public void threeByteEncode() throws UnsupportedEncodingException, IOException { String ... |
RMSKeyUtils { int toKeyIndex(final Long hashValue) { return (int) ((hashValue.longValue() >>> 32) & 0xFFFFFFFF); } } | @Test public void keyIndexValuesCanStoreEntireIntegerRange() { final int bitsInInteger = 32; final long one = 1; for (int bits = 0; bits < bitsInInteger; bits++) { final int keyIntegerValue = (int)(one << bits); final long shiftedLong = one << (bits + bitsInInteger); int ki = keyUtils.toKeyIndex(shiftedLong); assertEqu... |
RMSFastCache extends FlashCache { public void removeData(final long digest) throws FlashDatabaseException { synchronized (mutex) { try { final Long indexEntry = indexHashGet(digest, false); if (indexEntry != null) { final Long dig = new Long(digest); indexHash.remove(dig); final int valueRecordId = RMSKeyUtils.toValueI... | @Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenNullStringRemoveData() throws DigestException, FlashDatabaseException { rmsFastCache.removeData((String) null); } |
StringUtils { public static String readStringFromJAR(final String name) throws IOException { return readStringFromJAR(name, "UTF-8"); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final String name, final ... | @Test public void testReadStringFromJAR() throws Exception { String name_1 = "/test.txt"; String expResult_1 = "Hello, this is test text"; String result_1 = StringUtils.readStringFromJAR(name_1); assertEquals(expResult_1, result_1); } |
StringUtils { public static byte[] readBytesFromJAR(final String name) throws IOException { return StringUtilsHolder.instance.doReadBytesFromJAR(name); } private StringUtils(); static byte[] readBytesFromJAR(final String name); static String readStringFromJAR(final String name); static String readStringFromJAR(final S... | @Test public void testReadBytesFromJAR() throws Exception { InputStream stream = getClass().getResourceAsStream(EXAMPLE_FILE_NAME); assertNotNull("Could not read example file from classpath", stream); byte[] result_1 = StringUtils.readBytesFromJAR(EXAMPLE_FILE_NAME); assertNotNull(result_1); assertEquals(stream.availab... |
RMSFastCache extends FlashCache { public void put(final String key, final byte[] value) throws DigestException, FlashFullException, FlashDatabaseException { if (key == null) { throw new NullPointerException("You attempted to put a null key to the cache"); } if (value == null) { throw new NullPointerException("You attem... | @Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenPutNullKey() throws DigestException, FlashDatabaseException { rmsFastCache.put(null, new byte[16]); }
@Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenPutNullData() throws DigestException, FlashD... |
SortedVector extends Vector { public synchronized void addElement(final Object o) { int insertIndex = size(); for (int i = size() - 1; i >= 0; i--) { if (comparator.compare(o, elementAt(i)) < 0) { insertIndex--; } else { break; } } if (insertIndex == size()) { super.addElement(o); } else { super.insertElementAt(o, inse... | @Test public void collectionMaintainsSortOrder() { collection.addElement(2); collection.addElement(1); assertEquals(1, collection.firstElement()); assertEquals(2, collection.lastElement()); }
@Test public void duplicatesAreAllowed() { Integer one = new Integer(1); Integer two = new Integer(1); assertNotSame(one, two); ... |
SortedVector extends Vector { public final void insertElementAt(Object o, int index) { throw new IllegalArgumentException("insertElementAt() not supported"); } SortedVector(final Comparator comparator); synchronized void addElement(final Object o); final void insertElementAt(Object o, int index); final void setElementA... | @Test public void insertElementAtTest() { System.out.println("insertElementAt"); SortedVector instance = new SortedVector(new Comparator() { public int compare(Object o1, Object o2) { return ((Integer) o1).intValue() - ((Integer) o2).intValue(); } }); Object o_1 = null; int index_1 = 0; try { instance.insertElementAt(o... |
SortedVector extends Vector { public final void setElementAt(Object o, int index) { throw new IllegalArgumentException("setElementAt() not supported"); } SortedVector(final Comparator comparator); synchronized void addElement(final Object o); final void insertElementAt(Object o, int index); final void setElementAt(Obje... | @Test public void setElementAtTest() { System.out.println("setElementAt"); SortedVector instance = new SortedVector(new Comparator() { public int compare(Object o1, Object o2) { return ((Integer) o1).intValue() - ((Integer) o2).intValue(); } }); Object o_1 = null; int index_1 = 0; try { instance.setElementAt(o_1, index... |
CryptoUtils { public synchronized long toDigest(final String key) throws DigestException, UnsupportedEncodingException { if (key == null) { throw new NullPointerException("You attempted to convert a null string into a hash digest"); } final byte[] bytes = key.getBytes("UTF-8"); return toDigest(bytes); } private Crypto... | @Test public void boodleLongsAreNotTheSameTest() throws DigestException, UnsupportedEncodingException { assertNotEquals("boodle is not a url", cryptoUtils.toDigest(imageUrl1), cryptoUtils.toDigest(boodle)); }
@Test public void almostSameLongsAreNotTheSameTest() throws DigestException, UnsupportedEncodingException { ass... |
LengthLimitedVector extends Vector { public synchronized void addElement(final Object o) { if (maxLength == 0) { throw new IllegalArgumentException("Max length of LRU vector is currently 0, can not add: " + o); } super.addElement(o); if (size() > maxLength) { final Object extra = firstElement(); removeElementAt(0); len... | @Test public void testAddElement() { System.out.println("addElement"); LengthLimitedVector instance = new LengthLimitedVector(3) { protected void lengthExceeded(Object extra) { tooLong = true; } }; instance.addElement("a"); instance.addElement("b"); instance.addElement("c"); instance.addElement("d"); assertEquals("too ... |
LengthLimitedVector extends Vector { protected abstract void lengthExceeded(Object extra); LengthLimitedVector(final int maxLength); synchronized void addElement(final Object o); synchronized final boolean isLengthExceeded(); boolean markAsExtra(final Object o); synchronized void setMaxLength(final int maxLength); } | @Test public void testLengthExceeded() { System.out.println("lengthExceeded"); LengthLimitedVector instance = new LengthLimitedVector(3) { protected void lengthExceeded(Object o) { } }; instance.addElement("a"); instance.addElement("b"); instance.addElement("c"); assertEquals("Full length", 3, instance.size()); instanc... |
RollingAverage { public float value() { return average; } RollingAverage(final int windowLength, final float initialValue); void setUpperBound(final float upperBound); void setLowerBound(final float lowerBound); float value(); float update(final float value); float reset(final float value); } | @Test public void firstGet() { RollingAverage rollingAverage = new RollingAverage(10, 10.0f); assertEquals(10.f, rollingAverage.value(), 0.000001f); } |
RMSFastCache extends FlashCache { public byte[] get(final long digest, final boolean markAsLeastRecentlyUsed) throws FlashDatabaseException { synchronized (mutex) { final Long dig = new Long(digest); final Long hashValue = ((Long) indexHash.get(dig, markAsLeastRecentlyUsed)); if (hashValue != null) { try { final int va... | @Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenGetNullString() throws DigestException, FlashDatabaseException { rmsFastCache.get((String) null); } |
WeakHashCache { public synchronized boolean remove(final Object key) { if (key != null) { return hash.remove(key) != null; } L.i(this, "WeakHashCache", "remove() with null key"); return false; } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronize... | @Test public void testRemove() { System.out.println("remove"); WeakHashCache instance = new WeakHashCache(); String key1 = ""; String key2 = "a"; instance.remove(null); instance.remove(key1); instance.put(key1, "fruit"); instance.put(key2, "cake"); instance.remove(key1); instance.remove(key2); assertEquals(instance.siz... |
WeakHashCache { public synchronized void put(final Object key, final Object value) { if (key == null) { throw new NullPointerException("null key put to WeakHashCache"); } if (value == null) { throw new IllegalArgumentException("null value put to WeakHashCache"); } hash.put(key, new WeakReference(value)); } synchronize... | @Test public void testPut() { System.out.println("put"); WeakHashCache instance = new WeakHashCache(); String key1 = ""; String key2 = "a"; String expectedVal1 = "fruit"; instance.put(key1, expectedVal1); instance.put(key2, "cake"); try { instance.put(null, "dog"); fail("Did not catch null key put to WeakHashCache"); }... |
WeakHashCache { public synchronized Object get(final Object key) { if (key == null) { throw new NullPointerException("Attempt to get(null) from WeakHashCache"); } final WeakReference reference = (WeakReference) hash.get(key); if (reference == null) { return null; } return reference.get(); } synchronized Object get(fin... | @Test public void testGet() { System.out.println("get"); WeakHashCache instance = new WeakHashCache(); String key1 = "11"; String key2 = "22"; Object value1 = "chocolate"; Object value2 = "cake"; Object result_1 = instance.get(key1); assertNull("get null", result_1); instance.put(key1, value1); instance.put(key2, value... |
WeakHashCache { public synchronized boolean containsKey(final Object key) { if (key == null) { throw new NullPointerException("containsKey() with null key"); } return hash.containsKey(key); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized v... | @Test public void testContainsKey() { System.out.println("containsKey"); WeakHashCache instance = new WeakHashCache(); String key1 = "11"; String key2 = "22"; Object value1 = "chocolate"; Object value2 = "cake"; instance.put(key1, value1); instance.put(key2, value2); assertEquals(false, instance.containsKey("red")); as... |
WeakHashCache { public synchronized int size() { return hash.size(); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean rem... | @Test public void testSize() { System.out.println("size"); WeakHashCache instance = new WeakHashCache(); final int length = 10000; for (int i = 0; i < length; i++) { instance.put("keykeykey" + i, "valuevaluevalue" + i); } assertEquals(length, instance.size()); } |
WeakHashCache { public synchronized void clear() { hash.clear(); } synchronized Object get(final Object key); synchronized Enumeration keys(); synchronized Enumeration elements(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(... | @Test public void testClear() { System.out.println("size"); WeakHashCache instance = new WeakHashCache(); final int length = 10000; for (int i = 0; i < length; i++) { instance.put(VALUE_CONSTANT + i, "valuevaluevalue" + i); } assertEquals(length, instance.size()); instance.clearValues(); assertEquals(length, instance.s... |
JSONModel { public synchronized void setJSON(final String json) throws JSONException { if (json == null) { throw new NullPointerException("Can not setJSON(null): " + this); } jsonObject = new JSONObject(json); } JSONModel(); JSONModel(final String json); synchronized void setJSON(final String json); synchronized boole... | @Test public void basicModelTest() throws JSONException { JSONModel model = new JSONModel(); model.setJSON(SAMPLE_DATA); }
@Test public void oddParsingOfTheModel() throws IOException, JSONException { final JSONModel jsonModel = new JSONModel(); jsonModel.setJSON(SAMPLE_DATA); } |
LRUVector extends Vector { public void setElementAt(Object o, int index) { throw new IllegalArgumentException("setElementAt() not allowed on LRUVector"); } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Object o, int index)... | @Test public void testSetElementAt() { System.out.println("setElementAt"); LRUVector instance = new LRUVector(); Object o_1 = null; int index_1 = 0; try { instance.setElementAt(o_1, index_1); } catch (IllegalArgumentException e) { return; } fail("testSetElementAt() should throw an exception."); } |
RSSModel extends XMLModel { protected synchronized void parseElement(final String qname, final String chars, final XMLAttributes attributes) { try { if (currentItem != null) { if (qname.equals("title")) { currentItem.setTitle(chars); } else if (qname.equals("description")) { currentItem.setDescription(chars); } else if... | @Test public void testParseElement() throws SAXException { instance.setXML(xml); assertEquals("rss size", 86, instance.size()); } |
HttpGetter extends Task { public Object exec(final Object in) throws InterruptedException { LOR out = null; if (Task.isShuttingDown()) { L.i("Attempt to run HttpGetter during shutdown", "ignored"); setRetriesRemaining(0); cancel("Attempt to run HttpGetter during shutdown"); return out; } if (!(in instanceof String) || ... | @Test public void canceledWhenNonStringKey() throws InterruptedException { getter.exec(new Object()); assertEquals("Getter was not correctly cancelled for non-String url", getter.getStatus(), Task.CANCELED); } |
Task { public final Task fork() { return Worker.fork(this); } Task(final int priority); Task(); Task(final int priority, final Object initialValue); static boolean isTimerThread(); static boolean isShuttingDown(); static boolean isShutdownComplete(); static Timer getTimer(); void unchain(); final Object get(); final ... | @Test public void testFork() { System.out.println("fork"); Task instance = new Task(Task.FASTLANE_PRIORITY) { protected Object exec(Object in) { return "run"; } }; Task result_1 = instance.fork(); assertEquals(instance, result_1); try { Thread.sleep(200); } catch (InterruptedException ex) { ex.printStackTrace(); } try ... |
Task { public final Object join() throws CancellationException, TimeoutException { return join(MAX_TIMEOUT); } Task(final int priority); Task(); Task(final int priority, final Object initialValue); static boolean isTimerThread(); static boolean isShuttingDown(); static boolean isShutdownComplete(); static Timer getTi... | @Test(expected = TimeoutException.class) public void taskTimesOutIfJoinedBeforeFork() throws CancellationException, TimeoutException { Task instance = new Task(Task.FASTLANE_PRIORITY, "white") { protected Object exec(Object in) { System.out.println("Executing task 1"); return (String) in + " rabbit"; } }; instance.join... |
Task { protected void onCanceled(final String reason) { L.i(this, "default Task.onCanceled() - this method was not overridden: cancellationReason=" + reason, this.toString()); } Task(final int priority); Task(); Task(final int priority, final Object initialValue); static boolean isTimerThread(); static boolean isShut... | @Ignore @Test public void onCanceledTest() { System.out.println("onCanceled"); final Vector v = new Vector(); v.addElement("Dummy"); final Task instance = new Task(Task.HIGH_PRIORITY) { @Override protected Object exec(Object in) { try { Thread.sleep(200); fail("testOnCanceled() Task instance should have been interrupte... |
LRUVector extends Vector { public void insertElementAt(Object o, int index) { throw new IllegalArgumentException("insertElementAt() not allowed on LRUVector"); } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Object o, int ... | @Test public void testInsertElementAt() { System.out.println("setElementAt"); LRUVector instance = new LRUVector(); Object o_1 = null; int index_1 = 0; try { instance.insertElementAt(o_1, index_1); } catch (IllegalArgumentException e) { return; } fail("testInsertElementAt() should throw an exception."); } |
LRUVector extends Vector { public synchronized void addElement(Object o) { removeElement(o); super.addElement(o); } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Object o, int index); synchronized Object removeLeastRecentl... | @Test public void testAddElement() { System.out.println("addElement"); LRUVector instance = new LRUVector(); Object o_1 = "a"; Object o_2 = "b"; instance.addElement(o_1); assertEquals("Size 1", 1, instance.size()); instance.addElement(o_2); assertEquals("Size 2", 2, instance.size()); instance.addElement(o_1); assertEqu... |
LRUVector extends Vector { public synchronized Object removeLeastRecentlyUsed() { final Object o = getLeastRecentlyUsed(); if (o != null) { removeElement(o); } return o; } LRUVector(); LRUVector(final int length); synchronized void addElement(Object o); void setElementAt(Object o, int index); void insertElementAt(Obje... | @Test public void testRemoveLeastRecentlyUsed() { System.out.println("removeLeastRecentlyUsed"); LRUVector instance = new LRUVector(); Object expResult_1 = true; instance.addElement("a"); instance.addElement("b"); instance.addElement("c"); instance.addElement("d"); instance.addElement("e"); instance.addElement("f"); Ob... |
CustomerController { @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) public void createCustomer(@Valid @RequestBody Customer customer) { log.debug("Creating customer {}", customer); customerRepository.save(customer); } @ApiOperation(value = "Create a new customer.") @Po... | @Test public void testCreateCustomer() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/customer").content(CUSTOMER_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()); } |
ProductController { @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") public Product findOne(@PathVariable("productId") Long productId) { return productRepository.findOne(productId); } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Fi... | @Test public void testFindOne() throws Exception { when(productRepository.findOne(1L)).thenReturn(buildPersistentProduct()); mvc.perform(MockMvcRequestBuilders.get("/product/{productId}", 1L) .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk())... |
AccountEntry { public BigDecimal getTotalAmount() { return price.multiply(BigDecimal.valueOf(quantity)); } BigDecimal getTotalAmount(); } | @Test public void testTotalAmount() throws Exception { AccountEntry entry = new AccountEntry().setPrice(BigDecimal.ONE).setQuantity(12l); assertThat(entry.getTotalAmount(), is(equalTo(new BigDecimal("12")))); } |
StockService { public Long registerStock(String stockName) { return stockRepository.save(new Stock().setName(stockName)).getId(); } Long registerStock(String stockName); List<Stock> findAllStocks(); Stock findStock(Long stockId); List<StockEntryQuantity> quantityOfAvailableProducts(Long stockId); void put(Long stockId... | @Test public void testRegisterStock() throws Exception { Long stockId = stockService.registerStock(STOCKNAME); assertThat(stockId, is(notNullValue())); } |
StockService { public Stock findStock(Long stockId) { return stockRepository.findOne(stockId); } Long registerStock(String stockName); List<Stock> findAllStocks(); Stock findStock(Long stockId); List<StockEntryQuantity> quantityOfAvailableProducts(Long stockId); void put(Long stockId, Long productId, Long quantity, do... | @Test public void testFindStock() throws Exception { Long stockId = stockService.registerStock(STOCKNAME); Stock stock = stockService.findStock(stockId); assertThat(stock.getName(), is(STOCKNAME)); } |
StockController { @ApiOperation("Get stock") @GetMapping(path = "/{stockId}") public StockInfo getStock(@PathVariable("stockId") Long stockId) { Stock stock = stockService.findStock(stockId); return new StockInfo(stock.getId(),stock.getName()); } @ApiOperation("Get all stocks") @GetMapping List<StockInfo> getStocks();... | @Test public void testGetStock() throws Exception { when(stockService.findStock(1l)).thenReturn(buildPersistentStock()); mvc.perform(MockMvcRequestBuilders.get("/stock/{stockId}", 1l) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().json("{\"... |
CustomerController { @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") public Customer findCustomer(@PathVariable("customerId") long customerId) { return customerRepository.findOne(customerId); } @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) v... | @Test public void testFindCustomer() throws Exception { when(customerRepository.findOne(anyLong())) .thenReturn(CustomerFixture.buildDefaultCustomer()); mvc.perform(MockMvcRequestBuilders.get("/customer/{customerId}", 5l) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().i... |
CustomerController { @ApiOperation("Find all customers.") @GetMapping public List<Customer> findAll() { return customerRepository.findAll(); } @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value... | @Test public void testFindAll() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/customer") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()) .andExpect(content() .json("[]")); } |
CustomerController { @ApiOperation("Update customer") @PutMapping("/{customerId}") public Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer) { final Customer customerModel = customerRepository.findOne(customerId); customerModel.setName(customer.getName()); custom... | @Test public void testUpdateCustomer() throws Exception { when(customerRepository.findOne(anyLong())) .thenReturn(CustomerFixture.buildDefaultCustomer()); mvc.perform(MockMvcRequestBuilders.put("/customer/{customerId}", 5l).content(CUSTOMER_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JS... |
UserController { @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATED) public void createUser(@Valid @RequestBody User user) { userRepository.save(user); } @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createUser(@Valid @Request... | @Test public void testCreateUser() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/user").content(USER_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()); } |
UserController { @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) public void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest) { User user = userRepository.findOne(userId); if (user != null) { if (use... | @Test public void testUpdatePassword() throws Exception { User user = UserFixture.buildPersistentUser(); when(userRepository.findOne(2L)) .thenReturn(user); mvc.perform(MockMvcRequestBuilders.put("/user/{userId}/change-password", 2L).content(PASSWORD_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPL... |
UserController { @ApiOperation(value = "Find all users.") @GetMapping public List<UserInfo> findAll() { return userRepository .findAll() .stream() .filter(u -> u != null) .map(this::mapToUserInfo).collect(Collectors.toList()); } @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATE... | @Test public void testFindCustomer() throws Exception { when(userRepository.findAll()) .thenReturn(Arrays.asList(UserFixture.buildDefaultUser(), UserFixture.buildPersistentUser())); mvc.perform(MockMvcRequestBuilders.get("/user", 5l) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpec... |
ProductController { @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping public void createProduct(@Valid @RequestBody Product product) { productRepository.save(product); } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Find o... | @Test public void testCreateProduct() throws Exception { mvc.perform(MockMvcRequestBuilders.post("/product").content(PRODUCT_JSON) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON)).andExpect(status().isCreated()); verify(productRepository, times(1)).save(any(Product.class)); } |
ProductController { @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") public void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product) { Product entity = productRepository.findOne(productId); if (entity != null) { entity.setName(product.getName()); enti... | @Test public void testUpdateProduct() throws Exception { when(productRepository.findOne(1L)).thenReturn(buildPersistentProduct()); mvc.perform(MockMvcRequestBuilders.put("/product/{productId}", 1L) .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExpect(status().i... |
ProductController { @ApiOperation(value = "Find all products.") @GetMapping public List<Product> findAll() { return productRepository.findAll(); } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") Product findO... | @Test public void testFindAll() throws Exception { when(productRepository.findAll()).thenReturn(Arrays.asList(buildDefaultProduct(), buildPersistentProduct())); mvc.perform(MockMvcRequestBuilders.get("/product") .contentType(MediaType.APPLICATION_JSON) .content(PRODUCT_JSON) .accept(MediaType.APPLICATION_JSON)) .andExp... |
PDDocumentCatalogBleach { private void sanitizeAcroFormActions(PDAcroForm acroForm) { if (acroForm == null) { LOGGER.debug("No AcroForms found"); return; } LOGGER.trace("Checking AcroForm Actions"); Iterator<PDField> fields = acroForm.getFieldIterator(); fields.forEachRemaining(this::sanitizeField); } PDDocumentCatalog... | @Test void sanitizeAcroFormActions() { PDFormFieldAdditionalActions fieldActions = new PDFormFieldAdditionalActions(); fieldActions.setC(new PDActionJavaScript()); fieldActions.setF(new PDActionJavaScript()); fieldActions.setK(new PDActionJavaScript()); fieldActions.setV(new PDActionJavaScript()); instance.sanitizeFiel... |
MacroRemover extends EntryFilter { @Override public boolean test(Entry entry) { String entryName = entry.getName(); if (!isMacro(entryName)) { return true; } LOGGER.info("Found Macros, removing them."); StringBuilder infos = new StringBuilder(); if (entry instanceof DirectoryEntry) { Set<String> entryNames = ((Director... | @Test void testRemovesMacro() { Entry entry = mock(Entry.class); doReturn("_VBA_PROJECT_CUR").when(entry).getName(); assertFalse(instance.test(entry), "A macro entry should not be copied over"); BleachTestBase.assertThreatsFound(session, 1); reset(session); }
@Test void testKeepsEverythingElse() { Entry entry = mock(En... |
MacroRemover extends EntryFilter { protected boolean isMacro(String entryName) { return MACRO_ENTRY.equalsIgnoreCase(entryName) || entryName.contains(VBA_ENTRY); } MacroRemover(BleachSession session); @Override boolean test(Entry entry); } | @Test void recognizesMacros() { assertTrue( instance.isMacro("_VBA_PROJECT_CUR"), "_VBA_PROJECT_CUR is the Excel Macro directory"); assertFalse(instance.isMacro("Nothing"), "Nothing is not a macro. Is-it?"); } |
ExcelRecordCleaner { protected static void removeObProjRecord(Collection<Record> records) { new HashSet<>(records) .forEach( record -> { if (!isObProj(record)) { return; } records.remove(record); LOGGER.debug("Found and removed ObProj record: {}", record); }); } } | @Test void removeObProjRecord() { Record valid1 = new UnknownRecord(0x01, new byte[]{}); Record obProj1 = new UnknownRecord(0xD3, new byte[]{}); Record valid2 = new UnknownRecord(0x02, new byte[]{}); Collection<Record> records = new HashSet<>(); records.add(valid1); records.add(obProj1); records.add(valid2); ExcelRecor... |
SummaryInformationSanitiser extends EntryFilter { protected void sanitizeSummaryInformation(BleachSession session, DocumentEntry dsiEntry) { if (dsiEntry.getSize() <= 0) { return; } try (DocumentInputStream dis = new DocumentInputStream(dsiEntry)) { PropertySet ps = new PropertySet(dis); SummaryInformation dsi = new Su... | @Test void sanitizeSummaryInformation() { } |
SummaryInformationSanitiser extends EntryFilter { protected void sanitizeComments(BleachSession session, SummaryInformation dsi) { String comments = dsi.getComments(); if (comments == null || comments.isEmpty()) { return; } LOGGER.trace("Removing the document's Comments (was '{}')", comments); dsi.removeComments(); Thr... | @Test void sanitizeComments() { SummaryInformation si = new SummaryInformation(); instance.sanitizeComments(session, si); assertThreatsFound(session, 0); si.setComments("Hello!"); instance.sanitizeComments(session, si); assertNull(si.getComments()); assertThreatsFound(session, 1); } |
SummaryInformationSanitiser extends EntryFilter { protected void sanitizeTemplate(BleachSession session, SummaryInformation dsi) { String template = dsi.getTemplate(); if (NORMAL_TEMPLATE.equals(template)) { return; } if (template == null) { return; } LOGGER.trace("Removing the document's template (was '{}')", template... | @Test void sanitizeTemplate() { } |
SummaryInformationSanitiser extends EntryFilter { protected boolean isExternalTemplate(String template) { return template.startsWith("http: || template.startsWith("https: || template.startsWith("ftp: } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); } | @Test void isExternalTemplate() { assertFalse(instance.isExternalTemplate("Normal.dotm"), "The base template is not external"); assertFalse(instance.isExternalTemplate("my-template.dotm"), "Unknown template"); assertFalse(instance.isExternalTemplate("hxxp: assertTrue(instance.isExternalTemplate("https: assertTrue(insta... |
ObjectRemover extends EntryFilter { @Override public boolean test(Entry entry) { String entryName = entry.getName(); if (!isObject(entryName)) { return true; } LOGGER.info("Found Compound Objects, removing them."); StringBuilder infos = new StringBuilder(); if (entry instanceof DirectoryEntry) { Set<String> entryNames ... | @Test void testRemovesMacro() { Entry entry = mock(Entry.class); doReturn("\u0001CompObj").when(entry).getName(); assertFalse(instance.test(entry), "An object entry should not be copied over"); BleachTestBase.assertThreatsFound(session, 1); reset(session); }
@Test void testKeepsEverythingElse() { Entry entry = mock(Ent... |
PDDocumentCatalogBleach { private void sanitizePageActions(PDPageTree pages) throws IOException { LOGGER.trace("Checking Pages Actions"); for (PDPage page : pages) { sanitizePage(page); } } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); } | @Test void sanitizePageActions() { PDPageAdditionalActions actions = new PDPageAdditionalActions(); actions.setC(new PDActionJavaScript()); actions.setO(new PDActionJavaScript()); instance.sanitizePageActions(actions); assertThreatsFound(session, 2); assertNull(actions.getC()); assertNull(actions.getO()); reset(session... |
ObjectRemover extends EntryFilter { protected boolean isObject(String entryName) { return OBJECT_POOL_ENTRY.equalsIgnoreCase(entryName) || COMPOUND_OBJECT_ENTRY.equalsIgnoreCase(entryName); } ObjectRemover(BleachSession session); @Override boolean test(Entry entry); } | @Test void recognizesObjects() { assertTrue( instance.isObject("\u0001CompObj"), "u0001CompObj is the Excel Macro directory name"); assertFalse(instance.isObject("Nothing"), "Nothing is not an object. Is-it?"); } |
OOXMLBleach implements Bleach { boolean isForbiddenType(ContentType type) { String fullType = type.toString(false); for (String _type : BLACKLISTED_CONTENT_TYPES) { if (_type.equalsIgnoreCase(fullType)) { return true; } } return false; } @Override boolean handlesMagic(InputStream stream); @Override String getName(); @... | @Test @Disabled void isForbiddenType() throws InvalidFormatException { ContentType ct; ct = new ContentType("application/postscript"); assertTrue(instance.isForbiddenType(ct)); }
@Test @Disabled void noFalsePositiveForbiddenType() throws InvalidFormatException { ContentType ct; for (String contentType : NOT_DYNAMIC_TYP... |
OOXMLBleach implements Bleach { @Override public boolean handlesMagic(InputStream stream) { try { return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OOXML; } catch (Exception e) { LOGGER.warn("An exception occured", e); return false; } } @Override boolean handlesMagic(InputStream stream); @Overrid... | @Test void handlesMagic() throws IOException { Charset cs = Charset.defaultCharset(); InputStream invalidInputStream2 = new ByteArrayInputStream("".getBytes(cs)); assertFalse(instance.handlesMagic(invalidInputStream2)); InputStream invalidInputStream3 = new ByteArrayInputStream("Anything".getBytes(cs)); assertFalse(ins... |
PDDocumentCatalogBleach { void sanitizeDocumentActions(PDDocumentCatalogAdditionalActions documentActions) { LOGGER.trace("Checking additional actions..."); if (documentActions.getDP() != null) { LOGGER.debug("Found&removed action after printing (was {})", documentActions.getDP()); documentActions.setDP(null); pdfBleac... | @Test void sanitizeAdditionalActions() { PDDocumentCatalogAdditionalActions documentCatalogAdditionalActions = new PDDocumentCatalogAdditionalActions(); instance.sanitizeDocumentActions(documentCatalogAdditionalActions); documentCatalogAdditionalActions.setDP(new PDActionJavaScript()); documentCatalogAdditionalActions.... |
PDDocumentCatalogBleach { void sanitizeOpenAction(PDDocumentCatalog docCatalog) throws IOException { LOGGER.trace("Checking OpenAction..."); PDDestinationOrAction openAction = docCatalog.getOpenAction(); if (openAction == null) { return; } LOGGER.debug("Found a JavaScript OpenAction, removed. Was {}", openAction); docC... | @Test void sanitizeOpenAction() throws IOException { PDDocumentCatalog documentCatalog = mock(PDDocumentCatalog.class); when(documentCatalog.getOpenAction()).thenReturn(new PDActionJavaScript()); instance.sanitizeOpenAction(documentCatalog); verify(documentCatalog, atLeastOnce()).getOpenAction(); verify(documentCatalog... |
PDAnnotationBleach { void sanitizeLinkAnnotation(PDAnnotationLink annotationLink) { if (annotationLink.getAction() == null) { return; } LOGGER.debug("Found&removed annotation link - action, was {}", annotationLink.getAction()); pdfBleachSession.recordJavascriptThreat("Annotation", "External link"); annotationLink.setAc... | @Test void sanitizeAnnotationLink() { PDAnnotationLink annotationLink = new PDAnnotationLink(); annotationLink.setAction(new PDActionJavaScript()); instance.sanitizeLinkAnnotation(annotationLink); assertThreatsFound(session, 1); assertNull(annotationLink.getAction()); reset(session); instance.sanitizeLinkAnnotation(ann... |
PDAnnotationBleach { void sanitizeWidgetAnnotation(PDAnnotationWidget annotationWidget) { if (annotationWidget.getAction() != null) { LOGGER.debug( "Found&Removed action on annotation widget, was {}", annotationWidget.getAction()); pdfBleachSession.recordJavascriptThreat("Annotation", "External widget"); annotationWidg... | @Test void sanitizeAnnotationWidgetAction() { PDAnnotationWidget annotationWidget = new PDAnnotationWidget(); annotationWidget.setAction(new PDActionJavaScript()); instance.sanitizeWidgetAnnotation(annotationWidget); assertThreatsFound(session, 1); assertNull(annotationWidget.getAction()); reset(session); instance.sani... |
PDAnnotationBleach { void sanitizeAnnotationActions(PDAnnotationAdditionalActions annotationAdditionalActions) { if (annotationAdditionalActions == null) { return; } if (annotationAdditionalActions.getBl() != null) { LOGGER.debug( "Found&Removed action on annotation widget to be performed when the annotation loses the ... | @Test void sanitizeAnnotationWidgetActions() throws ReflectiveOperationException { final String[] methods = {"Bl", "D", "E", "Fo", "PC", "PI", "PO", "U", "X"}; final PDAction action = new PDActionJavaScript(); final Class<PDAnnotationAdditionalActions> clazz = PDAnnotationAdditionalActions.class; for (String name : met... |
PdfBleach implements Bleach { @Override public boolean handlesMagic(InputStream stream) { return StreamUtils.hasHeader(stream, PDF_MAGIC); } @Override boolean handlesMagic(InputStream stream); @Override String getName(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session)... | @Test void handlesMagic() { Charset charset = Charset.defaultCharset(); InputStream validInputStream = new ByteArrayInputStream("%PDF1.5".getBytes(charset)); assertTrue(instance.handlesMagic(validInputStream)); InputStream invalidInputStream = new ByteArrayInputStream("".getBytes(charset)); assertFalse(instance.handles... |
PdfBleachSession { void recordJavascriptThreat(String location, String details) { Threat threat = Threat.builder() .type(ThreatType.ACTIVE_CONTENT) .severity(ThreatSeverity.HIGH) .details(details) .location(location) .action(ThreatAction.REMOVE) .build(); session.recordThreat(threat); } PdfBleachSession(BleachSession s... | @Test void recordingJavascriptThreatWorks() { instance.recordJavascriptThreat("", ""); assertThreatsFound(session, 1); } |
OLE2Bleach implements Bleach { @Override public boolean handlesMagic(InputStream stream) { try { return stream.available() > 4 && FileMagic.valueOf(stream) == FileMagic.OLE2; } catch (Exception e) { LOGGER.warn("An exception occured", e); return false; } } @Override boolean handlesMagic(InputStream stream); @Override ... | @Test void handlesMagic() throws IOException { Charset charset = Charset.defaultCharset(); InputStream invalidInputStream = new ByteArrayInputStream("".getBytes(charset)); assertFalse(instance.handlesMagic(invalidInputStream)); invalidInputStream = new ByteArrayInputStream("Anything".getBytes(charset)); assertFalse(ins... |
Altitude implements IWrappedInteger<Altitude>, Comparable<Altitude> { @Override public int compareTo(final Altitude that) { return Integer.compare(this.val, that.val); } Altitude(final int val); @Override int intValue(); @Override int compareTo(final Altitude that); @Override boolean equals(final Object object); @Overr... | @Test public void Test_compareTo() { { final Altitude a1 = new Altitude(0); final Altitude a2 = new Altitude(0); Assert.assertTrue(a1.compareTo(a2) == 0); } { final Altitude a1 = new Altitude(1); final Altitude a2 = new Altitude(2); Assert.assertTrue(a1.compareTo(a2) < 0); } { final Altitude a1 = new Altitude(1); final... |
Position { public Position divide(final Position position) { final int x = getX() / position.getX(); final int y = getY() / position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); ... | @Test public void PositionDivide() { Position p1 = new Position(1, 2); Position p2 = p1.divide(new Position(1, 1)); Position p3 = p1.divide(new Position(2, 2)); Assert.assertEquals(new Position(1, 2), p2); Assert.assertEquals(new Position(0, 1), p3); p2 = p2.divide(new Position(2, 2)); p3 = p3.divide(new Position(1, 1)... |
Position { @Override public String toString() { return "[" + getX() + ", " + getY() + "]"; } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int getY(); int getDistance(final Position position); TilePosition toTilePosi... | @Test public void PositionOstream() { Position p1 = new Position(2, -3); Assert.assertEquals("[2, -3]", p1.toString()); } |
Altitude implements IWrappedInteger<Altitude>, Comparable<Altitude> { @Override public int intValue() { return this.val; } Altitude(final int val); @Override int intValue(); @Override int compareTo(final Altitude that); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString()... | @Test public void Test_HashMap_get() { final AbstractMap<Altitude, Integer> map = new ConcurrentHashMap<>(); map.put(new Altitude(0), 0); map.put(new Altitude(1), 1); map.put(new Altitude(2), 2); map.put(new Altitude(3), 3); map.put(new Altitude(4), 4); Assert.assertEquals(0, map.get(new Altitude(0)).intValue()); Asser... |
WalkPosition { public WalkPosition add(WalkPosition walkPosition) { final int x = getX() + walkPosition.getX(); final int y = getY() + walkPosition.getY(); return new WalkPosition(x, y); } WalkPosition(final int x, final int y); WalkPosition(final TilePosition tilePosition); WalkPosition(final Position position); int... | @Test public void testArrayListContains() { final List<WalkPosition> list = new ArrayList<>(); list.add(new WalkPosition(0, 0)); list.add(new WalkPosition(24, 87)); list.add(new WalkPosition(48, 39)); list.add(new WalkPosition(361, 92)); list.add(new WalkPosition(510, 6)); Assert.assertTrue(list.contains(new WalkPositi... |
TilePosition { @Override public boolean equals(final Object object) { if (this == object) { return true; } if (!(object instanceof TilePosition)) { return false; } final TilePosition tilePosition = (TilePosition) object; if (getX() != tilePosition.getX()) { return false; } if (getY() != tilePosition.getY()) { return fa... | @Test public void testEquals() { { TilePosition a1 = new TilePosition(0, 0); TilePosition a2 = new TilePosition(0, 0); Assert.assertTrue(a1.equals(a2) && a2.equals(a1)); } { TilePosition b1 = new TilePosition(27, 98); TilePosition b2 = new TilePosition(27, 98); Assert.assertTrue(b1.equals(b2) && b2.equals(b1)); } { Til... |
TilePosition { @Override public int hashCode() { return (getX() * 2048 + getY()); } @BridgeValue TilePosition(final int x, final int y); TilePosition(final WalkPosition walkPosition); TilePosition(final Position position); int getX(); int getY(); double getDistance(final TilePosition position); WalkPosition toWalkPo... | @Test public void testHashCode() { Assert.assertEquals(new TilePosition(0, 0).hashCode(), new TilePosition(0, 0).hashCode()); Assert.assertEquals(new TilePosition(3, 87).hashCode(), new TilePosition(3, 87).hashCode()); Assert.assertEquals(new TilePosition(112, 6).hashCode(), new TilePosition(112, 6).hashCode()); HashMa... |
Position { @Override public boolean equals(final Object object) { if (this == object) { return true; } if (!(object instanceof Position)) { return false; } final Position position = (Position) object; if (getX() != position.getX()) { return false; } if (getY() != position.getY()) { return false; } return true; } @Bridg... | @Test public void PositionEquality() { final TilePosition p1 = new TilePosition(0, 0); final TilePosition p2 = new TilePosition(2, 2); Assert.assertFalse(p1.equals(p2)); Assert.assertTrue(!p1.equals(p2)); } |
Position { public Position add(final Position position) { final int x = getX() + position.getX(); final int y = getY() + position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX(); int... | @Test public void PositionAdd() { Position p1 = new Position(1, 1); Position p2 = new Position(1, 2); Position p3 = p1.add(p2); Assert.assertEquals(new Position(2, 3), p3); p3 = p3.add(p1); Assert.assertEquals(new Position(3, 4), p3); p3 = p3.add(new Position(0, 0)); Assert.assertEquals(new Position(3, 4), p3); } |
Position { public Position subtract(final Position position) { final int x = getX() - position.getX(); final int y = getY() - position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX()... | @Test public void PositionSubtract() { Position p1 = new Position(1, 1); Position p2 = new Position(1, 2); Position p3 = p1.subtract(p2); Assert.assertEquals(new Position(0, -1), p3); p3 = p3.subtract(p1); Assert.assertEquals(new Position(-1, -2), p3); p3 = p3.subtract(new Position(0, 0)); Assert.assertEquals(new Posit... |
Position { public Position multiply(final Position position) { final int x = getX() * position.getX(); final int y = getY() * position.getY(); return new Position(x, y); } @BridgeValue Position(final int x, final int y); Position(final TilePosition tilePosition); Position(final WalkPosition walkPosition); int getX()... | @Test public void PositionMultiply() { Position p1 = new Position(1, 2); Position p2 = p1.multiply(new Position(1, 1)); Position p3 = p1.multiply(new Position(2, 2)); Assert.assertEquals(new Position(1, 2), p2); Assert.assertEquals(new Position(2, 4), p3); p2 = p2.multiply(new Position(2, 2)); p3 = p3.multiply(new Posi... |
LostApiClientImpl implements LostApiClient { @Override public void connect() { clientManager.addClient(this); GeofencingApiImpl geofencingApi = getGeofencingImpl(); if (!geofencingApi.isConnected()) { geofencingApi.connect(context); } SettingsApiImpl settingsApi = getSettingsApiImpl(); if (!settingsApi.isConnected()) {... | @Test public void connect_shouldBeConnectedWhenConnectionCallbackInvoked() throws Exception { callbacks.setLostClient(client); client.connect(); assertThat(callbacks.isClientConnectedOnConnect()).isTrue(); }
@Test public void connect_multipleClients_shouldBeConnectedWhenConnectionCallbackInvoked() throws Exception { cl... |
LostApiClientImpl implements LostApiClient { @Override public boolean isConnected() { return getGeofencingImpl().isConnected() && getSettingsApiImpl().isConnected() && getFusedLocationProviderApiImpl().isConnected() && clientManager.containsClient(this); } LostApiClientImpl(Context context, ConnectionCallbacks callback... | @Test public void isConnected_shouldReturnFalseBeforeConnected() throws Exception { assertThat(client.isConnected()).isFalse(); } |
LocationRequest implements Parcelable { public int getPriority() { return priority; } private LocationRequest(); protected LocationRequest(Parcel in); static LocationRequest create(); long getInterval(); LocationRequest setInterval(long millis); long getFastestInterval(); LocationRequest setFastestInterval(long milli... | @Test public void getPriority_shouldReturnDefaultValue() throws Exception { assertThat(locationRequest.getPriority()).isEqualTo(PRIORITY_BALANCED_POWER_ACCURACY); } |
LocationRequest implements Parcelable { public LocationRequest setPriority(int priority) { if (priority != PRIORITY_HIGH_ACCURACY && priority != PRIORITY_BALANCED_POWER_ACCURACY && priority != PRIORITY_LOW_POWER && priority != PRIORITY_NO_POWER) { throw new IllegalArgumentException("Invalid priority: " + priority); } t... | @Test(expected = IllegalArgumentException.class) public void setPriority_shouldRejectInvalidValues() throws Exception { locationRequest.setPriority(-1); } |
LostClientManager implements ClientManager { @Override public int numberOfClients() { return clients.size(); } LostClientManager(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client)... | @Test public void shouldHaveZeroClientCount() { assertThat(manager.numberOfClients()).isEqualTo(0); } |
LostClientManager implements ClientManager { @Override public void addListener(LostApiClient client, LocationRequest request, LocationListener listener) { throwIfClientNotAdded(client); clients.get(client).locationListeners().add(listener); listenerToLocationRequests.put(listener, request); } LostClientManager(); stati... | @Test(expected = IllegalArgumentException.class) public void addListener_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addListener(client, LocationRequest.create(), new TestLocationListener()); } |
LostClientManager implements ClientManager { @Override public void addPendingIntent(LostApiClient client, LocationRequest request, PendingIntent callbackIntent) { throwIfClientNotAdded(client); clients.get(client).pendingIntents().add(callbackIntent); intentToLocationRequests.put(callbackIntent, request); } LostClientM... | @Test(expected = IllegalArgumentException.class) public void addPendingIntent_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addPendingIntent(client, LocationRequest.create(), mock(PendingIntent.class)); } |
LostClientManager implements ClientManager { @Override public void addLocationCallback(LostApiClient client, LocationRequest request, LocationCallback callback, Looper looper) { throwIfClientNotAdded(client); clients.get(client).locationCallbacks().add(callback); clients.get(client).looperMap().put(callback, looper); c... | @Test(expected = IllegalArgumentException.class) public void addLocationCallback_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addLocationCallback(client, LocationRequest.create(), new TestLocationCallback(), mock(Looper.class)); } |
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public boolean isConnecting() { return serviceConnectionManager.isConnecting(); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context ... | @Test public void isConnecting_shouldCallConnectionManager() { api.isConnecting(); verify(connectionManager).isConnecting(); } |
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public void addConnectionCallbacks(LostApiClient.ConnectionCallbacks callbacks) { serviceConnectionManager.addCallbacks(callbacks); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager c... | @Test public void addConnectionCallbacks_shouldCallConnectionManager() { TestConnectionCallbacks callbacks = new TestConnectionCallbacks(); api.addConnectionCallbacks(callbacks); verify(connectionManager).addCallbacks(callbacks); } |
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public void connect(Context context, LostApiClient.ConnectionCallbacks callbacks) { serviceConnectionManager.connect(context, callbacks); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionMan... | @Test public void connect_shouldCallConnectionManager() { Context context = mock(Context.class); TestConnectionCallbacks callbacks = new TestConnectionCallbacks(); api.connect(context, callbacks); verify(connectionManager).connect(context, callbacks); } |
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public void disconnect() { serviceConnectionManager.disconnect(); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context context); @Ove... | @Test public void disconnect_shouldCallConnectionManager() { api.disconnect(); verify(connectionManager).disconnect(); } |
FusedLocationProviderApiImpl extends ApiImpl implements FusedLocationProviderApi, EventCallbacks, ServiceConnection { public boolean isConnected() { return serviceConnectionManager.isConnected(); } FusedLocationProviderApiImpl(FusedLocationServiceConnectionManager connectionManager); @Override void onConnect(Context co... | @Test public void isConnected_shouldCallConnectionManager() { api.isConnected(); verify(connectionManager).isConnected(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.