method2testcases stringlengths 118 3.08k |
|---|
### Question:
Util { static String stripLeadingAndTrailingQuotes(String str) { int length = str.length(); if (length > 1 && str.startsWith("\"") && str.endsWith("\"") && str.substring(1, length - 1).indexOf('"') == -1) { str = str.substring(1, length - 1); } return str; } }### Answer:
@Test public void testStripLeadingAndTrailingQuotes() { assertEquals("foo", Util.stripLeadingAndTrailingQuotes("\"foo\"")); assertEquals("foo \"bar\"", Util.stripLeadingAndTrailingQuotes("foo \"bar\"")); assertEquals("\"foo\" bar", Util.stripLeadingAndTrailingQuotes("\"foo\" bar")); assertEquals("\"foo\" and \"bar\"", Util.stripLeadingAndTrailingQuotes("\"foo\" and \"bar\"")); assertEquals("\"", Util.stripLeadingAndTrailingQuotes("\"")); } |
### Question:
Option implements Cloneable, Serializable { @Override public Object clone() { try { Option option = (Option) super.clone(); option.values = new ArrayList<String>(values); return option; } catch (CloneNotSupportedException cnse) { throw new RuntimeException("A CloneNotSupportedException was thrown: " + cnse.getMessage()); } } private Option(final Builder builder); Option(String opt, String description); Option(String opt, boolean hasArg, String description); Option(String opt, String longOpt, boolean hasArg, String description); int getId(); String getOpt(); Object getType(); @Deprecated void setType(Object type); void setType(Class<?> type); String getLongOpt(); void setLongOpt(String longOpt); void setOptionalArg(boolean optionalArg); boolean hasOptionalArg(); boolean hasLongOpt(); boolean hasArg(); String getDescription(); void setDescription(String description); boolean isRequired(); void setRequired(boolean required); void setArgName(String argName); String getArgName(); boolean hasArgName(); boolean hasArgs(); void setArgs(int num); void setValueSeparator(char sep); char getValueSeparator(); boolean hasValueSeparator(); int getArgs(); String getValue(); String getValue(int index); String getValue(String defaultValue); String[] getValues(); List<String> getValuesList(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Object clone(); @Deprecated boolean addValue(String value); static Builder builder(); static Builder builder(final String opt); static final int UNINITIALIZED; static final int UNLIMITED_VALUES; }### Answer:
@Test public void testClone() { TestOption a = new TestOption("a", true, ""); TestOption b = (TestOption) a.clone(); assertEquals(a, b); assertNotSame(a, b); a.setDescription("a"); assertEquals("", b.getDescription()); b.setArgs(2); b.addValue("b1"); b.addValue("b2"); assertEquals(1, a.getArgs()); assertEquals(0, a.getValuesList().size()); assertEquals(2, b.getValues().length); } |
### Question:
Option implements Cloneable, Serializable { public boolean hasArgName() { return argName != null && argName.length() > 0; } private Option(final Builder builder); Option(String opt, String description); Option(String opt, boolean hasArg, String description); Option(String opt, String longOpt, boolean hasArg, String description); int getId(); String getOpt(); Object getType(); @Deprecated void setType(Object type); void setType(Class<?> type); String getLongOpt(); void setLongOpt(String longOpt); void setOptionalArg(boolean optionalArg); boolean hasOptionalArg(); boolean hasLongOpt(); boolean hasArg(); String getDescription(); void setDescription(String description); boolean isRequired(); void setRequired(boolean required); void setArgName(String argName); String getArgName(); boolean hasArgName(); boolean hasArgs(); void setArgs(int num); void setValueSeparator(char sep); char getValueSeparator(); boolean hasValueSeparator(); int getArgs(); String getValue(); String getValue(int index); String getValue(String defaultValue); String[] getValues(); List<String> getValuesList(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Object clone(); @Deprecated boolean addValue(String value); static Builder builder(); static Builder builder(final String opt); static final int UNINITIALIZED; static final int UNLIMITED_VALUES; }### Answer:
@Test public void testHasArgName() { Option option = new Option("f", null); option.setArgName(null); assertFalse(option.hasArgName()); option.setArgName(""); assertFalse(option.hasArgName()); option.setArgName("file"); assertTrue(option.hasArgName()); } |
### Question:
Option implements Cloneable, Serializable { public boolean hasArgs() { return numberOfArgs > 1 || numberOfArgs == UNLIMITED_VALUES; } private Option(final Builder builder); Option(String opt, String description); Option(String opt, boolean hasArg, String description); Option(String opt, String longOpt, boolean hasArg, String description); int getId(); String getOpt(); Object getType(); @Deprecated void setType(Object type); void setType(Class<?> type); String getLongOpt(); void setLongOpt(String longOpt); void setOptionalArg(boolean optionalArg); boolean hasOptionalArg(); boolean hasLongOpt(); boolean hasArg(); String getDescription(); void setDescription(String description); boolean isRequired(); void setRequired(boolean required); void setArgName(String argName); String getArgName(); boolean hasArgName(); boolean hasArgs(); void setArgs(int num); void setValueSeparator(char sep); char getValueSeparator(); boolean hasValueSeparator(); int getArgs(); String getValue(); String getValue(int index); String getValue(String defaultValue); String[] getValues(); List<String> getValuesList(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Object clone(); @Deprecated boolean addValue(String value); static Builder builder(); static Builder builder(final String opt); static final int UNINITIALIZED; static final int UNLIMITED_VALUES; }### Answer:
@Test public void testHasArgs() { Option option = new Option("f", null); option.setArgs(0); assertFalse(option.hasArgs()); option.setArgs(1); assertFalse(option.hasArgs()); option.setArgs(10); assertTrue(option.hasArgs()); option.setArgs(Option.UNLIMITED_VALUES); assertTrue(option.hasArgs()); option.setArgs(Option.UNINITIALIZED); assertFalse(option.hasArgs()); } |
### Question:
Option implements Cloneable, Serializable { public String getValue() { return hasNoValues() ? null : values.get(0); } private Option(final Builder builder); Option(String opt, String description); Option(String opt, boolean hasArg, String description); Option(String opt, String longOpt, boolean hasArg, String description); int getId(); String getOpt(); Object getType(); @Deprecated void setType(Object type); void setType(Class<?> type); String getLongOpt(); void setLongOpt(String longOpt); void setOptionalArg(boolean optionalArg); boolean hasOptionalArg(); boolean hasLongOpt(); boolean hasArg(); String getDescription(); void setDescription(String description); boolean isRequired(); void setRequired(boolean required); void setArgName(String argName); String getArgName(); boolean hasArgName(); boolean hasArgs(); void setArgs(int num); void setValueSeparator(char sep); char getValueSeparator(); boolean hasValueSeparator(); int getArgs(); String getValue(); String getValue(int index); String getValue(String defaultValue); String[] getValues(); List<String> getValuesList(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Object clone(); @Deprecated boolean addValue(String value); static Builder builder(); static Builder builder(final String opt); static final int UNINITIALIZED; static final int UNLIMITED_VALUES; }### Answer:
@Test public void testGetValue() { Option option = new Option("f", null); option.setArgs(Option.UNLIMITED_VALUES); assertEquals("default", option.getValue("default")); assertEquals(null, option.getValue(0)); option.addValueForProcessing("foo"); assertEquals("foo", option.getValue()); assertEquals("foo", option.getValue(0)); assertEquals("foo", option.getValue("default")); } |
### Question:
Option implements Cloneable, Serializable { public static Builder builder() { return builder(null); } private Option(final Builder builder); Option(String opt, String description); Option(String opt, boolean hasArg, String description); Option(String opt, String longOpt, boolean hasArg, String description); int getId(); String getOpt(); Object getType(); @Deprecated void setType(Object type); void setType(Class<?> type); String getLongOpt(); void setLongOpt(String longOpt); void setOptionalArg(boolean optionalArg); boolean hasOptionalArg(); boolean hasLongOpt(); boolean hasArg(); String getDescription(); void setDescription(String description); boolean isRequired(); void setRequired(boolean required); void setArgName(String argName); String getArgName(); boolean hasArgName(); boolean hasArgs(); void setArgs(int num); void setValueSeparator(char sep); char getValueSeparator(); boolean hasValueSeparator(); int getArgs(); String getValue(); String getValue(int index); String getValue(String defaultValue); String[] getValues(); List<String> getValuesList(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); @Override Object clone(); @Deprecated boolean addValue(String value); static Builder builder(); static Builder builder(final String opt); static final int UNINITIALIZED; static final int UNLIMITED_VALUES; }### Answer:
@Test(expected=IllegalArgumentException.class) public void testBuilderInsufficientParams1() { Option.builder().desc("desc").build(); }
@Test(expected=IllegalArgumentException.class) public void testBuilderInsufficientParams2() { Option.builder(null).desc("desc").build(); } |
### Question:
Options implements Serializable { List<Option> helpOptions() { return new ArrayList<Option>(shortOpts.values()); } Options addOptionGroup(OptionGroup group); Options addOption(String opt, String description); Options addOption(String opt, boolean hasArg, String description); Options addOption(String opt, String longOpt, boolean hasArg, String description); Options addRequiredOption(String opt, String longOpt, boolean hasArg, String description); Options addOption(Option opt); Collection<Option> getOptions(); List getRequiredOptions(); Option getOption(String opt); List<String> getMatchingOptions(String opt); boolean hasOption(String opt); boolean hasLongOption(String opt); boolean hasShortOption(String opt); OptionGroup getOptionGroup(Option opt); @Override String toString(); }### Answer:
@Test public void testHelpOptions() { Option longOnly1 = OptionBuilder.withLongOpt("long-only1").create(); Option longOnly2 = OptionBuilder.withLongOpt("long-only2").create(); Option shortOnly1 = OptionBuilder.create("1"); Option shortOnly2 = OptionBuilder.create("2"); Option bothA = OptionBuilder.withLongOpt("bothA").create("a"); Option bothB = OptionBuilder.withLongOpt("bothB").create("b"); Options options = new Options(); options.addOption(longOnly1); options.addOption(longOnly2); options.addOption(shortOnly1); options.addOption(shortOnly2); options.addOption(bothA); options.addOption(bothB); Collection<Option> allOptions = new ArrayList<Option>(); allOptions.add(longOnly1); allOptions.add(longOnly2); allOptions.add(shortOnly1); allOptions.add(shortOnly2); allOptions.add(bothA); allOptions.add(bothB); Collection<Option> helpOptions = options.helpOptions(); assertTrue("Everything in all should be in help", helpOptions.containsAll(allOptions)); assertTrue("Everything in help should be in all", allOptions.containsAll(helpOptions)); } |
### Question:
Options implements Serializable { public Options addOption(String opt, String description) { addOption(opt, null, false, description); return this; } Options addOptionGroup(OptionGroup group); Options addOption(String opt, String description); Options addOption(String opt, boolean hasArg, String description); Options addOption(String opt, String longOpt, boolean hasArg, String description); Options addRequiredOption(String opt, String longOpt, boolean hasArg, String description); Options addOption(Option opt); Collection<Option> getOptions(); List getRequiredOptions(); Option getOption(String opt); List<String> getMatchingOptions(String opt); boolean hasOption(String opt); boolean hasLongOption(String opt); boolean hasShortOption(String opt); OptionGroup getOptionGroup(Option opt); @Override String toString(); }### Answer:
@Test public void testMissingOptionException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required option: f", e.getMessage()); } }
@Test public void testMissingOptionsException() throws ParseException { Options options = new Options(); options.addOption(OptionBuilder.isRequired().create("f")); options.addOption(OptionBuilder.isRequired().create("x")); try { new PosixParser().parse(options, new String[0]); fail("Expected MissingOptionException to be thrown"); } catch (MissingOptionException e) { assertEquals("Missing required options: f, x", e.getMessage()); } } |
### Question:
Options implements Serializable { @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append("[ Options: [ short "); buf.append(shortOpts.toString()); buf.append(" ] [ long "); buf.append(longOpts); buf.append(" ]"); return buf.toString(); } Options addOptionGroup(OptionGroup group); Options addOption(String opt, String description); Options addOption(String opt, boolean hasArg, String description); Options addOption(String opt, String longOpt, boolean hasArg, String description); Options addRequiredOption(String opt, String longOpt, boolean hasArg, String description); Options addOption(Option opt); Collection<Option> getOptions(); List getRequiredOptions(); Option getOption(String opt); List<String> getMatchingOptions(String opt); boolean hasOption(String opt); boolean hasLongOption(String opt); boolean hasShortOption(String opt); OptionGroup getOptionGroup(Option opt); @Override String toString(); }### Answer:
@Test public void testToString() { Options options = new Options(); options.addOption("f", "foo", true, "Foo"); options.addOption("b", "bar", false, "Bar"); String s = options.toString(); assertNotNull("null string returned", s); assertTrue("foo option missing", s.toLowerCase().contains("foo")); assertTrue("bar option missing", s.toLowerCase().contains("bar")); } |
### Question:
OptionGroup implements Serializable { public String getSelected() { return selected; } OptionGroup addOption(Option option); Collection<String> getNames(); Collection<Option> getOptions(); void setSelected(Option option); String getSelected(); void setRequired(boolean required); boolean isRequired(); @Override String toString(); }### Answer:
@Test public void testTwoOptionsFromGroup() throws Exception { String[] args = new String[] { "-f", "-d" }; try { parser.parse( _options, args); fail( "two arguments from group not allowed" ); } catch (AlreadySelectedException e) { assertNotNull("null option group", e.getOptionGroup()); assertEquals("selected option", "f", e.getOptionGroup().getSelected()); assertEquals("option", "d", e.getOption().getOpt()); } }
@Test public void testTwoLongOptionsFromGroup() throws Exception { String[] args = new String[] { "--file", "--directory" }; try { parser.parse(_options, args); fail( "two arguments from group not allowed" ); } catch (AlreadySelectedException e) { assertNotNull("null option group", e.getOptionGroup()); assertEquals("selected option", "f", e.getOptionGroup().getSelected()); assertEquals("option", "d", e.getOption().getOpt()); } } |
### Question:
OptionGroup implements Serializable { @Override public String toString() { StringBuilder buff = new StringBuilder(); Iterator<Option> iter = getOptions().iterator(); buff.append("["); while (iter.hasNext()) { Option option = iter.next(); if (option.getOpt() != null) { buff.append("-"); buff.append(option.getOpt()); } else { buff.append("--"); buff.append(option.getLongOpt()); } if (option.getDescription() != null) { buff.append(" "); buff.append(option.getDescription()); } if (iter.hasNext()) { buff.append(", "); } } buff.append("]"); return buff.toString(); } OptionGroup addOption(Option option); Collection<String> getNames(); Collection<Option> getOptions(); void setSelected(Option option); String getSelected(); void setRequired(boolean required); boolean isRequired(); @Override String toString(); }### Answer:
@Test public void testToString() { OptionGroup group1 = new OptionGroup(); group1.addOption(new Option(null, "foo", false, "Foo")); group1.addOption(new Option(null, "bar", false, "Bar")); if (!"[--bar Bar, --foo Foo]".equals(group1.toString())) { assertEquals("[--foo Foo, --bar Bar]", group1.toString()); } OptionGroup group2 = new OptionGroup(); group2.addOption(new Option("f", "foo", false, "Foo")); group2.addOption(new Option("b", "bar", false, "Bar")); if (!"[-b Bar, -f Foo]".equals(group2.toString())) { assertEquals("[-f Foo, -b Bar]", group2.toString()); } } |
### Question:
OptionGroup implements Serializable { public Collection<String> getNames() { return optionMap.keySet(); } OptionGroup addOption(Option option); Collection<String> getNames(); Collection<Option> getOptions(); void setSelected(Option option); String getSelected(); void setRequired(boolean required); boolean isRequired(); @Override String toString(); }### Answer:
@Test public void testGetNames() { OptionGroup group = new OptionGroup(); group.addOption(OptionBuilder.create('a')); group.addOption(OptionBuilder.create('b')); assertNotNull("null names", group.getNames()); assertEquals(2, group.getNames().size()); assertTrue(group.getNames().contains("a")); assertTrue(group.getNames().contains("b")); } |
### Question:
CommandLine implements Serializable { public Option[] getOptions() { Collection<Option> processed = options; Option[] optionsArray = new Option[processed.size()]; return processed.toArray(optionsArray); } protected CommandLine(); boolean hasOption(String opt); boolean hasOption(char opt); @Deprecated Object getOptionObject(String opt); Object getParsedOptionValue(String opt); Object getOptionObject(char opt); String getOptionValue(String opt); String getOptionValue(char opt); String[] getOptionValues(String opt); String[] getOptionValues(char opt); String getOptionValue(String opt, String defaultValue); String getOptionValue(char opt, String defaultValue); Properties getOptionProperties(String opt); String[] getArgs(); List<String> getArgList(); Iterator<Option> iterator(); Option[] getOptions(); }### Answer:
@Test public void testGetOptions() { CommandLine cmd = new CommandLine(); assertNotNull(cmd.getOptions()); assertEquals(0, cmd.getOptions().length); cmd.addOption(new Option("a", null)); cmd.addOption(new Option("b", null)); cmd.addOption(new Option("c", null)); assertEquals(3, cmd.getOptions().length); } |
### Question:
CommandLine implements Serializable { public Object getParsedOptionValue(String opt) throws ParseException { String res = getOptionValue(opt); Option option = resolveOption(opt); if (option == null || res == null) { return null; } return TypeHandler.createValue(res, option.getType()); } protected CommandLine(); boolean hasOption(String opt); boolean hasOption(char opt); @Deprecated Object getOptionObject(String opt); Object getParsedOptionValue(String opt); Object getOptionObject(char opt); String getOptionValue(String opt); String getOptionValue(char opt); String[] getOptionValues(String opt); String[] getOptionValues(char opt); String getOptionValue(String opt, String defaultValue); String getOptionValue(char opt, String defaultValue); Properties getOptionProperties(String opt); String[] getArgs(); List<String> getArgList(); Iterator<Option> iterator(); Option[] getOptions(); }### Answer:
@Test public void testGetParsedOptionValue() throws Exception { Options options = new Options(); options.addOption(OptionBuilder.hasArg().withType(Number.class).create("i")); options.addOption(OptionBuilder.hasArg().create("f")); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, new String[] { "-i", "123", "-f", "foo" }); assertEquals(123, ((Number) cmd.getParsedOptionValue("i")).intValue()); assertEquals("foo", cmd.getParsedOptionValue("f")); } |
### Question:
Task implements Parcelable { public ArrayList<String> getPhoto(){return this.pictureArray;} Task(String title, String description, LatLng geoLoc, String status, String userId, String userName, ArrayList<String> pictureList); private Task(Parcel in); void setTitle(String title); void setDescription(String description); void setId(String id); void setPhoto(ArrayList<String> pictureList); void setGeo(LatLng geoLoc); void setStatus(String status); String getTitle(); String getDescription(); String getId(); ArrayList<String> getPhoto(); LatLng getGeoLoc(); String getStatus(); String getUserId(); String getUserName(); String getAcceptedUser(); void setAcceptedUser(String username); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); String getProvider(); void setTaskProvider(String taskProvider); static final Parcelable.Creator<Task> CREATOR; }### Answer:
@Test public void getPhoto() throws Exception { ArrayList<String> imgArray = new ArrayList<String>(); assert(imgArray.get(0) == null); Task testTask = new Task("title", "test desc", new LatLng(0,0), "bidded", "sampleUsrID_r56yh", "sampleuserName", ); assert(testTask.getPhoto() == null); imgArray.add("test_img_str"); testTask.setPhoto(imgArray); assert(testTask.getPhoto() != null); } |
### Question:
Task implements Parcelable { public String getTitle(){return this.title;} Task(String title, String description, LatLng geoLoc, String status, String userId, String userName, ArrayList<String> pictureList); private Task(Parcel in); void setTitle(String title); void setDescription(String description); void setId(String id); void setPhoto(ArrayList<String> pictureList); void setGeo(LatLng geoLoc); void setStatus(String status); String getTitle(); String getDescription(); String getId(); ArrayList<String> getPhoto(); LatLng getGeoLoc(); String getStatus(); String getUserId(); String getUserName(); String getAcceptedUser(); void setAcceptedUser(String username); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); String getProvider(); void setTaskProvider(String taskProvider); static final Parcelable.Creator<Task> CREATOR; }### Answer:
@Test public void getTitle() throws Exception { Task testTask = new Task("title", "test desc", new LatLng(0,0), "bidded", "sampleUsrID_r56yh", "sampleuserName", ); assert(testTask.getTitle() != null); } |
### Question:
Task implements Parcelable { public String getDescription(){return this.description;} Task(String title, String description, LatLng geoLoc, String status, String userId, String userName, ArrayList<String> pictureList); private Task(Parcel in); void setTitle(String title); void setDescription(String description); void setId(String id); void setPhoto(ArrayList<String> pictureList); void setGeo(LatLng geoLoc); void setStatus(String status); String getTitle(); String getDescription(); String getId(); ArrayList<String> getPhoto(); LatLng getGeoLoc(); String getStatus(); String getUserId(); String getUserName(); String getAcceptedUser(); void setAcceptedUser(String username); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); String getProvider(); void setTaskProvider(String taskProvider); static final Parcelable.Creator<Task> CREATOR; }### Answer:
@Test public void getDescription() throws Exception { Task testTask = new Task("title", "test desc", new LatLng(0,0), "bidded", "sampleUsrID_r56yh", "sampleuserName", ); assert(testTask.getDescription() != null); } |
### Question:
BidList implements Parcelable { public void add(Bid bid) { if (hasBid(bid)) { throw new IllegalArgumentException("Duplicate bid found!"); } bids.add(bid); } protected BidList(Parcel in); void add(Bid bid); boolean hasBid(Bid bid); Bid getBid(int index); void delBid(Bid bid); int size(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<BidList> CREATOR; }### Answer:
@Test public void add() throws Exception { BidList bidsList; bidsList = new BidList(); Bid myBid = new Bid("test_user_name", (float) 19.99,"declined"); assertFalse(Arrays.asList(bidsList).contains(myBid)); bidsList.add(myBid); System.out.println("Test user name is: " + bidsList.getBid(0).getUsername() + '\n'); System.out.println("Test bid value is: " + bidsList.getBid(0).getValue() + '\n'); System.out.println("Test bid value is: " + bidsList.getBid(0).getFlag() + '\n'); assertTrue(Arrays.asList(bidsList).contains(myBid)); } |
### Question:
BidList implements Parcelable { public boolean hasBid(Bid bid) { return bids.contains(bid); } protected BidList(Parcel in); void add(Bid bid); boolean hasBid(Bid bid); Bid getBid(int index); void delBid(Bid bid); int size(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<BidList> CREATOR; }### Answer:
@Test public void hasBid() throws Exception { BidList bidsList = new BidList(); Bid myBid = new Bid("test_user_name", (float) 19.99); assertFalse(bidsList.hasBid(myBid)); bidsList.add(myBid); assertTrue(bidsList.hasBid(myBid)); } |
### Question:
BidList implements Parcelable { public Bid getBid(int index) { return bids.get(index); } protected BidList(Parcel in); void add(Bid bid); boolean hasBid(Bid bid); Bid getBid(int index); void delBid(Bid bid); int size(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<BidList> CREATOR; }### Answer:
@Test public void getBid() throws Exception { BidList bidsList = new BidList(); Bid myBid = new Bid("test_user_name", (float) 19.99); bidsList.add(myBid); assertEquals(bidsList.getBid(0), myBid); } |
### Question:
BidList implements Parcelable { public void delBid(Bid bid) { bids.remove(bid); } protected BidList(Parcel in); void add(Bid bid); boolean hasBid(Bid bid); Bid getBid(int index); void delBid(Bid bid); int size(); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<BidList> CREATOR; }### Answer:
@Test public void delBid() throws Exception { BidList bidsList = new BidList(); Bid myBid = new Bid("test_user_name", (float) 19.99); assertFalse(bidsList.hasBid(myBid)); bidsList.add(myBid); assertTrue(bidsList.hasBid(myBid)); bidsList.delBid(myBid); assertFalse(bidsList.hasBid(myBid)); } |
### Question:
Tasklist implements Parcelable { public void add(Task task) { tasks.add(task); } protected Tasklist(Parcel in); void add(Task task); boolean hasTask(Task task); Task getTask(int index); int length(); void delTask(Task task); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<Tasklist> CREATOR; }### Answer:
@Test public void add() throws Exception { Tasklist taskList = new Tasklist(); Task myTask = new Task("Shovel snow", "Shovelling snow at my house", "open"); assertFalse(Arrays.asList(taskList).contains(myTask)); taskList.add(myTask); assertTrue(Arrays.asList(taskList).contains(myTask)); } |
### Question:
Tasklist implements Parcelable { public boolean hasTask(Task task) { return tasks.contains(task); } protected Tasklist(Parcel in); void add(Task task); boolean hasTask(Task task); Task getTask(int index); int length(); void delTask(Task task); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<Tasklist> CREATOR; }### Answer:
@Test public void hasTask() throws Exception { Tasklist taskList = new Tasklist(); Task myTask = new Task("Shovel snow", "Shovelling snow at my house", "open"); assertFalse(taskList.hasTask(myTask)); taskList.add(myTask); assertTrue(taskList.hasTask(myTask)); } |
### Question:
Tasklist implements Parcelable { public Task getTask(int index) { return tasks.get(index); } protected Tasklist(Parcel in); void add(Task task); boolean hasTask(Task task); Task getTask(int index); int length(); void delTask(Task task); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<Tasklist> CREATOR; }### Answer:
@Test public void getTask() throws Exception { Tasklist taskList = new Tasklist(); Task myTask = new Task("Shovel snow", "Shovelling snow at my house", "open"); taskList.add(myTask); assertEquals(taskList.getTask(0), myTask); } |
### Question:
Tasklist implements Parcelable { public void delTask(Task task) { tasks.remove(task); } protected Tasklist(Parcel in); void add(Task task); boolean hasTask(Task task); Task getTask(int index); int length(); void delTask(Task task); @Override int describeContents(); @Override void writeToParcel(Parcel dest, int flags); static final Creator<Tasklist> CREATOR; }### Answer:
@Test public void delTask() throws Exception { Tasklist taskList = new Tasklist(); Task myTask = new Task("Shovel snow", "Shovelling snow at my house", "open"); taskList.add(myTask); assertTrue(Arrays.asList(taskList).contains(myTask)); taskList.delTask(myTask); assertFalse(Arrays.asList(taskList).contains(myTask)); } |
### Question:
User implements Parcelable { public void setUsername(String name) throws UsernameTooLongException { this.username = name; } User(String username, String email, String phoneNumber); User(String username, String email, String phoneNumber, float rating); User(String Username); private User(Parcel in); String getUsername(); void setUsername(String name); String getEmail(); void setEmail(String mail); void setPhoneNumber(String number); String getPhoneNumber(); void setId(String id); String getId(); float getRating(); void addRating(float rate); void addReview(String newReview); ArrayList<String> getReviews(); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); static final Parcelable.Creator<User> CREATOR; }### Answer:
@Test public void setUsername() throws Exception { ArrayList<User> UserList = new ArrayList<>(); User newUser = new User("HelloWorld"); assertFalse(UserList.contains(newUser)); UserList.add(newUser); assertTrue(UserList.contains(newUser)); } |
### Question:
User implements Parcelable { public void setEmail(String mail) throws InvalidEmailException { this.email = mail; } User(String username, String email, String phoneNumber); User(String username, String email, String phoneNumber, float rating); User(String Username); private User(Parcel in); String getUsername(); void setUsername(String name); String getEmail(); void setEmail(String mail); void setPhoneNumber(String number); String getPhoneNumber(); void setId(String id); String getId(); float getRating(); void addRating(float rate); void addReview(String newReview); ArrayList<String> getReviews(); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); static final Parcelable.Creator<User> CREATOR; }### Answer:
@Test public void setEmail() throws Exception { User newUser = new User("HelloWorld"); newUser.setEmail("myEmail@gmail.com"); assertTrue(newUser.getEmail().equals("myEmail@gmail.com")); } |
### Question:
User implements Parcelable { public void setPhoneNumber(String number) { this.phoneNumber = number; } User(String username, String email, String phoneNumber); User(String username, String email, String phoneNumber, float rating); User(String Username); private User(Parcel in); String getUsername(); void setUsername(String name); String getEmail(); void setEmail(String mail); void setPhoneNumber(String number); String getPhoneNumber(); void setId(String id); String getId(); float getRating(); void addRating(float rate); void addReview(String newReview); ArrayList<String> getReviews(); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); static final Parcelable.Creator<User> CREATOR; }### Answer:
@Test public void setPhoneNumber() throws Exception { User newUser = new User("HelloWorld"); newUser.setPhoneNumber("5551234567"); assertTrue(newUser.getPhoneNumber().equals("5551234567")); } |
### Question:
User implements Parcelable { public void addRating(float rate) { float newRating; newRating = ((this.rating*this.numRatings)+rate)/(numRatings+1); this.rating = newRating; this.numRatings++; } User(String username, String email, String phoneNumber); User(String username, String email, String phoneNumber, float rating); User(String Username); private User(Parcel in); String getUsername(); void setUsername(String name); String getEmail(); void setEmail(String mail); void setPhoneNumber(String number); String getPhoneNumber(); void setId(String id); String getId(); float getRating(); void addRating(float rate); void addReview(String newReview); ArrayList<String> getReviews(); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); static final Parcelable.Creator<User> CREATOR; }### Answer:
@Test public void addRating() throws Exception { User newUser = new User("HelloWorld"); newUser.addRating(4); assertTrue(newUser.getRating() == 4.0); newUser.addRating(3.0f); assertTrue(newUser.getRating() == 3.5); } |
### Question:
Task implements Parcelable { public String getId() {return this.id;} Task(String title, String description, LatLng geoLoc, String status, String userId, String userName, ArrayList<String> pictureList); private Task(Parcel in); void setTitle(String title); void setDescription(String description); void setId(String id); void setPhoto(ArrayList<String> pictureList); void setGeo(LatLng geoLoc); void setStatus(String status); String getTitle(); String getDescription(); String getId(); ArrayList<String> getPhoto(); LatLng getGeoLoc(); String getStatus(); String getUserId(); String getUserName(); String getAcceptedUser(); void setAcceptedUser(String username); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); String getProvider(); void setTaskProvider(String taskProvider); static final Parcelable.Creator<Task> CREATOR; }### Answer:
@Test public void getId() throws Exception { Task testTask = new Task("title", "test desc", new LatLng(0,0), "bidded", "sampleUsrID_r56yh", "sampleuserName", new ArrayList<String>()); assert(testTask.getId() == null); testTask.setId("taskId_tdr5invhcbg"); assert(testTask.getId() != null); } |
### Question:
Task implements Parcelable { public void setId(String id) { this.id = id; } Task(String title, String description, LatLng geoLoc, String status, String userId, String userName, ArrayList<String> pictureList); private Task(Parcel in); void setTitle(String title); void setDescription(String description); void setId(String id); void setPhoto(ArrayList<String> pictureList); void setGeo(LatLng geoLoc); void setStatus(String status); String getTitle(); String getDescription(); String getId(); ArrayList<String> getPhoto(); LatLng getGeoLoc(); String getStatus(); String getUserId(); String getUserName(); String getAcceptedUser(); void setAcceptedUser(String username); @Override int describeContents(); @Override void writeToParcel(Parcel out, int flags); String getProvider(); void setTaskProvider(String taskProvider); static final Parcelable.Creator<Task> CREATOR; }### Answer:
@Test public void setId() throws Exception { Task testTask = new Task("title", "test desc", new LatLng(0,0), "bidded", "sampleUsrID_r56yh", "sampleuserName", new ArrayList<String>()); assert(testTask.getId() == null); testTask.setId("taskId_t4rydgv"); assert(testTask.getId() != null); } |
### Question:
ColumnQualifier implements WritableComparable<ColumnQualifier> { public ColumnQualifier() { } ColumnQualifier(); ColumnQualifier(String cf, String qualifier); ColumnQualifier(byte[] cf, byte[] qualifier); ColumnQualifier(String cf, String qualifier, ValueType type, int maxValueLength); ColumnQualifier(String cf, String qualifier, ValueType type, int maxValueLength,
ValuePartition vp); ColumnQualifier(byte[] cf, byte[] qualifier, ValueType type, int maxValueLength,
ValuePartition vp); String getColumnFamilyString(); String getQualifierString(); byte[] getColumnFamily(); byte[] getQualifier(); ValuePartition getValuePartition(); void readFields(DataInput in); void write(DataOutput out); @Override boolean equals(Object cq); int hashCode(); @Override int compareTo(ColumnQualifier cq); int getMaxValueLength(); ValueType getType(); String toString(); }### Answer:
@Test public void testColumnQualifier() throws Exception { ColumnQualifier cq = new ColumnQualifier("cf", "cq"); assertEquals("Column family not match with acutal value.", "cf", cq.getColumnFamilyString()); assertEquals("Column qualifier not match with actual value.", "cq", cq.getQualifierString()); assertEquals("Column family bytes not match with actual value.", 0, Bytes.compareTo(Bytes.toBytes("cf"), cq.getColumnFamily())); assertEquals("Column qualifier bytes not match with actual value.", 0, Bytes.compareTo(Bytes.toBytes("cq"), cq.getQualifier())); } |
### Question:
IndexSpecification implements WritableComparable<IndexSpecification> { public String getName() { return Bytes.toString(this.name); } IndexSpecification(); IndexSpecification(String name); IndexSpecification(byte[] name); String getName(); void addIndexColumn(HColumnDescriptor cf, String qualifier, ValueType type,
int maxValueLength); void addIndexColumn(HColumnDescriptor cf, String qualifier, ValuePartition vp,
ValueType type, int maxValueLength); Set<ColumnQualifier> getIndexColumns(); void readFields(DataInput in); void write(DataOutput out); int compareTo(IndexSpecification o); String toString(); boolean equals(Object obj); int hashCode(); ColumnQualifier getLastColumn(); boolean contains(byte[] family); boolean contains(byte[] family, byte[] qualifier); int getTotalValueLength(); long getTTL(); int getMaxVersions(); }### Answer:
@Test public void testGetName() throws Exception { IndexSpecification iSpec = new IndexSpecification("index_name"); assertEquals("Index name not match with acutal index name.", "index_name", iSpec.getName()); iSpec = new IndexSpecification("index_name"); assertEquals("Index name not match with acutal index name.", "index_name", iSpec.getName()); } |
### Question:
IndexMapReduceUtil { public static boolean isIndexedTable(String tableName, Configuration conf) throws IOException { IndexedHTableDescriptor tableDescriptor = getTableDescriptor(tableName, conf); return tableDescriptor != null; } static IndexedHTableDescriptor getTableDescriptor(String tableName, Configuration conf); static boolean isIndexedTable(String tableName, Configuration conf); static boolean isIndexedTable(Configuration conf); static List<Put> getIndexPut(Put userPut, Configuration conf); static List<Delete> getIndexDelete(Delete userDelete, Configuration conf); static byte[] getStartKey(Configuration conf, String tableName, byte[] row); static final String INDEX_DATA_DIR; static final String INDEX_IS_INDEXED_TABLE; }### Answer:
@Test(timeout = 180000) public void testShouldAbleReturnTrueForIndexedTable() throws Exception { tableName = "testShouldAbleReturnTrueForIndexedTable"; IndexedHTableDescriptor ihtd = new IndexedHTableDescriptor(tableName); HColumnDescriptor hcd = new HColumnDescriptor("col"); IndexSpecification iSpec = new IndexSpecification("ScanIndexf"); iSpec.addIndexColumn(hcd, "ql", ValueType.String, 10); ihtd.addFamily(hcd); ihtd.addIndex(iSpec); admin.createTable(ihtd); Assert.assertTrue(IndexMapReduceUtil.isIndexedTable(tableName, conf)); }
@Test(timeout = 180000) public void testShouldAbleReturnFalseForNonIndexedTable() throws Exception { tableName = "testShouldAbleReturnFalseForNonIndexedTable"; HTableDescriptor ihtd = new HTableDescriptor(tableName); HColumnDescriptor hcd = new HColumnDescriptor("col"); ihtd.addFamily(hcd); admin.createTable(ihtd); Assert.assertFalse(IndexMapReduceUtil.isIndexedTable(tableName, conf)); } |
### Question:
IndexUtils { public static byte[] toBytes(IndexExpression indexExpression) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(indexExpression); return bos.toByteArray(); } private IndexUtils(); static byte[] toBytes(IndexExpression indexExpression); static IndexExpression toIndexExpression(byte[] bytes); }### Answer:
@Test public void testConvertingSimpleIndexExpressionToByteArray() throws Exception { SingleIndexExpression singleIndexExpression = new SingleIndexExpression("idx1"); Column column = new Column(FAMILY1, QUALIFIER1); byte[] value = "1".getBytes(); EqualsExpression equalsExpression = new EqualsExpression(column, value); singleIndexExpression.addEqualsExpression(equalsExpression); byte[] bytes = IndexUtils.toBytes(singleIndexExpression); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInputStream ois = new ObjectInputStream(bis); SingleIndexExpression readExp = (SingleIndexExpression) ois.readObject(); assertEquals("idx1", readExp.getIndexName()); assertEquals(1, readExp.getEqualsExpressions().size()); assertTrue(Bytes.equals(value, readExp.getEqualsExpressions().get(0).getValue())); assertEquals(column, readExp.getEqualsExpressions().get(0).getColumn()); } |
### Question:
CpanDataAccess { @Nullable public Component findComponent(final StorageTx tx, final Repository repository, final String name, final String version) { Iterable<Component> components = tx.findComponents( Query.builder() .where(P_NAME).eq(name) .and(P_VERSION).eq(version) .build(), singletonList(repository) ); if (components.iterator().hasNext()) { return components.iterator().next(); } return null; } @Nullable Component findComponent(final StorageTx tx,
final Repository repository,
final String name,
final String version); @Nullable Asset findAsset(final StorageTx tx, final Bucket bucket, final String assetName); Content saveAsset(final StorageTx tx,
final Asset asset,
final Supplier<InputStream> contentSupplier,
final Payload payload); Content saveAsset(final StorageTx tx,
final Asset asset,
final Supplier<InputStream> contentSupplier,
final String contentType,
@Nullable final AttributesMap contentAttributes); Content toContent(final Asset asset, final Blob blob); static final List<HashAlgorithm> HASH_ALGORITHMS; }### Answer:
@Test public void findComponent() { List<Component> list = ImmutableList.of(component); when(tx.findComponents(any(), any())) .thenReturn(list); assertThat(underTest.findComponent(tx, repository, "test", "test"), is(equalTo(component))); } |
### Question:
CpanDataAccess { @Nullable public Asset findAsset(final StorageTx tx, final Bucket bucket, final String assetName) { return tx.findAssetWithProperty(MetadataNodeEntityAdapter.P_NAME, assetName, bucket); } @Nullable Component findComponent(final StorageTx tx,
final Repository repository,
final String name,
final String version); @Nullable Asset findAsset(final StorageTx tx, final Bucket bucket, final String assetName); Content saveAsset(final StorageTx tx,
final Asset asset,
final Supplier<InputStream> contentSupplier,
final Payload payload); Content saveAsset(final StorageTx tx,
final Asset asset,
final Supplier<InputStream> contentSupplier,
final String contentType,
@Nullable final AttributesMap contentAttributes); Content toContent(final Asset asset, final Blob blob); static final List<HashAlgorithm> HASH_ALGORITHMS; }### Answer:
@Test public void findAsset() { when(tx.findAssetWithProperty(any(), any(), any(Bucket.class))) .thenReturn(asset); assertThat(underTest.findAsset(tx, bucket, assetName), is(equalTo(asset))); } |
### Question:
CpanPathUtils { private String match(TokenMatcher.State state, String name) { checkNotNull(state); String result = state.getTokens().get(name); checkNotNull(result); return result; } CpanPathUtils(); String path(final TokenMatcher.State state); String path(final String path, final String filename); String filename(final TokenMatcher.State state); String extension(final TokenMatcher.State state); String archivePath(final String path, final String filename, final String extension); String checksumPath(final String path); TokenMatcher.State matcherState(final Context context); }### Answer:
@Test public void testMatch() { String result = "name"; when(matcherState.getTokens()).thenReturn(tokens); when(tokens.get(any())).thenReturn(result); assertThat(underTest.path(matcherState), is(result)); } |
### Question:
CpanPathUtils { public String path(final TokenMatcher.State state) { return match(state, "path"); } CpanPathUtils(); String path(final TokenMatcher.State state); String path(final String path, final String filename); String filename(final TokenMatcher.State state); String extension(final TokenMatcher.State state); String archivePath(final String path, final String filename, final String extension); String checksumPath(final String path); TokenMatcher.State matcherState(final Context context); }### Answer:
@Test(expected = NullPointerException.class) public void matchWithNullResultThrowsNullPointerException() { when(matcherState.getTokens()).thenReturn(tokens); underTest.path(matcherState); }
@Test(expected = NullPointerException.class) public void matchWithNullMatcherStateThrowsNullPointerException() { underTest.path(null); }
@Test public void getPathWithPathAndFilename() { String path = "path"; String filename = "filename.extension"; String expectedResult = path + "/" + filename; assertThat(underTest.path(path, filename), is(expectedResult)); } |
### Question:
CpanPathUtils { public String filename(final TokenMatcher.State state) { return match(state, "filename"); } CpanPathUtils(); String path(final TokenMatcher.State state); String path(final String path, final String filename); String filename(final TokenMatcher.State state); String extension(final TokenMatcher.State state); String archivePath(final String path, final String filename, final String extension); String checksumPath(final String path); TokenMatcher.State matcherState(final Context context); }### Answer:
@Test public void getFilename() { String result = "filename.extension"; when(matcherState.getTokens()).thenReturn(tokens); when(tokens.get(any())).thenReturn(result); assertThat(underTest.filename(matcherState), is(result)); } |
### Question:
CpanPathUtils { public TokenMatcher.State matcherState(final Context context) { return context.getAttributes().require(TokenMatcher.State.class); } CpanPathUtils(); String path(final TokenMatcher.State state); String path(final String path, final String filename); String filename(final TokenMatcher.State state); String extension(final TokenMatcher.State state); String archivePath(final String path, final String filename, final String extension); String checksumPath(final String path); TokenMatcher.State matcherState(final Context context); }### Answer:
@Test public void getMatcherStateFromContext() { when(context.getAttributes()).thenReturn(attributesMap); when(attributesMap.require(TokenMatcher.State.class)).thenReturn(matcherState); assertThat(underTest.matcherState(context), is(matcherState)); } |
### Question:
CpanPathUtils { public String checksumPath(final String path) { return path + "/CHECKSUM"; } CpanPathUtils(); String path(final TokenMatcher.State state); String path(final String path, final String filename); String filename(final TokenMatcher.State state); String extension(final TokenMatcher.State state); String archivePath(final String path, final String filename, final String extension); String checksumPath(final String path); TokenMatcher.State matcherState(final Context context); }### Answer:
@Test public void getChecksumPath() { String path = "path"; String expectedResult = path + "/CHECKSUM"; assertThat(underTest.checksumPath(path), is(expectedResult)); } |
### Question:
CpanProxyFacetImpl extends ProxyFacetSupport { @Override protected String getUrl(@Nonnull final Context context) { return context.getRequest().getPath().substring(1); } @Inject CpanProxyFacetImpl(final CpanParser cpanParser, final CpanPathUtils cpanPathUtils, final CpanDataAccess cpanDataAccess); @TransactionalTouchMetadata void setCacheInfo(final Content content, final CacheInfo cacheInfo); }### Answer:
@Test public void getUrl() throws Exception { String testUrl = "/repository/cpan-proxy"; String expectedUrl = testUrl.substring(1); when(context.getRequest()).thenReturn(request); when(request.getPath()).thenReturn(testUrl); assertThat(underTest.getUrl(context), is(expectedUrl)); } |
### Question:
ConnectionFactoryRegistration implements Closeable { @Override public void close() { if (serviceReg != null) { serviceReg.unregister(); } safeClose(connectionFactory); } ConnectionFactoryRegistration(BundleContext context, ConnectionFactoryFactory cff, final Dictionary<String, Object> config, final Dictionary<String, Object> decryptedConfig); @Override void close(); }### Answer:
@Test public void testPublishedAndUnpublished() throws ConfigurationException, InvalidSyntaxException, SQLException { Capture<Map<String, Object>> capturedCfProps = EasyMock.newCapture(); Capture<Dictionary> capturedServiceProps = EasyMock.newCapture(); IMocksControl c = EasyMock.createControl(); BundleContext context = c.createMock(BundleContext.class); final ConnectionFactoryFactory cff = c.createMock(ConnectionFactoryFactory.class); ConnectionFactory cf = c.createMock(ConnectionFactory.class); expect(cff.createConnectionFactory(capture(capturedCfProps))).andReturn(cf); ServiceRegistration cfSreg = c.createMock(ServiceRegistration.class); expect( context.registerService(eq(ConnectionFactory.class.getName()), eq(cf), capture(capturedServiceProps))).andReturn(cfSreg); c.replay(); Dictionary<String, Object> properties = new Hashtable(); properties.put(ConnectionFactoryFactory.JMS_CONNECTIONFACTORY_NAME, "mycfname"); ConnectionFactoryRegistration publisher = new ConnectionFactoryRegistration(context, cff, properties, properties); c.verify(); Dictionary serviceProps = capturedServiceProps.getValue(); assertEquals("mycfname", serviceProps.get(ConnectionFactoryFactory.JMS_CONNECTIONFACTORY_NAME)); assertEquals("mycfname", serviceProps.get("osgi.jndi.service.name")); c.reset(); cfSreg.unregister(); expectLastCall(); c.replay(); publisher.close(); c.verify(); } |
### Question:
CheckFieldAdapter extends FieldVisitor { @Override public AnnotationVisitor visitTypeAnnotation( final int typeRef, final TypePath typePath, final String descriptor, final boolean visible) { checkVisitEndNotCalled(); int sort = new TypeReference(typeRef).getSort(); if (sort != TypeReference.FIELD) { throw new IllegalArgumentException( "Invalid type reference sort 0x" + Integer.toHexString(sort)); } CheckClassAdapter.checkTypeRef(typeRef); CheckMethodAdapter.checkDescriptor(Opcodes.V1_5, descriptor, false); return new CheckAnnotationAdapter( super.visitTypeAnnotation(typeRef, typePath, descriptor, visible)); } CheckFieldAdapter(final FieldVisitor fieldVisitor); protected CheckFieldAdapter(final int api, final FieldVisitor fieldVisitor); @Override AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible); @Override AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible); @Override void visitAttribute(final Attribute attribute); @Override void visitEnd(); }### Answer:
@Test public void testVisitTypeAnnotation_illegalTypeAnnotation() { CheckFieldAdapter checkFieldAdapter = new CheckFieldAdapter(null); Executable visitTypeAnnotation = () -> checkFieldAdapter.visitTypeAnnotation( TypeReference.newFormalParameterReference(0).getValue(), null, "LA;", true); Exception exception = assertThrows(IllegalArgumentException.class, visitTypeAnnotation); assertEquals("Invalid type reference sort 0x16", exception.getMessage()); } |
### Question:
CheckFieldAdapter extends FieldVisitor { @Override public void visitAttribute(final Attribute attribute) { checkVisitEndNotCalled(); if (attribute == null) { throw new IllegalArgumentException("Invalid attribute (must not be null)"); } super.visitAttribute(attribute); } CheckFieldAdapter(final FieldVisitor fieldVisitor); protected CheckFieldAdapter(final int api, final FieldVisitor fieldVisitor); @Override AnnotationVisitor visitAnnotation(final String descriptor, final boolean visible); @Override AnnotationVisitor visitTypeAnnotation(
final int typeRef, final TypePath typePath, final String descriptor, final boolean visible); @Override void visitAttribute(final Attribute attribute); @Override void visitEnd(); }### Answer:
@Test public void testVisitAttribute_illegalAttribute() { CheckFieldAdapter checkFieldAdapter = new CheckFieldAdapter(null); Executable visitAttribute = () -> checkFieldAdapter.visitAttribute(null); Exception exception = assertThrows(IllegalArgumentException.class, visitAttribute); assertEquals("Invalid attribute (must not be null)", exception.getMessage()); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public void visitFormalTypeParameter(final String name) { if (type == TYPE_SIGNATURE || !VISIT_FORMAL_TYPE_PARAMETER_STATES.contains(state)) { throw new IllegalStateException(); } checkIdentifier(name, "formal type parameter"); state = State.FORMAL; if (signatureVisitor != null) { signatureVisitor.visitFormalTypeParameter(name); } } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitFormalTypeParameter_typeSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); Executable visitFormalTypeParameter = () -> checkSignatureAdapter.visitFormalTypeParameter("T"); assertThrows(IllegalStateException.class, visitFormalTypeParameter); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitClassBound() { if (type == TYPE_SIGNATURE || !VISIT_CLASS_BOUND_STATES.contains(state)) { throw new IllegalStateException(); } state = State.BOUND; return new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitClassBound()); } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitClassBound_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); Executable visitClassBound = () -> checkSignatureAdapter.visitClassBound(); assertThrows(IllegalStateException.class, visitClassBound); }
@Test public void testVisitClassBound_typeSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); Executable visitClassBound = () -> checkSignatureAdapter.visitClassBound(); assertThrows(IllegalStateException.class, visitClassBound); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitInterfaceBound() { if (type == TYPE_SIGNATURE || !VISIT_INTERFACE_BOUND_STATES.contains(state)) { throw new IllegalStateException(); } return new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitInterfaceBound()); } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitInterfaceBound_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); Executable visitInterfaceBound = () -> checkSignatureAdapter.visitInterfaceBound(); assertThrows(IllegalStateException.class, visitInterfaceBound); }
@Test public void testVisitInterfaceBound_typeSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); Executable visitInterfaceBound = () -> checkSignatureAdapter.visitInterfaceBound(); assertThrows(IllegalStateException.class, visitInterfaceBound); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitSuperclass() { if (type != CLASS_SIGNATURE || !VISIT_SUPER_CLASS_STATES.contains(state)) { throw new IllegalStateException(); } state = State.SUPER; return new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitSuperclass()); } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitSuperClass_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); checkSignatureAdapter.visitSuperclass(); Executable visitSuperClass = () -> checkSignatureAdapter.visitSuperclass(); assertThrows(IllegalStateException.class, visitSuperClass); }
@Test public void testVisitSuperClass_methodSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.METHOD_SIGNATURE, null); Executable visitSuperClass = () -> checkSignatureAdapter.visitSuperclass(); assertThrows(IllegalStateException.class, visitSuperClass); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitInterface() { if (type != CLASS_SIGNATURE || !VISIT_INTERFACE_STATES.contains(state)) { throw new IllegalStateException(); } return new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitInterface()); } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitInterface_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); Executable visitInterface = () -> checkSignatureAdapter.visitInterface(); assertThrows(IllegalStateException.class, visitInterface); }
@Test public void testVisitInterface_methodSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.METHOD_SIGNATURE, null); Executable visitInterface = () -> checkSignatureAdapter.visitInterface(); assertThrows(IllegalStateException.class, visitInterface); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitParameterType() { if (type != METHOD_SIGNATURE || !VISIT_PARAMETER_TYPE_STATES.contains(state)) { throw new IllegalStateException(); } state = State.PARAM; return new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitParameterType()); } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitParameterType_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); Executable visitParameterType = () -> checkSignatureAdapter.visitParameterType(); assertThrows(IllegalStateException.class, visitParameterType); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitReturnType() { if (type != METHOD_SIGNATURE || !VISIT_RETURN_TYPE_STATES.contains(state)) { throw new IllegalStateException(); } state = State.RETURN; CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitReturnType()); checkSignatureAdapter.canBeVoid = true; return checkSignatureAdapter; } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitReturnType_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); Executable visitReturnType = () -> checkSignatureAdapter.visitReturnType(); assertThrows(IllegalStateException.class, visitReturnType); }
@Test public void testVisitReturnType_methodSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.METHOD_SIGNATURE, null); checkSignatureAdapter.visitReturnType(); Executable visitReturnType = () -> checkSignatureAdapter.visitReturnType(); assertThrows(IllegalStateException.class, visitReturnType); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitExceptionType() { if (type != METHOD_SIGNATURE || !VISIT_EXCEPTION_TYPE_STATES.contains(state)) { throw new IllegalStateException(); } return new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitExceptionType()); } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitExceptionType_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); Executable visitExceptionType = () -> checkSignatureAdapter.visitExceptionType(); assertThrows(IllegalStateException.class, visitExceptionType); }
@Test public void testVisitExceptionType_methodSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.METHOD_SIGNATURE, null); Executable visitExceptionType = () -> checkSignatureAdapter.visitExceptionType(); assertThrows(IllegalStateException.class, visitExceptionType); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public SignatureVisitor visitArrayType() { if (type != TYPE_SIGNATURE || state != State.EMPTY) { throw new IllegalStateException(); } state = State.SIMPLE_TYPE; return new CheckSignatureAdapter( TYPE_SIGNATURE, signatureVisitor == null ? null : signatureVisitor.visitArrayType()); } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitArrayType_classSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.CLASS_SIGNATURE, null); Executable visitArrayType = () -> checkSignatureAdapter.visitArrayType(); assertThrows(IllegalStateException.class, visitArrayType); }
@Test public void testVisitArrayType_typeSignature_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); checkSignatureAdapter.visitArrayType(); Executable visitArrayType = () -> checkSignatureAdapter.visitArrayType(); assertThrows(IllegalStateException.class, visitArrayType); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public void visitInnerClassType(final String name) { if (state != State.CLASS_TYPE) { throw new IllegalStateException(); } checkIdentifier(name, "inner class name"); if (signatureVisitor != null) { signatureVisitor.visitInnerClassType(name); } } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitInnerClassType_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); Executable visitInnerClassType = () -> checkSignatureAdapter.visitInnerClassType("A"); assertThrows(IllegalStateException.class, visitInnerClassType); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public void visitTypeArgument() { if (state != State.CLASS_TYPE) { throw new IllegalStateException(); } if (signatureVisitor != null) { signatureVisitor.visitTypeArgument(); } } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitTypeArgument_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); Executable visitTypeArgument = () -> checkSignatureAdapter.visitTypeArgument(); assertThrows(IllegalStateException.class, visitTypeArgument); }
@Test public void testVisitTypeArgument_wildcard_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); Executable visitTypeArgument = () -> checkSignatureAdapter.visitTypeArgument('+'); assertThrows(IllegalStateException.class, visitTypeArgument); } |
### Question:
CheckSignatureAdapter extends SignatureVisitor { @Override public void visitEnd() { if (state != State.CLASS_TYPE) { throw new IllegalStateException(); } state = State.END; if (signatureVisitor != null) { signatureVisitor.visitEnd(); } } CheckSignatureAdapter(final int type, final SignatureVisitor signatureVisitor); protected CheckSignatureAdapter(
final int api, final int type, final SignatureVisitor signatureVisitor); @Override void visitFormalTypeParameter(final String name); @Override SignatureVisitor visitClassBound(); @Override SignatureVisitor visitInterfaceBound(); @Override SignatureVisitor visitSuperclass(); @Override SignatureVisitor visitInterface(); @Override SignatureVisitor visitParameterType(); @Override SignatureVisitor visitReturnType(); @Override SignatureVisitor visitExceptionType(); @Override void visitBaseType(final char descriptor); @Override void visitTypeVariable(final String name); @Override SignatureVisitor visitArrayType(); @Override void visitClassType(final String name); @Override void visitInnerClassType(final String name); @Override void visitTypeArgument(); @Override SignatureVisitor visitTypeArgument(final char wildcard); @Override void visitEnd(); static final int CLASS_SIGNATURE; static final int METHOD_SIGNATURE; static final int TYPE_SIGNATURE; }### Answer:
@Test public void testVisitEnd_illegalState() { CheckSignatureAdapter checkSignatureAdapter = new CheckSignatureAdapter(CheckSignatureAdapter.TYPE_SIGNATURE, null); Executable visitEnd = () -> checkSignatureAdapter.visitEnd(); assertThrows(IllegalStateException.class, visitEnd); } |
### Question:
Method { public static Method getMethod(final java.lang.reflect.Method method) { return new Method(method.getName(), Type.getMethodDescriptor(method)); } Method(final String name, final String descriptor); Method(final String name, final Type returnType, final Type[] argumentTypes); static Method getMethod(final java.lang.reflect.Method method); static Method getMethod(final java.lang.reflect.Constructor<?> constructor); static Method getMethod(final String method); static Method getMethod(final String method, final boolean defaultPackage); String getName(); String getDescriptor(); Type getReturnType(); Type[] getArgumentTypes(); @Override String toString(); @Override boolean equals(final Object other); @Override int hashCode(); }### Answer:
@Test public void testGetMethod_fromInvalidDescriptor() { assertThrows(IllegalArgumentException.class, () -> Method.getMethod("name()")); assertThrows(IllegalArgumentException.class, () -> Method.getMethod("void name")); assertThrows(IllegalArgumentException.class, () -> Method.getMethod("void name(]")); } |
### Question:
Method { @Override public boolean equals(final Object other) { if (!(other instanceof Method)) { return false; } Method otherMethod = (Method) other; return name.equals(otherMethod.name) && descriptor.equals(otherMethod.descriptor); } Method(final String name, final String descriptor); Method(final String name, final Type returnType, final Type[] argumentTypes); static Method getMethod(final java.lang.reflect.Method method); static Method getMethod(final java.lang.reflect.Constructor<?> constructor); static Method getMethod(final String method); static Method getMethod(final String method, final boolean defaultPackage); String getName(); String getDescriptor(); Type getReturnType(); Type[] getArgumentTypes(); @Override String toString(); @Override boolean equals(final Object other); @Override int hashCode(); }### Answer:
@Test public void testEquals() { Method nullMethod = null; boolean equalsNull = new Method("name", "()V").equals(nullMethod); boolean equalsMethodWithDifferentName = new Method("name", "()V").equals(new Method("other", "()V")); boolean equalsMethodWithDifferentDescriptor = new Method("name", "()V").equals(new Method("name", "(I)J")); boolean equalsSame = new Method("name", "()V").equals(Method.getMethod("void name()")); assertFalse(equalsNull); assertFalse(equalsMethodWithDifferentName); assertFalse(equalsMethodWithDifferentDescriptor); assertTrue(equalsSame); }
@Test public void testEquals() { assertNotEquals(new Method("name", "()V"), null); assertNotEquals(new Method("name", "()V"), new Method("other", "()V")); assertNotEquals(new Method("name", "()V"), new Method("name", "(I)J")); assertEquals(new Method("name", "()V"), Method.getMethod("void name()")); } |
### Question:
Method { @Override public int hashCode() { return name.hashCode() ^ descriptor.hashCode(); } Method(final String name, final String descriptor); Method(final String name, final Type returnType, final Type[] argumentTypes); static Method getMethod(final java.lang.reflect.Method method); static Method getMethod(final java.lang.reflect.Constructor<?> constructor); static Method getMethod(final String method); static Method getMethod(final String method, final boolean defaultPackage); String getName(); String getDescriptor(); Type getReturnType(); Type[] getArgumentTypes(); @Override String toString(); @Override boolean equals(final Object other); @Override int hashCode(); }### Answer:
@Test public void testHashCode() { assertNotEquals(0, new Method("name", "()V").hashCode()); } |
### Question:
BasicValue implements Value { public boolean isReference() { return type != null && (type.getSort() == Type.OBJECT || type.getSort() == Type.ARRAY); } BasicValue(final Type type); Type getType(); @Override int getSize(); boolean isReference(); @Override boolean equals(final Object value); @Override int hashCode(); @Override String toString(); static final BasicValue UNINITIALIZED_VALUE; static final BasicValue INT_VALUE; static final BasicValue FLOAT_VALUE; static final BasicValue LONG_VALUE; static final BasicValue DOUBLE_VALUE; static final BasicValue REFERENCE_VALUE; static final BasicValue RETURNADDRESS_VALUE; }### Answer:
@Test public void testIsReference() { assertTrue(BasicValue.REFERENCE_VALUE.isReference()); assertTrue(new BasicValue(Type.getObjectType("[I")).isReference()); assertFalse(BasicValue.UNINITIALIZED_VALUE.isReference()); assertFalse(BasicValue.INT_VALUE.isReference()); } |
### Question:
Handler { static int getExceptionTableLength(final Handler firstHandler) { int length = 0; Handler handler = firstHandler; while (handler != null) { length++; handler = handler.nextHandler; } return length; } Handler(
final Label startPc,
final Label endPc,
final Label handlerPc,
final int catchType,
final String catchTypeDescriptor); Handler(final Handler handler, final Label startPc, final Label endPc); }### Answer:
@Test public void testGetExceptionTableLength() { Handler handler = newHandler(10, 20); assertEquals(0, Handler.getExceptionTableLength(null)); assertEquals(1, Handler.getExceptionTableLength(handler)); } |
### Question:
Handler { static int getExceptionTableSize(final Handler firstHandler) { return 2 + 8 * getExceptionTableLength(firstHandler); } Handler(
final Label startPc,
final Label endPc,
final Label handlerPc,
final int catchType,
final String catchTypeDescriptor); Handler(final Handler handler, final Label startPc, final Label endPc); }### Answer:
@Test public void testGetExceptionTableSize() { Handler handlerList = Handler.removeRange(newHandler(10, 20), newLabel(13), newLabel(17)); assertEquals(2, Handler.getExceptionTableSize(null)); assertEquals(18, Handler.getExceptionTableSize(handlerList)); } |
### Question:
Handler { static void putExceptionTable(final Handler firstHandler, final ByteVector output) { output.putShort(getExceptionTableLength(firstHandler)); Handler handler = firstHandler; while (handler != null) { output .putShort(handler.startPc.bytecodeOffset) .putShort(handler.endPc.bytecodeOffset) .putShort(handler.handlerPc.bytecodeOffset) .putShort(handler.catchType); handler = handler.nextHandler; } } Handler(
final Label startPc,
final Label endPc,
final Label handlerPc,
final int catchType,
final String catchTypeDescriptor); Handler(final Handler handler, final Label startPc, final Label endPc); }### Answer:
@Test public void testPutExceptionTable() { Handler handlerList = Handler.removeRange(newHandler(10, 20), newLabel(13), newLabel(17)); ByteVector byteVector = new ByteVector(); Handler.putExceptionTable(handlerList, byteVector); assertEquals(18, byteVector.length); } |
### Question:
ClassReader { public int readByte(final int offset) { return classFileBuffer[offset] & 0xFF; } ClassReader(final byte[] classFile); ClassReader(
final byte[] classFileBuffer,
final int classFileOffset,
final int classFileLength); ClassReader(
final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion); ClassReader(final InputStream inputStream); ClassReader(final String className); int getAccess(); String getClassName(); String getSuperName(); String[] getInterfaces(); void accept(final ClassVisitor classVisitor, final int parsingOptions); void accept(
final ClassVisitor classVisitor,
final Attribute[] attributePrototypes,
final int parsingOptions); int getItemCount(); int getItem(final int constantPoolEntryIndex); int getMaxStringLength(); int readByte(final int offset); int readUnsignedShort(final int offset); short readShort(final int offset); int readInt(final int offset); long readLong(final int offset); String readUTF8(final int offset, final char[] charBuffer); String readClass(final int offset, final char[] charBuffer); String readModule(final int offset, final char[] charBuffer); String readPackage(final int offset, final char[] charBuffer); Object readConst(final int constantPoolEntryIndex, final char[] charBuffer); static final int SKIP_CODE; static final int SKIP_DEBUG; static final int SKIP_FRAMES; static final int EXPAND_FRAMES; @Deprecated
// DontCheck(MemberName): can't be renamed (for backward binary compatibility).
final byte[] b; final int header; }### Answer:
@Test public void testReadByte() throws IOException { ClassReader classReader = new ClassReader(getClass().getName()); assertEquals(classReader.classFileBuffer[0] & 0xFF, classReader.readByte(0)); } |
### Question:
ClassReader { public int getItem(final int constantPoolEntryIndex) { return cpInfoOffsets[constantPoolEntryIndex]; } ClassReader(final byte[] classFile); ClassReader(
final byte[] classFileBuffer,
final int classFileOffset,
final int classFileLength); ClassReader(
final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion); ClassReader(final InputStream inputStream); ClassReader(final String className); int getAccess(); String getClassName(); String getSuperName(); String[] getInterfaces(); void accept(final ClassVisitor classVisitor, final int parsingOptions); void accept(
final ClassVisitor classVisitor,
final Attribute[] attributePrototypes,
final int parsingOptions); int getItemCount(); int getItem(final int constantPoolEntryIndex); int getMaxStringLength(); int readByte(final int offset); int readUnsignedShort(final int offset); short readShort(final int offset); int readInt(final int offset); long readLong(final int offset); String readUTF8(final int offset, final char[] charBuffer); String readClass(final int offset, final char[] charBuffer); String readModule(final int offset, final char[] charBuffer); String readPackage(final int offset, final char[] charBuffer); Object readConst(final int constantPoolEntryIndex, final char[] charBuffer); static final int SKIP_CODE; static final int SKIP_DEBUG; static final int SKIP_FRAMES; static final int EXPAND_FRAMES; @Deprecated
// DontCheck(MemberName): can't be renamed (for backward binary compatibility).
final byte[] b; final int header; }### Answer:
@Test public void testGetItem() throws IOException { ClassReader classReader = new ClassReader(getClass().getName()); int item = classReader.getItem(1); assertTrue(item >= 10); assertTrue(item < classReader.header); } |
### Question:
ClassReader { public int getAccess() { return readUnsignedShort(header); } ClassReader(final byte[] classFile); ClassReader(
final byte[] classFileBuffer,
final int classFileOffset,
final int classFileLength); ClassReader(
final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion); ClassReader(final InputStream inputStream); ClassReader(final String className); int getAccess(); String getClassName(); String getSuperName(); String[] getInterfaces(); void accept(final ClassVisitor classVisitor, final int parsingOptions); void accept(
final ClassVisitor classVisitor,
final Attribute[] attributePrototypes,
final int parsingOptions); int getItemCount(); int getItem(final int constantPoolEntryIndex); int getMaxStringLength(); int readByte(final int offset); int readUnsignedShort(final int offset); short readShort(final int offset); int readInt(final int offset); long readLong(final int offset); String readUTF8(final int offset, final char[] charBuffer); String readClass(final int offset, final char[] charBuffer); String readModule(final int offset, final char[] charBuffer); String readPackage(final int offset, final char[] charBuffer); Object readConst(final int constantPoolEntryIndex, final char[] charBuffer); static final int SKIP_CODE; static final int SKIP_DEBUG; static final int SKIP_FRAMES; static final int EXPAND_FRAMES; @Deprecated
// DontCheck(MemberName): can't be renamed (for backward binary compatibility).
final byte[] b; final int header; }### Answer:
@Test public void testGetAccess() throws Exception { String name = getClass().getName(); assertEquals(ACC_PUBLIC | ACC_SUPER, new ClassReader(name).getAccess()); } |
### Question:
ClassReader { public String getClassName() { return readClass(header + 2, new char[maxStringLength]); } ClassReader(final byte[] classFile); ClassReader(
final byte[] classFileBuffer,
final int classFileOffset,
final int classFileLength); ClassReader(
final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion); ClassReader(final InputStream inputStream); ClassReader(final String className); int getAccess(); String getClassName(); String getSuperName(); String[] getInterfaces(); void accept(final ClassVisitor classVisitor, final int parsingOptions); void accept(
final ClassVisitor classVisitor,
final Attribute[] attributePrototypes,
final int parsingOptions); int getItemCount(); int getItem(final int constantPoolEntryIndex); int getMaxStringLength(); int readByte(final int offset); int readUnsignedShort(final int offset); short readShort(final int offset); int readInt(final int offset); long readLong(final int offset); String readUTF8(final int offset, final char[] charBuffer); String readClass(final int offset, final char[] charBuffer); String readModule(final int offset, final char[] charBuffer); String readPackage(final int offset, final char[] charBuffer); Object readConst(final int constantPoolEntryIndex, final char[] charBuffer); static final int SKIP_CODE; static final int SKIP_DEBUG; static final int SKIP_FRAMES; static final int EXPAND_FRAMES; @Deprecated
// DontCheck(MemberName): can't be renamed (for backward binary compatibility).
final byte[] b; final int header; }### Answer:
@Test public void testGetClassName() throws Exception { String name = getClass().getName(); assertEquals(name.replace('.', '/'), new ClassReader(name).getClassName()); } |
### Question:
ClassReader { public String getSuperName() { return readClass(header + 4, new char[maxStringLength]); } ClassReader(final byte[] classFile); ClassReader(
final byte[] classFileBuffer,
final int classFileOffset,
final int classFileLength); ClassReader(
final byte[] classFileBuffer, final int classFileOffset, final boolean checkClassVersion); ClassReader(final InputStream inputStream); ClassReader(final String className); int getAccess(); String getClassName(); String getSuperName(); String[] getInterfaces(); void accept(final ClassVisitor classVisitor, final int parsingOptions); void accept(
final ClassVisitor classVisitor,
final Attribute[] attributePrototypes,
final int parsingOptions); int getItemCount(); int getItem(final int constantPoolEntryIndex); int getMaxStringLength(); int readByte(final int offset); int readUnsignedShort(final int offset); short readShort(final int offset); int readInt(final int offset); long readLong(final int offset); String readUTF8(final int offset, final char[] charBuffer); String readClass(final int offset, final char[] charBuffer); String readModule(final int offset, final char[] charBuffer); String readPackage(final int offset, final char[] charBuffer); Object readConst(final int constantPoolEntryIndex, final char[] charBuffer); static final int SKIP_CODE; static final int SKIP_DEBUG; static final int SKIP_FRAMES; static final int EXPAND_FRAMES; @Deprecated
// DontCheck(MemberName): can't be renamed (for backward binary compatibility).
final byte[] b; final int header; }### Answer:
@Test public void testGetSuperName() throws Exception { ClassReader thisClassReader = new ClassReader(getClass().getName()); ClassReader objectClassReader = new ClassReader(Object.class.getName()); assertEquals(AsmTest.class.getName().replace('.', '/'), thisClassReader.getSuperName()); assertEquals(null, objectClassReader.getSuperName()); } |
### Question:
Handle { @Override public int hashCode() { return tag + (isInterface ? 64 : 0) + owner.hashCode() * name.hashCode() * descriptor.hashCode(); } @Deprecated Handle(final int tag, final String owner, final String name, final String descriptor); Handle(
final int tag,
final String owner,
final String name,
final String descriptor,
final boolean isInterface); int getTag(); String getOwner(); String getName(); String getDesc(); boolean isInterface(); @Override boolean equals(final Object object); @Override int hashCode(); @Override String toString(); }### Answer:
@Test public void testHashCode() { Handle handle1 = new Handle(Opcodes.H_INVOKESTATIC, "owner", "name", "descriptor", false); Handle handle2 = new Handle(Opcodes.H_INVOKESTATIC, "owner", "name", "descriptor", true); assertNotEquals(0, handle1.hashCode()); assertNotEquals(0, handle2.hashCode()); } |
### Question:
BasicValue implements Value { @Override public boolean equals(final Object value) { if (value == this) { return true; } else if (value instanceof BasicValue) { if (type == null) { return ((BasicValue) value).type == null; } else { return type.equals(((BasicValue) value).type); } } else { return false; } } BasicValue(final Type type); Type getType(); @Override int getSize(); boolean isReference(); @Override boolean equals(final Object value); @Override int hashCode(); @Override String toString(); static final BasicValue UNINITIALIZED_VALUE; static final BasicValue INT_VALUE; static final BasicValue FLOAT_VALUE; static final BasicValue LONG_VALUE; static final BasicValue DOUBLE_VALUE; static final BasicValue REFERENCE_VALUE; static final BasicValue RETURNADDRESS_VALUE; }### Answer:
@Test public void testEquals() { boolean equalsSameUninitializedValue = new BasicValue(null).equals(BasicValue.UNINITIALIZED_VALUE); boolean equalsSameValue = new BasicValue(Type.INT_TYPE).equals(BasicValue.INT_VALUE); boolean equalsThis = BasicValue.INT_VALUE.equals(BasicValue.INT_VALUE); boolean equalsDifferentClass = BasicValue.INT_VALUE.equals(new Object()); assertTrue(equalsSameUninitializedValue); assertTrue(equalsSameValue); assertTrue(equalsThis); assertFalse(equalsDifferentClass); }
@Test public void testEquals() { assertEquals(new BasicValue(null), BasicValue.UNINITIALIZED_VALUE); assertEquals(new BasicValue(Type.INT_TYPE), BasicValue.INT_VALUE); assertEquals(BasicValue.INT_VALUE, BasicValue.INT_VALUE); assertNotEquals(new Object(), BasicValue.INT_VALUE); } |
### Question:
Label { public int getOffset() { if ((flags & FLAG_RESOLVED) == 0) { throw new IllegalStateException("Label offset position has not been resolved yet"); } return bytecodeOffset; } Label(); int getOffset(); @Override String toString(); public Object info; }### Answer:
@Test public void testGetOffset() { MethodVisitor methodVisitor = new ClassWriter(0).visitMethod(Opcodes.ACC_PUBLIC, "m", "()V", null, null); methodVisitor.visitCode(); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); Label label = new Label(); methodVisitor.visitLabel(label); assertEquals(1, label.getOffset()); }
@Test public void testGetOffset_illegalState() { Executable getOffset = () -> new Label().getOffset(); Exception exception = assertThrows(IllegalStateException.class, getOffset); assertEquals("Label offset position has not been resolved yet", exception.getMessage()); } |
### Question:
Label { @Override public String toString() { return "L" + System.identityHashCode(this); } Label(); int getOffset(); @Override String toString(); public Object info; }### Answer:
@Test public void testToString() { String string = new Label().toString(); assertEquals('L', string.charAt(0)); } |
### Question:
ByteVector { public ByteVector putByte(final int byteValue) { int currentLength = length; if (currentLength + 1 > data.length) { enlarge(1); } data[currentLength++] = (byte) byteValue; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPutByte() { ByteVector byteVector = new ByteVector(0); byteVector.putByte(1); assertArrayEquals(new byte[] {1}, toArray(byteVector)); } |
### Question:
ByteVector { final ByteVector put11(final int byteValue1, final int byteValue2) { int currentLength = length; if (currentLength + 2 > data.length) { enlarge(2); } byte[] currentData = data; currentData[currentLength++] = (byte) byteValue1; currentData[currentLength++] = (byte) byteValue2; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPut11() { ByteVector byteVector = new ByteVector(0); byteVector.put11(1, 2); assertArrayEquals(new byte[] {1, 2}, toArray(byteVector)); } |
### Question:
ByteVector { public ByteVector putShort(final int shortValue) { int currentLength = length; if (currentLength + 2 > data.length) { enlarge(2); } byte[] currentData = data; currentData[currentLength++] = (byte) (shortValue >>> 8); currentData[currentLength++] = (byte) shortValue; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPutShort() { ByteVector byteVector = new ByteVector(0); byteVector.putShort(0x0102); assertArrayEquals(new byte[] {1, 2}, toArray(byteVector)); } |
### Question:
ByteVector { final ByteVector put12(final int byteValue, final int shortValue) { int currentLength = length; if (currentLength + 3 > data.length) { enlarge(3); } byte[] currentData = data; currentData[currentLength++] = (byte) byteValue; currentData[currentLength++] = (byte) (shortValue >>> 8); currentData[currentLength++] = (byte) shortValue; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPut12() { ByteVector byteVector = new ByteVector(0); byteVector.put12(1, 0x0203); assertArrayEquals(new byte[] {1, 2, 3}, toArray(byteVector)); } |
### Question:
ByteVector { final ByteVector put112(final int byteValue1, final int byteValue2, final int shortValue) { int currentLength = length; if (currentLength + 4 > data.length) { enlarge(4); } byte[] currentData = data; currentData[currentLength++] = (byte) byteValue1; currentData[currentLength++] = (byte) byteValue2; currentData[currentLength++] = (byte) (shortValue >>> 8); currentData[currentLength++] = (byte) shortValue; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPut112() { ByteVector byteVector = new ByteVector(0); byteVector.put112(1, 2, 0x0304); assertArrayEquals(new byte[] {1, 2, 3, 4}, toArray(byteVector)); } |
### Question:
ByteVector { public ByteVector putInt(final int intValue) { int currentLength = length; if (currentLength + 4 > data.length) { enlarge(4); } byte[] currentData = data; currentData[currentLength++] = (byte) (intValue >>> 24); currentData[currentLength++] = (byte) (intValue >>> 16); currentData[currentLength++] = (byte) (intValue >>> 8); currentData[currentLength++] = (byte) intValue; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPutInt() { ByteVector byteVector = new ByteVector(0); byteVector.putInt(0x01020304); assertArrayEquals(new byte[] {1, 2, 3, 4}, toArray(byteVector)); } |
### Question:
ByteVector { final ByteVector put122(final int byteValue, final int shortValue1, final int shortValue2) { int currentLength = length; if (currentLength + 5 > data.length) { enlarge(5); } byte[] currentData = data; currentData[currentLength++] = (byte) byteValue; currentData[currentLength++] = (byte) (shortValue1 >>> 8); currentData[currentLength++] = (byte) shortValue1; currentData[currentLength++] = (byte) (shortValue2 >>> 8); currentData[currentLength++] = (byte) shortValue2; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPut122() { ByteVector byteVector = new ByteVector(0); byteVector.put122(1, 0x0203, 0x0405); assertArrayEquals(new byte[] {1, 2, 3, 4, 5}, toArray(byteVector)); } |
### Question:
ByteVector { public ByteVector putLong(final long longValue) { int currentLength = length; if (currentLength + 8 > data.length) { enlarge(8); } byte[] currentData = data; int intValue = (int) (longValue >>> 32); currentData[currentLength++] = (byte) (intValue >>> 24); currentData[currentLength++] = (byte) (intValue >>> 16); currentData[currentLength++] = (byte) (intValue >>> 8); currentData[currentLength++] = (byte) intValue; intValue = (int) longValue; currentData[currentLength++] = (byte) (intValue >>> 24); currentData[currentLength++] = (byte) (intValue >>> 16); currentData[currentLength++] = (byte) (intValue >>> 8); currentData[currentLength++] = (byte) intValue; length = currentLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPutLong() { ByteVector byteVector = new ByteVector(0); byteVector.putLong(0x0102030405060708L); assertArrayEquals(new byte[] {1, 2, 3, 4, 5, 6, 7, 8}, toArray(byteVector)); } |
### Question:
ByteVector { public ByteVector putByteArray( final byte[] byteArrayValue, final int byteOffset, final int byteLength) { if (length + byteLength > data.length) { enlarge(byteLength); } if (byteArrayValue != null) { System.arraycopy(byteArrayValue, byteOffset, data, length, byteLength); } length += byteLength; return this; } ByteVector(); ByteVector(final int initialCapacity); ByteVector(final byte[] data); ByteVector putByte(final int byteValue); ByteVector putShort(final int shortValue); ByteVector putInt(final int intValue); ByteVector putLong(final long longValue); ByteVector putUTF8(final String stringValue); ByteVector putByteArray(
final byte[] byteArrayValue, final int byteOffset, final int byteLength); }### Answer:
@Test public void testPutByteArray() { ByteVector byteVector = new ByteVector(0); byteVector.putByteArray(new byte[] {0, 1, 2, 3, 4, 5}, 1, 3); assertArrayEquals(new byte[] {1, 2, 3}, toArray(byteVector)); } |
### Question:
TypePath { public int getLength() { return typePathContainer[typePathOffset]; } TypePath(final byte[] typePathContainer, final int typePathOffset); int getLength(); int getStep(final int index); int getStepArgument(final int index); static TypePath fromString(final String typePath); @Override String toString(); static final int ARRAY_ELEMENT; static final int INNER_TYPE; static final int WILDCARD_BOUND; static final int TYPE_ARGUMENT; }### Answer:
@Test public void testGetLength() { assertEquals(5, TypePath.fromString("[.[*0").getLength()); assertEquals(5, TypePath.fromString("[*0;*[").getLength()); assertEquals(1, TypePath.fromString("10;").getLength()); assertEquals(2, TypePath.fromString("1;0;").getLength()); } |
### Question:
TypePath { public int getStep(final int index) { return typePathContainer[typePathOffset + 2 * index + 1]; } TypePath(final byte[] typePathContainer, final int typePathOffset); int getLength(); int getStep(final int index); int getStepArgument(final int index); static TypePath fromString(final String typePath); @Override String toString(); static final int ARRAY_ELEMENT; static final int INNER_TYPE; static final int WILDCARD_BOUND; static final int TYPE_ARGUMENT; }### Answer:
@Test public void testGetStep() { TypePath typePath = TypePath.fromString("[.[*7"); assertEquals(TypePath.ARRAY_ELEMENT, typePath.getStep(0)); assertEquals(TypePath.INNER_TYPE, typePath.getStep(1)); assertEquals(TypePath.WILDCARD_BOUND, typePath.getStep(3)); assertEquals(TypePath.TYPE_ARGUMENT, typePath.getStep(4)); assertEquals(7, typePath.getStepArgument(4)); } |
### Question:
Constants { static boolean isWhitelisted(final String internalName) { if (!internalName.startsWith("org/objectweb/asm/")) { return false; } String member = "(Annotation|Class|Field|Method|Module|RecordComponent|Signature)"; return internalName.contains("Test$") || Pattern.matches( "org/objectweb/asm/util/Trace" + member + "Visitor(\\$.*)?", internalName) || Pattern.matches( "org/objectweb/asm/util/Check" + member + "Adapter(\\$.*)?", internalName); } private Constants(); }### Answer:
@Test public void testIsWhitelisted() { assertFalse(Constants.isWhitelisted("org/jacoco/core/internal/flow/ClassProbesVisitor")); assertFalse(Constants.isWhitelisted("org/objectweb/asm/ClassWriter")); assertFalse(Constants.isWhitelisted("org/objectweb/asm/util/CheckClassVisitor")); assertFalse(Constants.isWhitelisted("org/objectweb/asm/ClassWriterTest")); assertTrue(Constants.isWhitelisted("org/objectweb/asm/ClassWriterTest$DeadCodeInserter")); assertTrue(Constants.isWhitelisted("org/objectweb/asm/util/TraceClassVisitor")); assertTrue(Constants.isWhitelisted("org/objectweb/asm/util/CheckClassAdapter")); } |
### Question:
Constants { static void checkIsPreview(final InputStream classInputStream) { if (classInputStream == null) { throw new IllegalStateException("Bytecode not available, can't check class version"); } int minorVersion; try (DataInputStream callerClassStream = new DataInputStream(classInputStream); ) { callerClassStream.readInt(); minorVersion = callerClassStream.readUnsignedShort(); } catch (IOException ioe) { throw new IllegalStateException("I/O error, can't check class version", ioe); } if (minorVersion != 0xFFFF) { throw new IllegalStateException( "ASM9_EXPERIMENTAL can only be used by classes compiled with --enable-preview"); } } private Constants(); }### Answer:
@Test public void testCheckIsPreview_nullStream() { Executable checkIsPreview = () -> Constants.checkIsPreview(null); assertThrows(IllegalStateException.class, checkIsPreview); }
@Test public void testCheckIsPreview_invalidStream() { InputStream invalidStream = new ByteArrayInputStream(new byte[4]); Executable checkIsPreview = () -> Constants.checkIsPreview(invalidStream); assertThrows(IllegalStateException.class, checkIsPreview); }
@Test public void testCheckIsPreview_nonPreviewClass() { InputStream nonPreviewStream = new ByteArrayInputStream(new byte[8]); Executable checkIsPreview = () -> Constants.checkIsPreview(nonPreviewStream); assertThrows(IllegalStateException.class, checkIsPreview); }
@Test public void testCheckIsPreview_previewClass() { byte[] previewClass = new byte[] {0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF}; InputStream previewStream = new ByteArrayInputStream(previewClass); Executable checkIsPreview = () -> Constants.checkIsPreview(previewStream); assertDoesNotThrow(checkIsPreview); } |
### Question:
Attribute { public boolean isUnknown() { return true; } protected Attribute(final String type); boolean isUnknown(); boolean isCodeAttribute(); final String type; }### Answer:
@Test public void testIsUnknown() { assertTrue(new Attribute("Comment").isUnknown()); } |
### Question:
Attribute { protected Label[] getLabels() { return new Label[0]; } protected Attribute(final String type); boolean isUnknown(); boolean isCodeAttribute(); final String type; }### Answer:
@Test public void testGetLabels() { assertArrayEquals(new Label[0], new Attribute("Comment").getLabels()); } |
### Question:
Util { static <T> List<T> asArrayList(final int length) { List<T> list = new ArrayList<>(length); for (int i = 0; i < length; ++i) { list.add(null); } return list; } private Util(); }### Answer:
@Test public void testAsArrayList_nullArray() { assertTrue(Util.asArrayList((Object[]) null).isEmpty()); assertTrue(Util.asArrayList((byte[]) null).isEmpty()); assertTrue(Util.asArrayList((boolean[]) null).isEmpty()); assertTrue(Util.asArrayList((short[]) null).isEmpty()); assertTrue(Util.asArrayList((char[]) null).isEmpty()); assertTrue(Util.asArrayList((int[]) null).isEmpty()); assertTrue(Util.asArrayList((float[]) null).isEmpty()); assertTrue(Util.asArrayList((long[]) null).isEmpty()); assertTrue(Util.asArrayList((double[]) null).isEmpty()); }
@Test public void testAsArrayList_withLength() { List<String> strings = Util.asArrayList(3); assertEquals(3, strings.size()); assertNull(strings.get(0)); assertNull(strings.get(1)); assertNull(strings.get(2)); }
@Test public void testAsArrayList_withLengthAndArray() { List<Integer> ints = Util.asArrayList(3, new Integer[] {1, 2, 3, 4, 5}); assertEquals(3, ints.size()); assertEquals(Integer.valueOf(1), ints.get(0)); assertEquals(Integer.valueOf(2), ints.get(1)); assertEquals(Integer.valueOf(3), ints.get(2)); } |
### Question:
LookupSwitchInsnNode extends AbstractInsnNode { @Override public int getType() { return LOOKUPSWITCH_INSN; } LookupSwitchInsnNode(final LabelNode dflt, final int[] keys, final LabelNode[] labels); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public LabelNode dflt; public List<Integer> keys; public List<LabelNode> labels; }### Answer:
@Test public void testConstructor() { LabelNode dflt = new LabelNode(); int[] keys = new int[] {1}; LabelNode[] labels = new LabelNode[] {new LabelNode()}; LookupSwitchInsnNode lookupSwitchInsnNode = new LookupSwitchInsnNode(dflt, keys, labels); assertEquals(AbstractInsnNode.LOOKUPSWITCH_INSN, lookupSwitchInsnNode.getType()); assertEquals(dflt, lookupSwitchInsnNode.dflt); assertEquals(Arrays.asList(new Integer[] {1}), lookupSwitchInsnNode.keys); assertEquals(Arrays.asList(labels), lookupSwitchInsnNode.labels); } |
### Question:
InvokeDynamicInsnNode extends AbstractInsnNode { @Override public int getType() { return INVOKE_DYNAMIC_INSN; } InvokeDynamicInsnNode(
final String name,
final String descriptor,
final Handle bootstrapMethodHandle,
final Object... bootstrapMethodArguments); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String name; public String desc; public Handle bsm; public Object[] bsmArgs; }### Answer:
@Test public void testConstructor() { Handle handle = new Handle(Opcodes.H_INVOKESTATIC, "owner", "name", "()V", false); Object[] bootstrapMethodArguments = new Object[] {"s"}; InvokeDynamicInsnNode invokeDynamicInsnNode = new InvokeDynamicInsnNode("name", "()V", handle, bootstrapMethodArguments); assertEquals(Opcodes.INVOKEDYNAMIC, invokeDynamicInsnNode.getOpcode()); assertEquals(AbstractInsnNode.INVOKE_DYNAMIC_INSN, invokeDynamicInsnNode.getType()); assertEquals("name", invokeDynamicInsnNode.name); assertEquals("()V", invokeDynamicInsnNode.desc); assertEquals(handle, invokeDynamicInsnNode.bsm); assertEquals(bootstrapMethodArguments, invokeDynamicInsnNode.bsmArgs); } |
### Question:
MultiANewArrayInsnNode extends AbstractInsnNode { @Override public int getType() { return MULTIANEWARRAY_INSN; } MultiANewArrayInsnNode(final String descriptor, final int numDimensions); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String desc; public int dims; }### Answer:
@Test public void testConstructor() { MultiANewArrayInsnNode multiANewArrayInsnNode = new MultiANewArrayInsnNode("[[I", 2); assertEquals(AbstractInsnNode.MULTIANEWARRAY_INSN, multiANewArrayInsnNode.getType()); assertEquals("[[I", multiANewArrayInsnNode.desc); assertEquals(2, multiANewArrayInsnNode.dims); } |
### Question:
TableSwitchInsnNode extends AbstractInsnNode { @Override public int getType() { return TABLESWITCH_INSN; } TableSwitchInsnNode(
final int min, final int max, final LabelNode dflt, final LabelNode... labels); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int min; public int max; public LabelNode dflt; public List<LabelNode> labels; }### Answer:
@Test public void testConstructor() { LabelNode dflt = new LabelNode(); LabelNode[] labels = new LabelNode[] {new LabelNode()}; TableSwitchInsnNode tableSwitchInsnNode = new TableSwitchInsnNode(0, 1, dflt, labels); assertEquals(AbstractInsnNode.TABLESWITCH_INSN, tableSwitchInsnNode.getType()); assertEquals(0, tableSwitchInsnNode.min); assertEquals(1, tableSwitchInsnNode.max); assertEquals(dflt, tableSwitchInsnNode.dflt); assertEquals(Arrays.asList(labels), tableSwitchInsnNode.labels); } |
### Question:
SourceValue implements Value { @Override public int getSize() { return size; } SourceValue(final int size); SourceValue(final int size, final AbstractInsnNode insnNode); SourceValue(final int size, final Set<AbstractInsnNode> insnSet); @Override int getSize(); @Override boolean equals(final Object value); @Override int hashCode(); final int size; final Set<AbstractInsnNode> insns; }### Answer:
@Test public void testGetSize() { assertEquals(2, new SourceValue(2).getSize()); } |
### Question:
FieldInsnNode extends AbstractInsnNode { @Override public int getType() { return FIELD_INSN; } FieldInsnNode(
final int opcode, final String owner, final String name, final String descriptor); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String owner; public String name; public String desc; }### Answer:
@Test public void testConstructor() { FieldInsnNode fieldInsnNode = new FieldInsnNode(Opcodes.GETSTATIC, "owner", "name", "I"); assertEquals(AbstractInsnNode.FIELD_INSN, fieldInsnNode.getType()); assertEquals(Opcodes.GETSTATIC, fieldInsnNode.getOpcode()); assertEquals("owner", fieldInsnNode.owner); assertEquals("name", fieldInsnNode.name); assertEquals("I", fieldInsnNode.desc); } |
### Question:
FieldInsnNode extends AbstractInsnNode { public void setOpcode(final int opcode) { this.opcode = opcode; } FieldInsnNode(
final int opcode, final String owner, final String name, final String descriptor); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String owner; public String name; public String desc; }### Answer:
@Test public void testSetOpcode() { FieldInsnNode fieldInsnNode = new FieldInsnNode(Opcodes.GETSTATIC, "owner", "name", "I"); fieldInsnNode.setOpcode(Opcodes.PUTSTATIC); assertEquals(Opcodes.PUTSTATIC, fieldInsnNode.getOpcode()); } |
### Question:
FrameNode extends AbstractInsnNode { @Override public int getType() { return FRAME; } private FrameNode(); FrameNode(
final int type,
final int numLocal,
final Object[] local,
final int numStack,
final Object[] stack); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public int type; public List<Object> local; public List<Object> stack; }### Answer:
@Test public void testConstructor() { Object[] locals = new Object[] {"l"}; Object[] stack = new Object[] {"s", "t"}; FrameNode frameNode = new FrameNode(Opcodes.F_FULL, 1, locals, 2, stack); assertEquals(AbstractInsnNode.FRAME, frameNode.getType()); assertEquals(Opcodes.F_FULL, frameNode.type); assertEquals(Arrays.asList(locals), frameNode.local); assertEquals(Arrays.asList(stack), frameNode.stack); } |
### Question:
MethodInsnNode extends AbstractInsnNode { @Override public int getType() { return METHOD_INSN; } MethodInsnNode(
final int opcode, final String owner, final String name, final String descriptor); MethodInsnNode(
final int opcode,
final String owner,
final String name,
final String descriptor,
final boolean isInterface); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String owner; public String name; public String desc; public boolean itf; }### Answer:
@Test @SuppressWarnings("deprecation") public void testDeprecatedConstructor() { MethodInsnNode methodInsnNode1 = new MethodInsnNode(Opcodes.INVOKESTATIC, "owner", "name", "()I"); MethodInsnNode methodInsnNode2 = new MethodInsnNode(Opcodes.INVOKEINTERFACE, "owner", "name", "()I"); assertEquals(AbstractInsnNode.METHOD_INSN, methodInsnNode1.getType()); assertEquals(AbstractInsnNode.METHOD_INSN, methodInsnNode2.getType()); assertEquals(Opcodes.INVOKESTATIC, methodInsnNode1.getOpcode()); assertEquals(Opcodes.INVOKEINTERFACE, methodInsnNode2.getOpcode()); assertFalse(methodInsnNode1.itf); assertTrue(methodInsnNode2.itf); }
@Test public void testConstrutor() { MethodInsnNode methodInsnNode = new MethodInsnNode(Opcodes.INVOKESTATIC, "owner", "name", "()I", false); assertEquals(AbstractInsnNode.METHOD_INSN, methodInsnNode.getType()); assertEquals(Opcodes.INVOKESTATIC, methodInsnNode.getOpcode()); assertEquals("owner", methodInsnNode.owner); assertEquals("name", methodInsnNode.name); assertEquals("()I", methodInsnNode.desc); assertFalse(methodInsnNode.itf); } |
### Question:
MethodInsnNode extends AbstractInsnNode { public void setOpcode(final int opcode) { this.opcode = opcode; } MethodInsnNode(
final int opcode, final String owner, final String name, final String descriptor); MethodInsnNode(
final int opcode,
final String owner,
final String name,
final String descriptor,
final boolean isInterface); void setOpcode(final int opcode); @Override int getType(); @Override void accept(final MethodVisitor methodVisitor); @Override AbstractInsnNode clone(final Map<LabelNode, LabelNode> clonedLabels); public String owner; public String name; public String desc; public boolean itf; }### Answer:
@Test public void testSetOpcode() { MethodInsnNode methodInsnNode = new MethodInsnNode(Opcodes.INVOKESTATIC, "owner", "name", "()I", false); methodInsnNode.setOpcode(Opcodes.INVOKESPECIAL); assertEquals(Opcodes.INVOKESPECIAL, methodInsnNode.getOpcode()); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.