method2testcases
stringlengths 118
3.08k
|
---|
### Question:
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 String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }### Answer:
@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); } |
### Question:
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 String name, final String encoding); static String urlEncode(final String s); static String urlDecode(final String s); static String hexStringToString(final String s); static String stringToHexString(final String s); static String byteArrayToHexString(final byte[] bytes); static byte[] hexStringToByteArray(final String s); }### Answer:
@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.available(), result_1.length); } |
### Question:
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 setElementAt(Object o, int index); boolean equals(Object o); int hashCode(); }### Answer:
@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_1, index_1); } catch (IllegalArgumentException e) { return; } fail("testInsertElementAt() should throw an exception."); } |
### Question:
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(Object o, int index); boolean equals(Object o); int hashCode(); }### Answer:
@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_1); } catch (IllegalArgumentException e) { return; } fail("testSetElementAt() should throw an exception."); } |
### Question:
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); lengthExceeded(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); }### Answer:
@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 long test", true, tooLong); } |
### Question:
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); }### Answer:
@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()); instance.addElement("d"); assertEquals("Max length", 3, instance.size()); assertEquals("LRU after length exceeded", "b", instance.firstElement()); } |
### Question:
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); }### Answer:
@Test public void firstGet() { RollingAverage rollingAverage = new RollingAverage(10, 10.0f); assertEquals(10.f, rollingAverage.value(), 0.000001f); } |
### Question:
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 valueIndex = RMSKeyUtils.toValueIndex(hashValue); final byte[] bytes = getValueRS().getRecord(valueIndex); return bytes; } catch (Exception ex) { throw new FlashDatabaseException("Can not getData from RMS: " + Long.toString(digest, 16) + " - " + ex); } } return null; } } RMSFastCache(final char priority, final FlashCache.StartupTask startupTask); void markLeastRecentlyUsed(final Long digest); static void deleteDataFiles(final char priority); String getKey(final long digest); byte[] get(final long digest, final boolean markAsLeastRecentlyUsed); void put(final String key, final byte[] value); void removeData(final long digest); Enumeration getDigests(); void clear(); long getFreespace(); long getSize(); void close(); String toString(); void maintainDatabase(); }### Answer:
@Test(expected = NullPointerException.class) public void nullPointerExceptionThrownWhenGetNullString() throws DigestException, FlashDatabaseException { rmsFastCache.get((String) null); } |
### Question:
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(); synchronized void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }### Answer:
@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.size(), 0); } |
### Question:
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)); } 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(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }### Answer:
@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"); } catch (Exception e) { } assertEquals(instance.size(), 2); for (int i = 0; i < 10000; i++) { instance.put("keykeykey" + i, "valuevaluevalue" + i); } Object val1 = instance.get(key1); if (val1 != null) { assertEquals(val1, expectedVal1); } }
@Test(expected = IllegalArgumentException.class) public void testPutNullValue() { WeakHashCache instance = new WeakHashCache(); instance.put("aKey", null); }
@Test(expected = NullPointerException.class) public void testPutNullKey() { WeakHashCache instance = new WeakHashCache(); instance.put(null, "aValue"); } |
### Question:
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(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(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }### Answer:
@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, value2); assertEquals("get val 1", value1, instance.get(key1)); assertEquals("get val 2", value2, instance.get(key2)); } |
### Question:
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 void put(final Object key, final Object value); synchronized void markContains(final Object key); synchronized boolean remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }### Answer:
@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")); assertEquals(true, instance.containsKey(key1)); try { instance.containsKey(null); fail("Did not throw exception on containsKey(null)"); } catch (Exception e) { } } |
### Question:
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 remove(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }### Answer:
@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()); } |
### Question:
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(final Object key); synchronized boolean containsKey(final Object key); synchronized int size(); synchronized void clear(); synchronized int purgeExpiredWeakReferences(); synchronized void clearValues(); synchronized Object[] getKeys(); }### Answer:
@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.size()); for (int i = 0; i < length; i++) { String key = (String) KEY_CONSTANT + i; assertEquals(null, instance.get(key)); } } |
### Question:
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 boolean getBoolean(final String key); synchronized String getString(final String key); synchronized double getDouble(final String key); synchronized int getInt(final String key); synchronized long getLong(final String key); synchronized JSONObject take(); }### Answer:
@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); } |
### Question:
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); synchronized Object removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }### Answer:
@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."); } |
### Question:
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 (qname.equals("link")) { currentItem.setLink(chars); } else if (qname.equals("pubDate")) { currentItem.setPubDate(chars); } else if (qname.equals("media:thumbnail")) { currentItem.setThumbnail((String) attributes.getValue("url")); } } } catch (Exception e) { L.e("RSS parsing error", "qname=" + qname + " - chars=" + chars, e); } } RSSModel(final int maxLength); synchronized void startElement(final String uri, final String localName, final String qName, final Attributes attributes); synchronized void endElement(final String uri, final String localName, final String qname); synchronized void removeAllElements(); synchronized int size(); synchronized RSSItem elementAt(final int i); final synchronized RSSItem[] copy(RSSItem[] copy); synchronized RSSItem itemNextTo(final RSSItem item, final boolean before); String toString(); }### Answer:
@Test public void testParseElement() throws SAXException { instance.setXML(xml); assertEquals("rss size", 86, instance.size()); } |
### Question:
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 getTimer(); void unchain(); final Object get(); final Task set(final Object value); final Task fork(); static Task[] fork(final Task[] tasks); final Object join(); final Object join(long timeout); static void joinAll(final Task[] tasks); static void joinAll(final Task[] tasks, final long timeout); final int getStatus(); final String getStatusString(); final Task chain(final Task nextTask); final int getForkPriority(); final boolean cancel(final String reason); boolean cancel(final String reason, final Throwable t); final boolean isCanceled(); static String getClassName(final Object o); String getClassName(); Task setClassName(final String name); static Vector getCurrentState(); String toString(); static final int DEDICATED_THREAD_PRIORITY; static final int UI_PRIORITY; static final int FASTLANE_PRIORITY; static final int SERIAL_CURRENT_THREAD_PRIORITY; static final int SERIAL_PRIORITY; static final int HIGH_PRIORITY; static final int NORMAL_PRIORITY; static final int IDLE_PRIORITY; static final int SHUTDOWN_UI; static final int SHUTDOWN; static final Object LARGE_MEMORY_MUTEX; static final int MAX_TIMEOUT; static final int PENDING; static final int FINISHED; static final int CANCELED; static final String QUEUE_LENGTH_EXCEEDED; }### Answer:
@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(100); fail("join() or get() to a Task that was not fork()ed should timeout"); } |
### Question:
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 index); synchronized Object removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }### Answer:
@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."); } |
### Question:
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 removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }### Answer:
@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); assertEquals("Size 2 again", 2, instance.size()); } |
### Question:
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(Object o, int index); synchronized Object removeLeastRecentlyUsed(); synchronized Object getLeastRecentlyUsed(); synchronized boolean contains(Object o); }### Answer:
@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"); Object result_1 = instance.contains("a"); assertEquals("Least recently used", expResult_1, result_1); instance.addElement("a"); instance.contains("b"); Object result_2 = instance.removeLeastRecentlyUsed(); assertEquals("Least recently used", "c", result_2); } |
### Question:
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.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }### Answer:
@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()); } |
### Question:
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 = "Find one product") @GetMapping(value = "/{productId}") Product findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }### Answer:
@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()) .andExpect(content() .json("{}")); } |
### Question:
AccountEntry { public BigDecimal getTotalAmount() { return price.multiply(BigDecimal.valueOf(quantity)); } BigDecimal getTotalAmount(); }### Answer:
@Test public void testTotalAmount() throws Exception { AccountEntry entry = new AccountEntry().setPrice(BigDecimal.ONE).setQuantity(12l); assertThat(entry.getTotalAmount(), is(equalTo(new BigDecimal("12")))); } |
### Question:
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, Long productId, Long quantity, double price); List<StockEntryResponse> pull(Long stockId, Long productId, Long quantity); }### Answer:
@Test public void testRegisterStock() throws Exception { Long stockId = stockService.registerStock(STOCKNAME); assertThat(stockId, is(notNullValue())); } |
### Question:
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, double price); List<StockEntryResponse> pull(Long stockId, Long productId, Long quantity); }### Answer:
@Test public void testFindStock() throws Exception { Long stockId = stockService.registerStock(STOCKNAME); Stock stock = stockService.findStock(stockId); assertThat(stock.getName(), is(STOCKNAME)); } |
### Question:
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(); @ApiOperation("Create new stock") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createStock(@RequestBody @Valid StockRegisterRequest stockRegisterRequest); @ApiOperation("Get stock") @GetMapping(path = "/{stockId}") StockInfo getStock(@PathVariable("stockId") Long stockId); @ApiOperation("Get available product quantities") @GetMapping(path = "/{stockId}/entries") List<StockEntryQuantity> getAvailableProductQuantities(@PathVariable("stockId") Long stockId); @ApiOperation("Receipt products") @PutMapping(path = "/{stockId}/entries") void putToStock(@PathVariable("stockId") Long stockId, @RequestBody @Valid EntryReceiptRequest entry); @ApiOperation("Pull product from stock.") @PostMapping(path = "/{stockId}/entries") List<StockEntryResponse> getPull(@PathVariable("stockId") Long stockId,
@RequestBody @Valid EntryPullRequest entryPullRequest); }### Answer:
@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("{\"stockId\":1,\"name\":\"STOCK_NAME\"}s")); verify(stockService, times(1)).findStock(1l); } |
### Question:
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) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }### Answer:
@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().isOk()) .andExpect(content() .json(CUSTOMER_JSON)); } |
### Question:
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 = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }### Answer:
@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("[]")); } |
### Question:
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()); customerModel.setAddress(customer.getAddress()); customerModel.setEmail(customer.getEmail()); log.debug("Saving customer {}", customerModel); return customerRepository.save(customerModel); } @ApiOperation(value = "Create a new customer.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createCustomer(@Valid @RequestBody Customer customer); @ApiOperation(value = "Find customer by Id.") @GetMapping("/{customerId}") Customer findCustomer(@PathVariable("customerId") long customerId); @ApiOperation("Find all customers.") @GetMapping List<Customer> findAll(); @ApiOperation("Update customer") @PutMapping("/{customerId}") Customer updateCustomer(@PathVariable("customerId") long customerId, @Valid @RequestBody Customer customer); }### Answer:
@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_JSON)).andExpect(status().isOk()); } |
### Question:
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 @RequestBody User user); @ApiOperation(value = "Find all users.") @GetMapping List<UserInfo> findAll(); @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest); }### Answer:
@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()); } |
### Question:
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 (user.getPassword().equals(passwordRequest.getOldPassword())) { user.setPassword(passwordRequest.getNewPassword()); userRepository.save(user); } } } @ApiOperation(value = "Create a new user.") @PostMapping @ResponseStatus(HttpStatus.CREATED) void createUser(@Valid @RequestBody User user); @ApiOperation(value = "Find all users.") @GetMapping List<UserInfo> findAll(); @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest); }### Answer:
@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.APPLICATION_JSON)).andExpect(status().isAccepted()); user.setPassword("ZYX"); verify(userRepository, times(1)) .save(user); } |
### Question:
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.CREATED) void createUser(@Valid @RequestBody User user); @ApiOperation(value = "Find all users.") @GetMapping List<UserInfo> findAll(); @ApiOperation(value = "Change password.") @PutMapping("/{userId}/change-password") @ResponseStatus(HttpStatus.ACCEPTED) void updatePassword(@PathVariable("userId") Long userId, @RequestBody PasswordRequest passwordRequest); }### Answer:
@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)).andExpect(status().isOk()) .andExpect(content() .json(" [{\"id\":null,\"email\":\"[email protected]\",\"name\":\"Name\"},{\"id\":-2,\"email\":\"[email protected]\",\"name\":\"Name2\"}]")); } |
### Question:
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 one product") @GetMapping(value = "/{productId}") Product findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }### Answer:
@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)); } |
### Question:
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()); entity.setDescription(product.getDescription()); entity.setUnit(product.getUnit()); entity.setAmount(product.getAmount()); productRepository.save(entity); } } @ApiOperation(value = "Find all products.") @GetMapping List<Product> findAll(); @ApiOperation(value = "Find one product") @GetMapping(value = "/{productId}") Product findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }### Answer:
@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().isOk()); verify(productRepository, times(1)).save(any(Product.class)); } |
### Question:
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 findOne(@PathVariable("productId") Long productId); @ApiOperation(value = "Create Product") @ResponseStatus(HttpStatus.CREATED) @PostMapping void createProduct(@Valid @RequestBody Product product); @ApiOperation(value = "Update Product") @PutMapping(value = "/{productId}") void updateProduct(@PathVariable("productId") Long productId, @Valid @RequestBody Product product); @ApiOperation(value = "Search Products by Tag.") @GetMapping(params = "tags") List<Product> search(@RequestParam("tags") String[] tags); }### Answer:
@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)) .andExpect(status().isOk()) .andExpect(content() .json("[{\"id\":null,\"version\":null,\"name\":\"PRODUCT_NAME\",\"description\":\"PRODUCT_DESCRIPTION\",\"unit\":\"Liter\",\"amount\":1.0,\"tags\":[]},{\"id\":-2,\"version\":null,\"name\":\"PRODUCT_NAME_2\",\"description\":\"PRODUCT_DESCRIPTION_2\",\"unit\":\"1L\",\"amount\":123.45,\"tags\":[]}]")); } |
### Question:
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); } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); }### Answer:
@Test void sanitizeAcroFormActions() { PDFormFieldAdditionalActions fieldActions = new PDFormFieldAdditionalActions(); fieldActions.setC(new PDActionJavaScript()); fieldActions.setF(new PDActionJavaScript()); fieldActions.setK(new PDActionJavaScript()); fieldActions.setV(new PDActionJavaScript()); instance.sanitizeFieldAdditionalActions(fieldActions); assertThreatsFound(session, 4); assertNull(fieldActions.getC()); assertNull(fieldActions.getF()); assertNull(fieldActions.getK()); assertNull(fieldActions.getV()); reset(session); instance.sanitizeFieldAdditionalActions(fieldActions); assertThreatsFound(session, 0); } |
### Question:
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 = ((DirectoryEntry) entry).getEntryNames(); LOGGER.trace("Macros' entries: {}", entryNames); infos.append("Entries: ").append(entryNames); } else if (entry instanceof DocumentEntry) { int size = ((DocumentEntry) entry).getSize(); infos.append("Size: ").append(size); } Threat threat = Threat.builder() .type(ThreatType.ACTIVE_CONTENT) .severity(ThreatSeverity.EXTREME) .action(ThreatAction.REMOVE) .location(entryName) .details(infos.toString()) .build(); session.recordThreat(threat); return false; } MacroRemover(BleachSession session); @Override boolean test(Entry entry); }### Answer:
@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(Entry.class); doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(entry).getName(); assertTrue(instance.test(entry), "Non-macro streams should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); doReturn("RandomName").when(entry).getName(); assertTrue(instance.test(entry), "Non-macro streams should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); } |
### Question:
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); }### Answer:
@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?"); } |
### Question:
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); }); } }### Answer:
@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); ExcelRecordCleaner.removeObProjRecord(records); assertTrue(records.contains(valid1), "A valid record is not removed"); assertTrue(records.contains(valid2), "A valid record is not removed"); assertFalse(records.contains(obProj1), "The ObProj record is removed"); } |
### Question:
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 SummaryInformation(ps); sanitizeSummaryInformation(session, dsi); } catch (NoPropertySetStreamException | UnexpectedPropertySetTypeException | IOException e) { LOGGER.error("An error occured while trying to sanitize the document entry", e); } } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); }### Answer:
@Test void sanitizeSummaryInformation() { } |
### Question:
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(); Threat threat = Threat.builder() .type(ThreatType.UNRECOGNIZED_CONTENT) .severity(ThreatSeverity.LOW) .action(ThreatAction.REMOVE) .location("Summary Information - Comment") .details("Comment was: '" + comments + "'") .build(); session.recordThreat(threat); } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); }### Answer:
@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); } |
### Question:
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); dsi.removeTemplate(); ThreatSeverity severity = isExternalTemplate(template) ? ThreatSeverity.HIGH : ThreatSeverity.LOW; Threat threat = Threat.builder() .type(ThreatType.EXTERNAL_CONTENT) .severity(severity) .action(ThreatAction.REMOVE) .location("Summary Information - Template") .details("Template was: '" + template + "'") .build(); session.recordThreat(threat); } SummaryInformationSanitiser(BleachSession session); @Override boolean test(Entry entry); }### Answer:
@Test void sanitizeTemplate() { } |
### Question:
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); }### Answer:
@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(instance.isExternalTemplate("http: assertTrue(instance.isExternalTemplate("ftp: } |
### Question:
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 = ((DirectoryEntry) entry).getEntryNames(); LOGGER.trace("Compound Objects' entries: {}", entryNames); infos.append("Entries: ").append(entryNames); } else if (entry instanceof DocumentEntry) { int size = ((DocumentEntry) entry).getSize(); infos.append("Size: ").append(size); } Threat threat = Threat.builder() .type(ThreatType.EXTERNAL_CONTENT) .severity(ThreatSeverity.HIGH) .action(ThreatAction.REMOVE) .location(entryName) .details(infos.toString()) .build(); session.recordThreat(threat); return false; } ObjectRemover(BleachSession session); @Override boolean test(Entry entry); }### Answer:
@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(Entry.class); doReturn(SummaryInformation.DEFAULT_STREAM_NAME).when(entry).getName(); assertTrue(instance.test(entry), "Non-object entries should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); doReturn("RandomName").when(entry).getName(); assertTrue(instance.test(entry), "Non-object entries should be ignored"); BleachTestBase.assertThreatsFound(session, 0); reset(session); } |
### Question:
PDDocumentCatalogBleach { private void sanitizePageActions(PDPageTree pages) throws IOException { LOGGER.trace("Checking Pages Actions"); for (PDPage page : pages) { sanitizePage(page); } } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); }### Answer:
@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); instance.sanitizePageActions(actions); assertThreatsFound(session, 0); } |
### Question:
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); }### Answer:
@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?"); } |
### Question:
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(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session); void sanitize(OPCPackage pkg, BleachSession session); }### Answer:
@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_TYPES) { ct = new ContentType(contentType); assertFalse(instance.isForbiddenType(ct), contentType + " should not be a forbidden type"); } }
@Test @Disabled void remapsMacroEnabledDocumentType() throws InvalidFormatException { ContentType ct; for (String contentType : DYNAMIC_TYPES) { ct = new ContentType(contentType); assertTrue(instance.isForbiddenType(ct), contentType + " should be a forbidden type"); } } |
### Question:
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); @Override String getName(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session); void sanitize(OPCPackage pkg, BleachSession session); }### Answer:
@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(instance.handlesMagic(invalidInputStream3)); } |
### Question:
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); docCatalog.setOpenAction(null); pdfBleachSession.recordJavascriptThreat("Document Catalog", "OpenAction"); } PDDocumentCatalogBleach(PdfBleachSession pdfBleachSession); }### Answer:
@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, atLeastOnce()).setOpenAction(null); assertThreatsFound(session, 1); reset(session); reset(documentCatalog); when(documentCatalog.getOpenAction()).thenReturn(null); instance.sanitizeOpenAction(documentCatalog); verify(documentCatalog, atLeastOnce()).getOpenAction(); verify(documentCatalog, never()).setOpenAction(null); assertThreatsFound(session, 0); } |
### Question:
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.setAction(null); } PDAnnotationBleach(PdfBleachSession pdfBleachSession); }### Answer:
@Test void sanitizeAnnotationLink() { PDAnnotationLink annotationLink = new PDAnnotationLink(); annotationLink.setAction(new PDActionJavaScript()); instance.sanitizeLinkAnnotation(annotationLink); assertThreatsFound(session, 1); assertNull(annotationLink.getAction()); reset(session); instance.sanitizeLinkAnnotation(annotationLink); assertThreatsFound(session, 0); } |
### Question:
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"); annotationWidget.setAction(null); } sanitizeAnnotationActions(annotationWidget.getActions()); } PDAnnotationBleach(PdfBleachSession pdfBleachSession); }### Answer:
@Test void sanitizeAnnotationWidgetAction() { PDAnnotationWidget annotationWidget = new PDAnnotationWidget(); annotationWidget.setAction(new PDActionJavaScript()); instance.sanitizeWidgetAnnotation(annotationWidget); assertThreatsFound(session, 1); assertNull(annotationWidget.getAction()); reset(session); instance.sanitizeWidgetAnnotation(annotationWidget); assertThreatsFound(session, 0); } |
### Question:
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); }### Answer:
@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.handlesMagic(invalidInputStream)); invalidInputStream = new ByteArrayInputStream("Anything".getBytes(charset)); assertFalse(instance.handlesMagic(invalidInputStream)); } |
### Question:
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 session); }### Answer:
@Test void recordingJavascriptThreatWorks() { instance.recordJavascriptThreat("", ""); assertThreatsFound(session, 1); } |
### Question:
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 String getName(); @Override void sanitize(InputStream inputStream, OutputStream outputStream, BleachSession session); }### Answer:
@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(instance.handlesMagic(invalidInputStream)); } |
### Question:
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(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }### Answer:
@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)); Assert.assertEquals(new Position(0, 1), p2); Assert.assertEquals(new Position(0, 1), p3); } |
### Question:
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 toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }### Answer:
@Test public void PositionOstream() { Position p1 = new Position(2, -3); Assert.assertEquals("[2, -3]", p1.toString()); } |
### Question:
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(); static final Altitude UNINITIALIZED; static final Altitude ZERO; }### Answer:
@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()); Assert.assertEquals(1, map.get(new Altitude(1)).intValue()); Assert.assertEquals(2, map.get(new Altitude(2)).intValue()); Assert.assertEquals(3, map.get(new Altitude(3)).intValue()); Assert.assertEquals(4, map.get(new Altitude(4)).intValue()); Assert.assertNotEquals(1, map.get(new Altitude(0)).intValue()); Assert.assertNotEquals(4, map.get(new Altitude(1)).intValue()); Assert.assertNotEquals(3, map.get(new Altitude(2)).intValue()); Assert.assertNotEquals(4, map.get(new Altitude(3)).intValue()); Assert.assertNotEquals(8, map.get(new Altitude(4)).intValue()); } |
### Question:
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 getX(); int getY(); TilePosition toTilePosition(); Position toPosition(); WalkPosition add(WalkPosition walkPosition); WalkPosition subtract(WalkPosition walkPosition); WalkPosition multiply(WalkPosition walkPosition); WalkPosition divide(WalkPosition walkPosition); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); static final int SIZE_IN_PIXELS; }### Answer:
@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 WalkPosition(0, 0))); Assert.assertTrue(list.contains(new WalkPosition(24, 87))); Assert.assertTrue(list.contains(new WalkPosition(48, 39))); Assert.assertTrue(list.contains(new WalkPosition(361, 92))); Assert.assertTrue(list.contains(new WalkPosition(510, 6))); } |
### Question:
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; } @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 toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }### Answer:
@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)); } |
### Question:
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 getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }### Answer:
@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); } |
### Question:
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(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }### Answer:
@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 Position(-1, -2), p3); } |
### Question:
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(); int getY(); int getDistance(final Position position); TilePosition toTilePosition(); WalkPosition toWalkPosition(); Position add(final Position position); Position subtract(final Position position); Position multiply(final Position position); Position divide(final Position position); @Override String toString(); @Override boolean equals(final Object object); @Override int hashCode(); }### Answer:
@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 Position(1, 1)); Assert.assertEquals(new Position(2, 4), p2); Assert.assertEquals(new Position(2, 4), p3); } |
### Question:
LostApiClientImpl implements LostApiClient { @Override public boolean isConnected() { return getGeofencingImpl().isConnected() && getSettingsApiImpl().isConnected() && getFusedLocationProviderApiImpl().isConnected() && clientManager.containsClient(this); } LostApiClientImpl(Context context, ConnectionCallbacks callbacks,
ClientManager clientManager); @Override void connect(); @Override void disconnect(); @Override boolean isConnected(); }### Answer:
@Test public void isConnected_shouldReturnFalseBeforeConnected() throws Exception { assertThat(client.isConnected()).isFalse(); } |
### Question:
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 millis); float getSmallestDisplacement(); LocationRequest setSmallestDisplacement(float meters); int getPriority(); LocationRequest setPriority(int priority); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final int PRIORITY_HIGH_ACCURACY; static final int PRIORITY_BALANCED_POWER_ACCURACY; static final int PRIORITY_LOW_POWER; static final int PRIORITY_NO_POWER; static final Parcelable.Creator<LocationRequest> CREATOR; }### Answer:
@Test public void getPriority_shouldReturnDefaultValue() throws Exception { assertThat(locationRequest.getPriority()).isEqualTo(PRIORITY_BALANCED_POWER_ACCURACY); } |
### Question:
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); } this.priority = priority; return this; } private LocationRequest(); protected LocationRequest(Parcel in); static LocationRequest create(); long getInterval(); LocationRequest setInterval(long millis); long getFastestInterval(); LocationRequest setFastestInterval(long millis); float getSmallestDisplacement(); LocationRequest setSmallestDisplacement(float meters); int getPriority(); LocationRequest setPriority(int priority); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final int PRIORITY_HIGH_ACCURACY; static final int PRIORITY_BALANCED_POWER_ACCURACY; static final int PRIORITY_LOW_POWER; static final int PRIORITY_NO_POWER; static final Parcelable.Creator<LocationRequest> CREATOR; }### Answer:
@Test(expected = IllegalArgumentException.class) public void setPriority_shouldRejectInvalidValues() throws Exception { locationRequest.setPriority(-1); } |
### Question:
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); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request,
LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request,
PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request,
LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context,
final Location location, final LocationAvailability availability,
final LocationResult result); @Override ReportedChanges reportLocationResult(Location location,
final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }### Answer:
@Test public void shouldHaveZeroClientCount() { assertThat(manager.numberOfClients()).isEqualTo(0); } |
### Question:
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(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request,
LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request,
PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request,
LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context,
final Location location, final LocationAvailability availability,
final LocationResult result); @Override ReportedChanges reportLocationResult(Location location,
final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void addListener_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addListener(client, LocationRequest.create(), new TestLocationListener()); } |
### Question:
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); } LostClientManager(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request,
LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request,
PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request,
LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context,
final Location location, final LocationAvailability availability,
final LocationResult result); @Override ReportedChanges reportLocationResult(Location location,
final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void addPendingIntent_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addPendingIntent(client, LocationRequest.create(), mock(PendingIntent.class)); } |
### Question:
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); callbackToLocationRequests.put(callback, request); } LostClientManager(); static LostClientManager shared(); @Override void addClient(LostApiClient client); @Override void removeClient(LostApiClient client); @Override boolean containsClient(LostApiClient client); @Override int numberOfClients(); @Override void addListener(LostApiClient client, LocationRequest request,
LocationListener listener); @Override void addPendingIntent(LostApiClient client, LocationRequest request,
PendingIntent callbackIntent); @Override void addLocationCallback(LostApiClient client, LocationRequest request,
LocationCallback callback, Looper looper); @Override boolean removeListener(LostApiClient client, LocationListener listener); @Override boolean removePendingIntent(LostApiClient client, PendingIntent callbackIntent); @Override boolean removeLocationCallback(LostApiClient client, LocationCallback callback); @Override ReportedChanges reportLocationChanged(final Location location); @Override ReportedChanges sendPendingIntent(final Context context,
final Location location, final LocationAvailability availability,
final LocationResult result); @Override ReportedChanges reportLocationResult(Location location,
final LocationResult result); @Override void updateReportedValues(ReportedChanges changes); @Override void notifyLocationAvailability(final LocationAvailability availability); @Override boolean hasNoListeners(); @Override Map<LostApiClient, Set<LocationListener>> getLocationListeners(); @Override Map<LostApiClient, Set<PendingIntent>> getPendingIntents(); @Override Map<LostApiClient, Set<LocationCallback>> getLocationCallbacks(); }### Answer:
@Test(expected = IllegalArgumentException.class) public void addLocationCallback_shouldThrowExceptionIfClientWasNotAdded() throws Exception { manager.addLocationCallback(client, LocationRequest.create(), new TestLocationCallback(), mock(Looper.class)); } |
### Question:
FusedLocationProviderServiceDelegate implements LocationEngine.Callback { public Location getLastLocation() { return locationEngine.getLastLocation(); } FusedLocationProviderServiceDelegate(Context context); void init(IFusedLocationProviderCallback callback); Location getLastLocation(); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) LocationAvailability getLocationAvailability(); void requestLocationUpdates(LocationRequest request); void removeLocationUpdates(); void setMockMode(boolean isMockMode); void setMockLocation(Location mockLocation); void setMockTrace(String path, String filename); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportLocation(Location location); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderDisabled(String provider); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderEnabled(String provider); }### Answer:
@Test public void getLastLocation_shouldReturnMostRecentLocation() throws Exception { Location location = new Location(GPS_PROVIDER); shadowLocationManager.setLastKnownLocation(GPS_PROVIDER, location); assertThat(delegate.getLastLocation()).isNotNull(); } |
### Question:
FusedLocationProviderServiceDelegate implements LocationEngine.Callback { public void requestLocationUpdates(LocationRequest request) { locationEngine.setRequest(request); } FusedLocationProviderServiceDelegate(Context context); void init(IFusedLocationProviderCallback callback); Location getLastLocation(); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) LocationAvailability getLocationAvailability(); void requestLocationUpdates(LocationRequest request); void removeLocationUpdates(); void setMockMode(boolean isMockMode); void setMockLocation(Location mockLocation); void setMockTrace(String path, String filename); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportLocation(Location location); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderDisabled(String provider); @RequiresPermission(anyOf = {ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION}) void reportProviderEnabled(String provider); }### Answer:
@Test public void requestLocationUpdates_shouldRegisterGpsAndNetworkListener() throws Exception { delegate.requestLocationUpdates(LocationRequest.create().setPriority(PRIORITY_HIGH_ACCURACY)); assertThat(shadowLocationManager.getRequestLocationUpdateListeners()).hasSize(2); }
@Test public void requestLocationUpdates_shouldRegisterGpsAndNetworkListenerViaPendingIntent() throws Exception { delegate.requestLocationUpdates(LocationRequest.create().setPriority(PRIORITY_HIGH_ACCURACY)); assertThat(shadowLocationManager.getRequestLocationUpdateListeners()).hasSize(2); } |
### Question:
SystemClock implements Clock { public static long getTimeInNanos(Location location) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { return location.getElapsedRealtimeNanos(); } return location.getTime() * MS_TO_NS; } @Override long getCurrentTimeInMillis(); static long getTimeInNanos(Location location); static final long MS_TO_NS; }### Answer:
@Test @Config(sdk = 17) public void getTimeInNanos_shouldReturnElapsedRealtimeNanosForSdk17AndUp() throws Exception { final long nanos = 1000000; final Location location = new Location("mock"); location.setElapsedRealtimeNanos(nanos); assertThat(SystemClock.getTimeInNanos(location)).isEqualTo(nanos); }
@Test @Config(sdk = 16) public void getTimeInNanos_shouldUseUtcTimeInMillisForSdk16AndLower() throws Exception { final long millis = 1000; final Location location = new Location("mock"); location.setTime(millis); assertThat(SystemClock.getTimeInNanos(location)).isEqualTo(millis * MS_TO_NS); } |
### Question:
ResourceUtil { public static InputStream getResourceAsStream(String path) { if (StrUtil.startWithIgnoreCase(path, CLASSPATH_PRE)) { path = path.substring(CLASSPATH_PRE.length()); } return getClassLoader().getResourceAsStream(path); } static String getAbsolutePath(String path); static URL getResource(String path); static InputStream getResourceAsStream(String path); }### Answer:
@Test public void getResourceAsStreamTest() { InputStream resourceAsStream = ResourceUtil.getResourceAsStream("classpath:config/tio-quartz.properties"); Assert.assertNotNull(resourceAsStream); try { resourceAsStream.close(); } catch (IOException e) { } } |
### Question:
ByteKit { public static byte[][] split(byte[] raw, int partSize) { int length = raw.length % partSize == 0 ? raw.length / partSize : ((int) (raw.length / partSize)) + 1; byte[][] parts = new byte[length][]; int start = 0; for (int i = 0; i < length; i++) { int end = Integer.min(raw.length, start + partSize); parts[i] = Arrays.copyOfRange(raw, start, end); start = end; } return parts; } static byte[][] split(byte[] raw, int partSize); }### Answer:
@Test public void split() { byte[] bytes1 = new byte[12781]; for (int i = 0; i < bytes1.length; i++) { bytes1[i] = (byte) (256 * Math.random()); } byte[][] parts1 = ByteKit.split(bytes1, 1); assertEquals(parts1.length, bytes1.length); Byte[] combine1 = Arrays.stream(parts1).map(it -> it[0]).toArray(Byte[]::new); for (int i = 0; i < combine1.length; i++) { assertEquals((byte) combine1[i], bytes1[i]); } byte[][] parts2 = ByteKit.split(bytes1, 11); assertEquals( parts2.length, bytes1.length % 11 == 0 ? bytes1.length / 11 : bytes1.length / 11 + 1); Byte[] combine2 = Arrays.stream(parts2) .flatMap( part -> { List<Byte> bytes = new ArrayList<>(); for (byte b : part) { bytes.add(b); } return bytes.stream(); }) .toArray(Byte[]::new); for (int i = 0; i < combine2.length; i++) { assertEquals((byte) combine2[i], bytes1[i]); } } |
### Question:
UnifiedDiffWriter { public static void write(UnifiedDiff diff, Function<String, List<String>> originalLinesProvider, Writer writer, int contextSize) throws IOException { Objects.requireNonNull(originalLinesProvider, "original lines provider needs to be specified"); write(diff, originalLinesProvider, line -> { try { writer.append(line).append("\n"); } catch (IOException ex) { LOG.log(Level.SEVERE, null, ex); } }, contextSize); } static void write(UnifiedDiff diff, Function<String, List<String>> originalLinesProvider, Writer writer, int contextSize); static void write(UnifiedDiff diff, Function<String, List<String>> originalLinesProvider, Consumer<String> writer, int contextSize); }### Answer:
@Test public void testWrite() throws URISyntaxException, IOException { String str = readFile(UnifiedDiffReaderTest.class.getResource("jsqlparser_patch_1.diff").toURI(), Charset.defaultCharset()); UnifiedDiff diff = UnifiedDiffReader.parseUnifiedDiff(new ByteArrayInputStream(str.getBytes())); StringWriter writer = new StringWriter(); UnifiedDiffWriter.write(diff, f -> Collections.EMPTY_LIST, writer, 5); System.out.println(writer.toString()); }
@Test public void testWriteWithNewFile() throws URISyntaxException, IOException { List<String> original = new ArrayList<>(); List<String> revised = new ArrayList<>(); revised.add("line1"); revised.add("line2"); Patch<String> patch = DiffUtils.diff(original, revised); UnifiedDiff diff = new UnifiedDiff(); diff.addFile( UnifiedDiffFile.from(null, "revised", patch) ); StringWriter writer = new StringWriter(); UnifiedDiffWriter.write(diff, f -> original, writer, 5); System.out.println(writer.toString()); String[] lines = writer.toString().split("\\n"); assertEquals("--- /dev/null", lines[0]); assertEquals("+++ revised", lines[1]); assertEquals("@@ -0,0 +1,2 @@", lines[2]); } |
### Question:
StringUtils { public static String htmlEntites(String str) { return str.replace("<", "<").replace(">", ">"); } private StringUtils(); static String htmlEntites(String str); static String normalize(String str); static List<String> wrapText(List<String> list, int columnWidth); static String wrapText(String line, int columnWidth); }### Answer:
@Test public void testHtmlEntites() { assertEquals("<test>", StringUtils.htmlEntites("<test>")); } |
### Question:
StringUtils { public static String normalize(String str) { return htmlEntites(str).replace("\t", " "); } private StringUtils(); static String htmlEntites(String str); static String normalize(String str); static List<String> wrapText(List<String> list, int columnWidth); static String wrapText(String line, int columnWidth); }### Answer:
@Test public void testNormalize_String() { assertEquals(" test", StringUtils.normalize("\ttest")); } |
### Question:
StringUtils { public static List<String> wrapText(List<String> list, int columnWidth) { return list.stream() .map(line -> wrapText(line, columnWidth)) .collect(toList()); } private StringUtils(); static String htmlEntites(String str); static String normalize(String str); static List<String> wrapText(List<String> list, int columnWidth); static String wrapText(String line, int columnWidth); }### Answer:
@Test public void testWrapText_String_int() { assertEquals("te<br/>st", StringUtils.wrapText("test", 2)); assertEquals("tes<br/>t", StringUtils.wrapText("test", 3)); assertEquals("test", StringUtils.wrapText("test", 10)); }
@Test public void testWrapText_String_int_zero() { Assertions.assertThrows(IllegalArgumentException.class, () -> StringUtils.wrapText("test", -1)); } |
### Question:
UnifiedDiffReader { static String[] parseFileNames(String line) { String[] split = line.split(" "); return new String[]{ split[2].replaceAll("^a/", ""), split[3].replaceAll("^b/", "") }; } UnifiedDiffReader(Reader reader); static UnifiedDiff parseUnifiedDiff(InputStream stream); }### Answer:
@Test public void testParseDiffBlock() { String[] files = UnifiedDiffReader.parseFileNames("diff --git a/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java b/src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java"); assertThat(files).containsExactly("src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java", "src/test/java/net/sf/jsqlparser/statement/select/SelectTest.java"); } |
### Question:
StringUtils { public static String wrapString(String str) { return wrapString(str, MAX_LENGTH); } static String StringAsHtmlWrapString(String string); static String wrapString(String str); static String wrapString(String str, int maxWidth); static List<String> wrap(String str, int maxWidth); static void wrapLineInto(String line, List<String> list, int maxWidth); static int findBreakBefore(String line, int start); static int findBreakAfter(String line, int start); static List<String> splitIntoLines(String str); }### Answer:
@Test public void testWrapString() { LOG.info("wrapString"); String str = "This filter is responsible to check whether the time difference between each pair of gps points contained by a gps track does not exceed a given threshold. if there is a pair of gps point where the time difference exceed the specified the track get seperated into two segement and the filter continues the filtering process with the second segment until the end of the gps track is reached."; int maxWidth = 60; LOG.info(StringUtils.wrapString(str, maxWidth)); } |
### Question:
Lex { public static void init(@NonNull Application app) { init(app, LexContext.OPEN_DELIMITER, LexContext.CLOSE_DELIMITER); } static void init(@NonNull Application app); static void init(@NonNull Application app, @NonNull String openDelimiter, @NonNull String closeDelimiter); @NonNull static UnparsedLexString say(@StringRes int resourceId); @NonNull static UnparsedLexString say(@NonNull CharSequence template); @NonNull static LexList list(@NonNull List<? extends CharSequence> items); @NonNull static LexList list(@NonNull CharSequence... text); }### Answer:
@Test(expected = LexAlreadyInitializedException.class) public void init_throwsException_onSecondInvocation() { Lex.init(RuntimeEnvironment.application); } |
### Question:
ScriptAnalyzerRulesDefinition implements RulesDefinition { public void define(final Context context) { final String repositoryKey = ScriptAnalyzerRulesDefinition.getRepositoryKeyForLanguage(); final String repositoryName = ScriptAnalyzerRulesDefinition.getRepositoryNameForLanguage(); defineRulesForLanguage(context, repositoryKey, repositoryName, PowershellLanguage.KEY); } void define(final Context context); static String getRepositoryKeyForLanguage(); static String getRepositoryNameForLanguage(); }### Answer:
@Test public void testDefine() { Context t = new RulesDefinition.Context(); ScriptAnalyzerRulesDefinition def = new ScriptAnalyzerRulesDefinition(); def.define(t); Assert.assertEquals(1, t.repository(ScriptAnalyzerRulesDefinition.getRepositoryKeyForLanguage()).rules().size()); } |
### Question:
DictionaryLookup implements IStemmer, Iterable<WordData> { public static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements) { StringBuilder sb = new StringBuilder(word); for (final Map.Entry<String, String> e : replacements.entrySet()) { String key = e.getKey(); int index = sb.indexOf(e.getKey()); while (index != -1) { sb.replace(index, index + key.length(), e.getValue()); index = sb.indexOf(key, index + key.length()); } } return sb.toString(); } DictionaryLookup(Dictionary dictionary); @Override List<WordData> lookup(CharSequence word); static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements); @Override Iterator<WordData> iterator(); Dictionary getDictionary(); char getSeparatorChar(); }### Answer:
@Test public void testApplyReplacements() { LinkedHashMap<String, String> conversion = new LinkedHashMap<>(); conversion.put("'", "`"); conversion.put("fi", "fi"); conversion.put("\\a", "ą"); conversion.put("Barack", "George"); conversion.put("_", "xx"); assertEquals("filut", DictionaryLookup.applyReplacements("filut", conversion)); assertEquals("fizdrygałką", DictionaryLookup.applyReplacements("fizdrygałk\\a", conversion)); assertEquals("George Bush", DictionaryLookup.applyReplacements("Barack Bush", conversion)); assertEquals("xxxxxxxx", DictionaryLookup.applyReplacements("____", conversion)); } |
### Question:
Speller { public boolean isCamelCase(final String str) { return isNotEmpty(str) && !isAllUppercase(str) && isNotCapitalizedWord(str) && Character.isUpperCase(str.charAt(0)) && (!(str.length() > 1) || Character.isLowerCase(str.charAt(1))) && isNotAllLowercase(str); } Speller(final Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; }### Answer:
@Test public void testCamelCase() { final Speller spell = new Speller(dictionary, 1); assertTrue(spell.isCamelCase("CamelCase")); assertTrue(!spell.isCamelCase("Camel")); assertTrue(!spell.isCamelCase("CAMEL")); assertTrue(!spell.isCamelCase("camel")); assertTrue(!spell.isCamelCase("cAmel")); assertTrue(!spell.isCamelCase("CAmel")); assertTrue(!spell.isCamelCase("")); assertTrue(!spell.isCamelCase(null)); } |
### Question:
Speller { boolean isNotCapitalizedWord(final String str) { if (isNotEmpty(str) && Character.isUpperCase(str.charAt(0))) { for (int i = 1; i < str.length(); i++) { char c = str.charAt(i); if (Character.isLetter(c) && !Character.isLowerCase(c)) { return true; } } return false; } return true; } Speller(final Dictionary dictionary); Speller(final Dictionary dictionary, final int editDistance); boolean isMisspelled(final String word); boolean isInDictionary(final CharSequence word); int getFrequency(final CharSequence word); List<CandidateData> replaceRunOnWordCandidates(final String original); List<String> replaceRunOnWords(final String original); ArrayList<CandidateData> findSimilarWordCandidates(String word); ArrayList<String> findSimilarWords(String word); ArrayList<String> findReplacements(String word); ArrayList<CandidateData> findReplacementCandidates(String word); int ed(final int i, final int j, final int wordIndex, final int candIndex); int cuted(final int depth, final int wordIndex, final int candIndex); boolean isCamelCase(final String str); boolean convertsCase(); List<String> getAllReplacements(final String str, final int fromIndex, final int level); final int getWordLen(); final int getCandLen(); final int getEffectiveED(); static final int MAX_WORD_LENGTH; }### Answer:
@Test public void testCapitalizedWord() { final Speller spell = new Speller(dictionary, 1); assertTrue(spell.isNotCapitalizedWord("CamelCase")); assertTrue(!spell.isNotCapitalizedWord("Camel")); assertTrue(spell.isNotCapitalizedWord("CAMEL")); assertTrue(spell.isNotCapitalizedWord("camel")); assertTrue(spell.isNotCapitalizedWord("cAmel")); assertTrue(spell.isNotCapitalizedWord("CAmel")); assertTrue(spell.isNotCapitalizedWord("")); } |
### Question:
HMatrix { public int get(final int i, final int j) { return p[(j - i + editDistance + 1) * rowLength + j]; } HMatrix(final int distance, final int maxLength); int get(final int i, final int j); void set(final int i, final int j, final int val); }### Answer:
@Test public void stressTestInit() { for (int i = 0; i < 10; i++) { HMatrix H = new HMatrix(i, MAX_WORD_LENGTH); assertEquals(0, H.get(1, 1)); } } |
### Question:
FSABuilder { public static FSA build(byte[][] input) { final FSABuilder builder = new FSABuilder(); for (byte[] chs : input) { builder.add(chs, 0, chs.length); } return builder.complete(); } FSABuilder(); FSABuilder(int bufferGrowthSize); void add(byte[] sequence, int start, int len); FSA complete(); static FSA build(byte[][] input); static FSA build(Iterable<byte[]> input); Map<InfoEntry, Object> getInfo(); static final Comparator<byte[]> LEXICAL_ORDERING; }### Answer:
@Test public void testEmptyInput() { byte[][] input = {}; checkCorrect(input, FSABuilder.build(input)); }
@Test public void testHashResizeBug() throws Exception { byte[][] input = { { 0, 1 }, { 0, 2 }, { 1, 1 }, { 2, 1 }, }; FSA fsa = FSABuilder.build(input); checkCorrect(input, FSABuilder.build(input)); checkMinimal(fsa); }
@Test public void testSmallInput() throws Exception { byte[][] input = { "abc".getBytes("UTF-8"), "bbc".getBytes("UTF-8"), "d".getBytes("UTF-8"), }; checkCorrect(input, FSABuilder.build(input)); }
@Test public void testRandom25000_largerAlphabet() { FSA fsa = FSABuilder.build(input); checkCorrect(input, fsa); checkMinimal(fsa); }
@Test public void testRandom25000_smallAlphabet() throws IOException { FSA fsa = FSABuilder.build(input2); checkCorrect(input2, fsa); checkMinimal(fsa); } |
### Question:
DictionaryLookup implements IStemmer, Iterable<WordData> { public char getSeparatorChar() { return separatorChar; } DictionaryLookup(Dictionary dictionary); @Override List<WordData> lookup(CharSequence word); static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements); @Override Iterator<WordData> iterator(); Dictionary getDictionary(); char getSeparatorChar(); }### Answer:
@Test public void testGetSeparator() throws IOException { final URL url = this.getClass().getResource("test-separators.dict"); final DictionaryLookup s = new DictionaryLookup(Dictionary.read(url)); assertEquals('+', s.getSeparatorChar()); } |
### Question:
Dictionary { public static Dictionary read(Path location) throws IOException { final Path metadata = DictionaryMetadata.getExpectedMetadataLocation(location); try (InputStream fsaStream = Files.newInputStream(location); InputStream metadataStream = Files.newInputStream(metadata)) { return read(fsaStream, metadataStream); } } Dictionary(FSA fsa, DictionaryMetadata metadata); static Dictionary read(Path location); static Dictionary read(URL dictURL); static Dictionary read(InputStream fsaStream, InputStream metadataStream); final FSA fsa; final DictionaryMetadata metadata; }### Answer:
@Test public void testReadFromFile() throws IOException { Path tempDir = super.newTempDir(); Path dict = tempDir.resolve("odd name.dict"); Path info = dict.resolveSibling("odd name.info"); try (InputStream dictInput = this.getClass().getResource("test-infix.dict").openStream(); InputStream infoInput = this.getClass().getResource("test-infix.info").openStream()) { Files.copy(dictInput, dict); Files.copy(infoInput, info); } assertNotNull(Dictionary.read(dict.toUri().toURL())); assertNotNull(Dictionary.read(dict)); } |
### Question:
Destination { @NotNull protected final MultiverseCoreAPI getApi() { return this.api; } protected Destination(@NotNull MultiverseCoreAPI coreAPI); abstract void teleport(@NotNull Permissible teleporter, @NotNull Entity teleportee); @Override String toString(); }### Answer:
@Test public void testGetApi() throws Exception { assertSame(api, basicDestination.getApi()); } |
### Question:
DestinationRegistry { @Nullable DestinationFactory getDestinationFactory(@NotNull String prefix) { return prefixFactoryMap.get(prefix); } DestinationRegistry(@NotNull final MultiverseCoreAPI api); void registerDestinationFactory(@NotNull DestinationFactory destinationFactory); @NotNull Destination parseDestination(@NotNull final String destinationString); }### Answer:
@Test public void testGetDefaultDestinationFactories() { for (String prefix : CannonDestination.PREFIXES) { assertNotNull(registry.getDestinationFactory(prefix)); } for (String prefix : ExactDestination.PREFIXES) { assertNotNull(registry.getDestinationFactory(prefix)); } for (String prefix : PlayerDestination.PREFIXES) { assertNotNull(registry.getDestinationFactory(prefix)); } for (String prefix : WorldDestination.PREFIXES) { assertNotNull(registry.getDestinationFactory(prefix)); } } |
### Question:
DestinationRegistry { @NotNull public Destination parseDestination(@NotNull final String destinationString) throws InvalidDestinationException { String[] destParts = destinationString.split(":", 2); if (destParts.length == 1) { return worldDestinationFactory.createDestination(api, destinationString); } DestinationFactory destinationFactory = getDestinationFactory(destParts[0]); if (destinationFactory != null) { return destinationFactory.createDestination(api, destinationString); } return new UnknownDestination(api, this, getRegistrationCount(), destinationString); } DestinationRegistry(@NotNull final MultiverseCoreAPI api); void registerDestinationFactory(@NotNull DestinationFactory destinationFactory); @NotNull Destination parseDestination(@NotNull final String destinationString); }### Answer:
@Test public void testParseWorldDestinations() throws Exception { Destination dest = registry.parseDestination("someworld"); assertNotNull(dest); assertEquals(WorldDestination.class, dest.getClass()); assertEquals("world:someworld", dest.getDestinationString()); dest = registry.parseDestination(":"); assertNotNull(dest); assertEquals(UnknownDestination.class, dest.getClass()); dest = registry.parseDestination(""); assertNotNull(dest); assertEquals(WorldDestination.class, dest.getClass()); assertEquals("world:", dest.getDestinationString()); }
@Test public void testParseInvalidDestinations() throws Exception { Destination dest = registry.parseDestination("blafhga:fff"); assertNotNull(dest); assertEquals(UnknownDestination.class, dest.getClass()); dest = registry.parseDestination(":::::::"); assertNotNull(dest); assertEquals(UnknownDestination.class, dest.getClass()); }
@Test public void testParseExtraColonsDestinations() throws Exception { Destination dest = registry.parseDestination("world:some:world"); assertNotNull(dest); assertEquals(WorldDestination.class, dest.getClass()); assertEquals("world:some:world", dest.getDestinationString()); } |
### Question:
DestinationRegistry { int getRegistrationCount() { return prefixFactoryMap.size(); } DestinationRegistry(@NotNull final MultiverseCoreAPI api); void registerDestinationFactory(@NotNull DestinationFactory destinationFactory); @NotNull Destination parseDestination(@NotNull final String destinationString); }### Answer:
@Test public void testGetRegistrationCount() throws Exception { int originalCount = registry.getRegistrationCount(); registry.registerDestinationFactory(new TestDestination.Factory()); assertEquals(originalCount + TestDestination.PREFIXES.size(), registry.getRegistrationCount()); } |
### Question:
ExactDestination extends SimpleDestination { @Override @NotNull protected EntityCoordinates getDestination() { return this.coordinates; } ExactDestination(@NotNull MultiverseCoreAPI api, @NotNull EntityCoordinates coords); @Override String getDestinationString(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testValidDestinationStrings() throws Exception { for (String validDestination : validDestinations) { ExactDestination dest = factory.createDestination(api, validDestination); assertEquals(ExactDestination.class, dest.getClass()); assertNotNull(dest.getDestination()); } }
@Test public void testTeleportLocation() throws Exception { BasePlayer player = api.getServerInterface().getPlayer("Player"); assertNotNull(player); ExactDestination dest = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); assertNotEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); dest.teleport(player, (Entity) player); assertEquals(dest.getDestination(), ((Entity) player).getLocation()); assertEquals(1, ((Entity) player).getVelocity().length(), 0.00001); } |
### Question:
ExactDestination extends SimpleDestination { @Override public boolean equals(final Object o) { return this == o || ((o != null) && (getClass() == o.getClass()) && Locations.equal(this.coordinates, ((ExactDestination) o).coordinates)); } ExactDestination(@NotNull MultiverseCoreAPI api, @NotNull EntityCoordinates coords); @Override String getDestinationString(); @Override boolean equals(final Object o); @Override int hashCode(); }### Answer:
@Test public void testEquals() throws Exception { ExactDestination a = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); ExactDestination b = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50.5, 50, 50.5, 0, 0)); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); b = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50, 50, 50.5, 0, 0)); assertFalse(a.equals(b)); assertFalse(b.equals(a)); a = new ExactDestination(api, Locations.getEntityCoordinates("someworld", UUID.randomUUID(), 50, 50, 50.5, 0, 0)); assertTrue(a.equals(b)); assertTrue(b.equals(a)); assertFalse(a.equals(null)); assertFalse(b.equals(null)); } |
### Question:
DestinationUtil { static String colonJoin(Object... args) { StringBuilder builder = new StringBuilder(args[0].toString()); for (int i = 1; i < args.length; i++) builder.append(':').append(args[i].toString()); return builder.toString(); } private DestinationUtil(); }### Answer:
@Test public void testColonJoin() throws Exception { String joined = colonJoin("", "", ""); assertEquals("::", joined); joined = colonJoin("a", "b", "c"); assertEquals("a:b:c", joined); joined = colonJoin("d", "e"); assertEquals("d:e", joined); } |
### Question:
Destination { @NotNull protected final SafeTeleporter getSafeTeleporter() { return getApi().getSafeTeleporter(); } protected Destination(@NotNull MultiverseCoreAPI coreAPI); abstract void teleport(@NotNull Permissible teleporter, @NotNull Entity teleportee); @Override String toString(); }### Answer:
@Test public void testGetSafeTeleporter() throws Exception { assertSame(api.getSafeTeleporter(), basicDestination.getSafeTeleporter()); } |
### Question:
DestinationUtil { @NotNull static String removePrefix(@NotNull String destinationString) { String[] parts = destinationString.split(":", 2); return parts.length == 1 ? destinationString : parts[1]; } private DestinationUtil(); }### Answer:
@Test public void testRemovePrefix() throws Exception { String removedPrefix = removePrefix("test"); assertEquals("test", removedPrefix); removedPrefix = removePrefix("test:blah"); assertEquals("blah", removedPrefix); removedPrefix = removePrefix("test:blah:bloo"); assertEquals("blah:bloo", removedPrefix); } |
### Question:
CannonDestination extends SimpleDestination { @NotNull @Override protected EntityCoordinates getDestination() throws TeleportException { if (coordinates != null) { return this.coordinates; } else { throw new TeleportException(Message.bundleMessage(Language.Destination.Cannon.LAUNCH_ONLY, getDestinationString())); } } CannonDestination(@NotNull MultiverseCoreAPI api, @Nullable EntityCoordinates coordinates, double speed); @Override @NotNull String getDestinationString(); @Override void teleport(@NotNull Permissible teleporter, @NotNull Entity teleportee); @Override boolean equals(final Object o); @Override int hashCode(); double getLaunchSpeed(); }### Answer:
@Test public void testGetSpecificDestination() throws Exception { assertNotNull(factory.createDestination(api, "cannon:someworld:5:5.3:5.4:3:3:4").getDestination()); }
@Test(expected = TeleportException.class) public void testGetLaunchDestination() throws Exception { CannonDestination dest = factory.createDestination(api, "cannon:5"); dest.getDestination(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.