method2testcases
stringlengths 118
6.63k
|
---|
### Question:
ChatRepository { public LiveData<PagedList<ChatMessage>> getMessagesByGroupId(int groupId) { return new LivePagedListBuilder<>(chatDao.getMessagesByGroupId(groupId), 30).build(); } ChatRepository(ChatDao chatDao, RequestEncoder encoder,
Handler backgroundHandler); void addMessage(ChatMessage message); LiveData<PagedList<ChatMessage>> getMessagesByGroupId(int groupId); void requestSendMessage(int groupId, String message); void deleteAllMessages(); }### Answer:
@Test public void getMessagesTest() { when(mockChatDao.getMessagesByGroupId(mockGroupId)) .thenReturn(() -> { return null; }); testChatRepository.getMessagesByGroupId(mockGroupId); verify(mockChatDao).getMessagesByGroupId(mockGroupId); } |
### Question:
User { public int getUserId() { return userId; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void getUserId() throws Exception { assertEquals(ids[0], user1.getUserId()); } |
### Question:
User { public void setUserId(int userId) { this.userId = userId; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void setUserId() throws Exception { user2.setUserId(12121); assertEquals(12121, user2.getUserId()); } |
### Question:
User { public String getUsername() { return username; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void getUsername() throws Exception { assertEquals(names[0], user1.getUsername()); } |
### Question:
User { public void setUsername(String username) { this.username = username; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void setUsername() throws Exception { user2.setUsername("Wurst"); assertEquals("Wurst", user2.getUsername()); } |
### Question:
User { public boolean isFriend() { return isFriend; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void isFriend() throws Exception { assertFalse(user1.isFriend()); } |
### Question:
User { public void setFriend(boolean friend) { isFriend = friend; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void setFriend() throws Exception { user2.setFriend(true); assertTrue(user2.isFriend()); } |
### Question:
User { public boolean isBlocked() { return isBlocked; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void isBlocked() throws Exception { assertFalse(user1.isBlocked()); } |
### Question:
User { public void setBlocked(boolean blocked) { isBlocked = blocked; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void setBlocked() throws Exception { user2.setBlocked(true); assertTrue(user2.isBlocked()); } |
### Question:
User { public boolean isRequesting() { return isRequesting; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void isRequesting() throws Exception { assertFalse(user1.isRequesting()); } |
### Question:
PositionChangeUpdate extends Update { @Override public void applyUpdate(RepositorySet repositorySet) { User user = repositorySet.userRepository.getUser(creator); user.setLocation(toLocation(latitude, longitude, timeMeasured)); repositorySet.userRepository.updateUser(user); } PositionChangeUpdate(@JsonProperty("time-created") Date timeCreated,
@JsonProperty("creator") int creator,
@JsonProperty("latitude") double latitude,
@JsonProperty("longitude") double longitude,
@JsonProperty("time-measured")
long timeMeasured); @Override void applyUpdate(RepositorySet repositorySet); }### Answer:
@Test public void applyUpdate() throws Exception { PositionChangeUpdate update = new PositionChangeUpdate(date, creator1, lat, lon, date.getTime()); update.applyUpdate(mockRepos); verify(mockUserRepository).getUser(creator1); verify(mockUser).setLocation(any(Location.class)); verify(mockUserRepository).updateUser(mockUser); } |
### Question:
User { public void setRequesting(boolean requesting) { this.isRequesting = requesting; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void setRequesting() throws Exception { user2.setRequesting(true); assertTrue(user2.isRequesting()); } |
### Question:
User { public boolean isRequestPending() { return requestPending; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void isRequestPending() throws Exception { assertFalse(user1.isRequestPending()); } |
### Question:
User { public void setRequestPending(boolean requestPending) { this.requestPending = requestPending; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void setRequestPending() throws Exception { user2.setRequestPending(true); assertTrue(user2.isRequestPending()); } |
### Question:
User { public Location getLocation() { return location; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void getLocation() throws Exception { assertEquals(mockLocation, user1.getLocation()); } |
### Question:
User { public void setLocation(Location location) { this.location = location; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void setLocation() throws Exception { Location location = new Location(LocationManager.PASSIVE_PROVIDER); user2.setLocation(location); assertEquals(location, user2.getLocation()); } |
### Question:
User { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; if (userId != user.userId) return false; if (isFriend != user.isFriend) return false; if (isBlocked != user.isBlocked) return false; if (isRequesting != user.isRequesting) return false; if (requestPending != user.requestPending) return false; if (username != null ? !username.equals(user.username) : user.username != null) return false; return location != null ? location.equals(user.location) : user.location == null; } User(int userId,
String username,
boolean isFriend,
boolean isBlocked,
boolean isRequesting,
boolean requestPending,
Location location); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); boolean isFriend(); void setFriend(boolean friend); boolean isBlocked(); void setBlocked(boolean blocked); boolean isRequesting(); void setRequesting(boolean requesting); boolean isRequestPending(); void setRequestPending(boolean requestPending); Location getLocation(); void setLocation(Location location); @Override boolean equals(Object o); @Override int hashCode(); static User getPlaceholderAndScheduleQuery(int userID,
UserDao userDao); static User getPlaceholderAndScheduleQuery(int userID,
UserRepository
userRepository); static User getPlaceholderAndScheduleQuery(
int userID, UserRepository userRepository,
@Nullable UserManipulationFunction additionalManipulation); }### Answer:
@Test public void equals() throws Exception { assertTrue(user1.equals(user1)); assertTrue(user1.equals(user3)); } |
### Question:
GroupMembership { public int getUserId() { return userId; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getUserId() throws Exception { assertEquals(ids[0], groupMembership1.getUserId()); } |
### Question:
GroupMembership { public void setUserId(int userId) { this.userId = userId; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setUserId() throws Exception { groupMembership2.setUserId(65656); assertEquals(65656, groupMembership2.getUserId()); } |
### Question:
GroupMembership { public int getGroupId() { return groupId; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getGroupId() throws Exception { assertEquals(ids[1], groupMembership1.getGroupId()); } |
### Question:
GroupMembership { public void setGroupId(int groupId) { this.groupId = groupId; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setGroupId() throws Exception { groupMembership2.setGroupId(78787); assertEquals(78787, groupMembership2.getGroupId()); } |
### Question:
ContactRequestAnswerUpdate extends Update { @Override public void applyUpdate(RepositorySet repositorySet) { repositorySet.userRepository.setIsPending(creator, false); repositorySet.userRepository.setIsFriend(creator, answer); } ContactRequestAnswerUpdate(@JsonProperty("time-created") Date timeCreated,
@JsonProperty("creator") int creator,
@JsonProperty("answer") Boolean answer); @Override void applyUpdate(RepositorySet repositorySet); }### Answer:
@Test public void applyUpdate() throws Exception { ContactRequestAnswerUpdate update = new ContactRequestAnswerUpdate(date, creator1, true); update.applyUpdate(mockRepos); verify(mockUserRepository).setIsPending(creator1, false); verify(mockUserRepository).setIsFriend(creator1, true); } |
### Question:
GroupMembership { public Date getSharingUntil() { return sharingUntil; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getSharingUntil() throws Exception { assertEquals(date1, groupMembership1.getSharingUntil()); } |
### Question:
GroupMembership { public void setSharingUntil(Date sharingUntil) { this.sharingUntil = sharingUntil; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setSharingUntil() throws Exception { groupMembership2.setSharingUntil(date2); assertEquals(date2, groupMembership2.getSharingUntil()); } |
### Question:
GroupMembership { public boolean isSharing() { return sharing; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void isSharing() throws Exception { assertTrue(!groupMembership1.isSharing()); } |
### Question:
GroupMembership { public void setSharing(boolean sharing) { this.sharing = sharing; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setSharing() throws Exception { groupMembership2.setSharing(true); assertTrue(groupMembership2.isSharing()); } |
### Question:
GroupMembership { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GroupMembership that = (GroupMembership) o; if (userId != that.userId) return false; return groupId == that.groupId; } GroupMembership(int userId, int groupId); int getUserId(); void setUserId(int userId); int getGroupId(); void setGroupId(int groupId); Date getSharingUntil(); void setSharingUntil(Date sharingUntil); boolean isSharing(); void setSharing(boolean sharing); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void equals() throws Exception { assertTrue(groupMembership1.equals(groupMembership1)); assertTrue(groupMembership1.equals(groupMembership3)); } |
### Question:
UserGroup { public int getGroupId() { return groupId; } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getGroupId() throws Exception { assertEquals(ids[0], userGroup1.getGroupId()); } |
### Question:
UserGroup { public void setGroupId(int groupId) { this.groupId = groupId; } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setGroupId() throws Exception { userGroup2.setGroupId(ids[3]); assertEquals(ids[3], userGroup2.getGroupId()); } |
### Question:
UserGroup { public String getName() { return name; } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getName() throws Exception { assertEquals(groupNames[0], userGroup1.getName()); } |
### Question:
UserGroup { public void setName(String name) { this.name = name; } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setName() throws Exception { userGroup2.setName(groupNames[2]); assertEquals(groupNames[2], userGroup2.getName()); } |
### Question:
UserGroup { public boolean isSharingLocation() { return isSharingLocation; } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void isSharingLocation() throws Exception { assertFalse(userGroup1.isSharingLocation()); } |
### Question:
EventDeletionUpdate extends Update { @Override public void applyUpdate(RepositorySet repositorySet) { repositorySet.eventRepository.deleteEvent(eventID); } EventDeletionUpdate(@JsonProperty("time-created") Date timeCreated,
@JsonProperty("creator") int creator,
@JsonProperty("group-id") int groupID,
@JsonProperty("id") int eventID); @Override void applyUpdate(RepositorySet repositorySet); }### Answer:
@Test public void applyUpdate() throws Exception { EventDeletionUpdate update = new EventDeletionUpdate(date, creator1, group1, event1); update.applyUpdate(mockRepos); verify(mockEventRepository).deleteEvent(event1); } |
### Question:
UserGroup { public void setSharingLocation(boolean sharingLocation) { isSharingLocation = sharingLocation; } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setSharingLocation() throws Exception { userGroup2.setSharingLocation(true); assertTrue(userGroup2.isSharingLocation()); } |
### Question:
UserGroup { @Override public String toString() { return name; } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void testToString() throws Exception { assertEquals(groupNames[0], userGroup1.toString()); } |
### Question:
UserGroup { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserGroup group = (UserGroup) o; if (groupId != group.groupId) return false; return name.equals(group.name); } UserGroup(int groupId, String name); int getGroupId(); void setGroupId(int groupId); String getName(); void setName(String name); boolean isSharingLocation(); void setSharingLocation(boolean sharingLocation); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void equals() throws Exception { assertTrue(userGroup1.equals(userGroup1)); assertTrue(userGroup1.equals(userGroup3)); } |
### Question:
DateConverter { @TypeConverter public static Date toDate(Long timestamp) { return timestamp == null ? null : new Date(timestamp); } @TypeConverter static Date toDate(Long timestamp); @TypeConverter static Long toTimestamp(Date date); }### Answer:
@Test public void testToDate() { assertEquals(dateZero, DateConverter.toDate(timestampZero)); assertEquals(datePresentation, DateConverter.toDate(timestampPresentation)); assertEquals(dateZero, DateConverter.toDate(timestampNull)); } |
### Question:
DateConverter { @TypeConverter public static Long toTimestamp(Date date) { return date == null ? null : date.getTime(); } @TypeConverter static Date toDate(Long timestamp); @TypeConverter static Long toTimestamp(Date date); }### Answer:
@Test public void testToTimestamp() { long testTimestamp1 = DateConverter.toTimestamp(dateZero); assertEquals(timestampZero, testTimestamp1); long testTimestamp2 = DateConverter.toTimestamp(datePresentation); assertEquals(timestampPresentation, testTimestamp2); boolean exception = false; try { long testTimestamp3 = DateConverter.toTimestamp(dateNull); } catch (NullPointerException e) { exception = true; } assertTrue(exception); } |
### Question:
PositionConverter { @TypeConverter public static Location toLocation(String location) { if (location == null) return null; String[] split = location.split("#"); double lat = Double.parseDouble(split[0]); double lon = Double.parseDouble(split[1]); long time = Long.parseLong(split[2]); Location l = new Location(LocationManager.GPS_PROVIDER); l.setLatitude(lat); l.setLongitude(lon); l.setTime(time); return l; } @TypeConverter static Location toLocation(String location); @TypeConverter static String toDoubles(Location location); }### Answer:
@Test public void toLocation() throws Exception { PositionConverter.toLocation(positionString); verify(mockLocation).setLatitude(55.55); verify(mockLocation).setLongitude(90.0); verify(mockLocation).setTime((long)1521158400); } |
### Question:
PositionConverter { @TypeConverter public static String toDoubles(Location location) { if (location == null) return null; return location.getLatitude() + "#" + location.getLongitude() + "#" + location.getTime(); } @TypeConverter static Location toLocation(String location); @TypeConverter static String toDoubles(Location location); }### Answer:
@Test public void toDoubles() throws Exception { when(mockLocation.getLatitude()).thenReturn(55.55); when(mockLocation.getLongitude()).thenReturn(90.00); when(mockLocation.getTime()).thenReturn((long)1521158400); assertEquals(positionString ,PositionConverter.toDoubles(mockLocation)); } |
### Question:
IntegerSetConverter { @TypeConverter public static Set<Integer> toSet(String string) { if (string == null) return null; if (string.length() == 0) return new HashSet<>(); Set<Integer> set = new HashSet<>(); String[] ints = string.split("#"); for (String s : ints) { set.add(Integer.parseInt(s)); } return set; } @TypeConverter static Set<Integer> toSet(String string); @TypeConverter static String toString(Set<Integer> set); }### Answer:
@Test public void testToSet() { assertEquals(emptySet, IntegerSetConverter.toSet(emptyString)); assertEquals(null, IntegerSetConverter.toSet(nullString)); assertEquals(oneElementSet, IntegerSetConverter.toSet(oneElementString)); assertEquals(largeSet, IntegerSetConverter.toSet(largeString)); } |
### Question:
IntegerSetConverter { @TypeConverter public static String toString(Set<Integer> set) { if (set == null) return null; String string = ""; for (Integer i : set) { string += i; string += "#"; } return string; } @TypeConverter static Set<Integer> toSet(String string); @TypeConverter static String toString(Set<Integer> set); }### Answer:
@Test public void testToString() { assertEquals(nullString, IntegerSetConverter.toString(nullSet)); assertEquals(emptyString, IntegerSetConverter.toString(emptySet)); assertEquals(oneElementString + "#", IntegerSetConverter.toString(oneElementSet)); assertEquals(largeStringSorted, IntegerSetConverter.toString(largeSet)); } |
### Question:
ChatMessage { public int getMessageId() { return messageId; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getMessageId() throws Exception { assertEquals(0, message1.getMessageId()); } |
### Question:
AccountChangeUpdate extends Update { @Override public void applyUpdate(RepositorySet repositorySet) { User user = repositorySet.userRepository.getUser(account.id); if (user != null) { user.setUsername(account.username); repositorySet.userRepository.updateUser(user); } else { user = new User(account.id, account.username, false, false, false, false, new Location("update")); repositorySet.userRepository.addUser(user); } } AccountChangeUpdate(@JsonProperty("time-created") Date timeCreated,
@JsonProperty("creator") int creator,
@JsonProperty("account")
CompleteAccount account); @Override void applyUpdate(RepositorySet repositorySet); }### Answer:
@Test public void applyUpdate() throws Exception { AccountChangeUpdate update1 = new AccountChangeUpdate(date, creator1, account1); update1.applyUpdate(mockRepos); verify(mockUserRepository).addUser(mockUser); AccountChangeUpdate update2 = new AccountChangeUpdate(date, creator1, account2); update2.applyUpdate(mockRepos); verify(mockUser).setUsername(account2.username); verify(mockUserRepository).updateUser(mockUser); } |
### Question:
ChatMessage { public void setMessageId(int messageId) { this.messageId = messageId; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setMessageId() throws Exception { message2.setMessageId(1); assertEquals(1, message2.getMessageId()); } |
### Question:
ChatMessage { public int getGroupId() { return groupId; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getGroupId() throws Exception { assertEquals(69, message1.getGroupId()); } |
### Question:
ChatMessage { public void setGroupId(int groupId) { this.groupId = groupId; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setGroupId() throws Exception { message2.setGroupId(9997); assertEquals(9997, message2.getGroupId()); } |
### Question:
ChatMessage { public String getContent() { return content; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getContent() throws Exception { assertEquals("Hallo", message1.getContent()); } |
### Question:
ChatMessage { public void setContent(String content) { this.content = content; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setContent() throws Exception { message2.setContent("NEIN"); assertEquals("NEIN", message2.getContent()); } |
### Question:
ChatMessage { public int getUserId() { return userId; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getUserId() throws Exception { assertEquals(88, message1.getUserId()); } |
### Question:
ChatMessage { public void setUserId(int userId) { this.userId = userId; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setUserId() throws Exception { message2.setUserId(99143); assertEquals(99143, message2.getUserId()); } |
### Question:
ChatMessage { public String getUsername() { return username; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getUsername() throws Exception { assertEquals("Hans", message1.getUsername()); } |
### Question:
ChatMessage { public void setUsername(String username) { this.username = username; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setUsername() throws Exception { message2.setUsername("Wurst"); assertEquals("Wurst", message2.getUsername()); } |
### Question:
ChatMessage { public Date getTimeSent() { return timeSent; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getTimeSent() throws Exception { assertEquals(date1, message1.getTimeSent()); } |
### Question:
CancelContactRequestUpdate extends Update { @Override public void applyUpdate(RepositorySet repositorySet) { repositorySet.userRepository.setIsRequesting(creator, false); } CancelContactRequestUpdate(@JsonProperty("time-created") Date timeCreated,
@JsonProperty("creator") int creator); @Override void applyUpdate(RepositorySet repositorySet); }### Answer:
@Test public void applyUpdate() throws Exception { CancelContactRequestUpdate update = new CancelContactRequestUpdate(date, creator1); update.applyUpdate(mockRepos); verify(mockUserRepository).setIsRequesting(creator1, false); } |
### Question:
ChatMessage { public void setTimeSent(Date timeSent) { this.timeSent = timeSent; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setTimeSent() throws Exception { message2.setTimeSent(date2); assertEquals(date2, message2.getTimeSent()); } |
### Question:
ChatMessage { public boolean equalContent(ChatMessage o) { if (groupId != o.groupId) return false; if (userId != o.userId) return false; if (content != null ? !content.equals(o.content) : o.content != null) { return false; } return timeSent != null ? timeSent.equals(o.timeSent) : o.timeSent == null; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void equalContent() throws Exception { assertTrue("same message", message1.equalContent(message1)); assertTrue("different messages", message1.equalContent(message3)); } |
### Question:
ChatMessage { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ChatMessage that = (ChatMessage) o; if (messageId != that.messageId) return false; if (groupId != that.groupId) return false; if (userId != that.userId) return false; if (content != null ? !content .equals(that.content) : that.content != null) { return false; } return timeSent != null ? timeSent .equals(that.timeSent) : that.timeSent == null; } ChatMessage(int groupId,
String content,
int userId,
String username,
Date timeSent); int getMessageId(); void setMessageId(int messageId); int getGroupId(); void setGroupId(int groupId); String getContent(); void setContent(String content); int getUserId(); void setUserId(int userId); String getUsername(); void setUsername(String username); Date getTimeSent(); void setTimeSent(Date timeSent); boolean equalContent(ChatMessage o); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void equals() throws Exception { assertTrue("same message", message1.equals(message1)); assertTrue("different messages", message1.equals(message3)); } |
### Question:
Event extends Occasion { public int getId() { return id; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getId() throws Exception { assertEquals(ids[0], event1.getId()); } |
### Question:
Event extends Occasion { public void setId(int id) { this.id = id; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setId() throws Exception { event2.setId(1234); assertEquals(1234, event2.getId()); } |
### Question:
Event extends Occasion { public Date getEnd() { return end; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getEnd() throws Exception { assertEquals(date2, event1.getEnd()); } |
### Question:
Event extends Occasion { public void setEnd(Date end) { this.end = end; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setEnd() throws Exception { event2.setEnd(date2); assertEquals(date2, event2.getEnd()); } |
### Question:
Event extends Occasion { public Date getStart() { return start; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getStart() throws Exception { assertEquals(date1, event1.getStart()); } |
### Question:
Event extends Occasion { public void setStart(Date start) { this.start = start; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setStart() throws Exception { event2.setStart(date2); assertEquals(date2, event2.getStart()); } |
### Question:
Event extends Occasion { public int getCreator() { return creator; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getCreator() throws Exception { assertEquals(ids[1], event1.getCreator()); } |
### Question:
GroupMembershipChangeUpdate extends Update { @Override public void applyUpdate(RepositorySet repositorySet) { GroupMembership membership = new GroupMembership (membershipDescription.accountID, membershipDescription .groupID); membership.setSharingUntil(membershipDescription.sharingUntil); repositorySet.userGroupRepository.updateMembership(membership); } GroupMembershipChangeUpdate(@JsonProperty("time-created")
Date timeCreated,
@JsonProperty("creator") int creator,
@JsonProperty("membership")
CompleteMembership
membershipDescription); @Override void applyUpdate(RepositorySet repositorySet); }### Answer:
@Test public void applyUpdate() throws Exception { GroupMembershipChangeUpdate update = new GroupMembershipChangeUpdate(date, creator1, membership); update.applyUpdate(mockRepos); verify(mockGroupMembership).setSharingUntil(date); verify(mockUserGroupRepository).updateMembership(mockGroupMembership); } |
### Question:
Event extends Occasion { public void setCreator(int creator) { this.creator = creator; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setCreator() throws Exception { event2.setCreator(54545); assertEquals(54545, event2.getCreator()); } |
### Question:
Event extends Occasion { public String getStartString() { return start.toString().substring(0, 16); } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getStartString() throws Exception { assertEquals(date1.toString().substring(0, 16), event1.getStartString()); } |
### Question:
Event extends Occasion { public Location getLocation() { return location; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getLocation() throws Exception { assertEquals(mockLocation, event1.getLocation()); } |
### Question:
Event extends Occasion { public void setLocation(Location location) { this.location = location; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setLocation() throws Exception { Location location = new Location(LocationManager.PASSIVE_PROVIDER); event2.setLocation(location); assertEquals(location, event2.getLocation()); } |
### Question:
Event extends Occasion { public int getGroupId() { return groupId; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void getGroupId() throws Exception { assertEquals(ids[2], event1.getGroupId()); } |
### Question:
Event extends Occasion { public void setGroupId(int groupId) { this.groupId = groupId; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void setGroupId() throws Exception { event2.setGroupId(98989); assertEquals(98989, event2.getGroupId()); } |
### Question:
Event extends Occasion { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Event event = (Event) o; if (id != event.id) return false; if (creator != event.creator) return false; if (end != null ? !end.equals(event.end) : event.end !=null) { return false; } if (start != null ? !start.equals(event.start) : event.start != null) { return false; } return location != null ? location .equals(event.location) : event.location == null; } Event(int id,
String name,
Date start,
Date end,
Location location,
int creator,
int groupId); int getId(); void setId(int id); Date getEnd(); void setEnd(Date end); Date getStart(); void setStart(Date start); int getCreator(); void setCreator(int creator); String getStartString(); Location getLocation(); void setLocation(Location location); int getGroupId(); void setGroupId(int groupId); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test public void equals() throws Exception { assertTrue(event1.equals(event1)); assertTrue(event1.equals(event3)); } |
### Question:
PollCompleteSerializer extends JsonSerializer<Poll> { @Override public void serialize(Poll poll, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); gen.writeStringField("type", "poll"); gen.writeNumberField("id", poll.getID()); gen.writeNumberField("creator", poll.getCreator().getID()); gen.writeStringField("question", poll.getQuestion()); gen.writeBooleanField("multi-choice", poll.isMultiChoice()); gen.writeNumberField("time-close", poll.getTimeVoteClose().getTime()); SerializerUtil.writeIDArray(poll.getPollOptions().keySet(), "options", gen); gen.writeEndObject(); } @Override void serialize(Poll poll, JsonGenerator gen, SerializerProvider
serializers); }### Answer:
@Test public void serialize() throws IOException { StringWriter outputWriter = new StringWriter(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(outputWriter); jsonGenerator.useDefaultPrettyPrinter(); Poll poll = mock(Poll.class); when(poll.getID()).thenReturn(4); when(poll.getQuestion()).thenReturn("the-question"); when(poll.isMultiChoice()).thenReturn(true); Calendar timeVoteClose = new GregorianCalendar(); timeVoteClose.set(2018,Calendar.JANUARY,1,13,33,37); when(poll.getTimeVoteClose()) .thenReturn(timeVoteClose.getTime()); Account creator = mock(Account.class); when(poll.getCreator()).thenReturn(creator); when(creator.getID()).thenReturn(1337); Map<Integer, PollOption> pollOptions = new HashMap<>(); pollOptions.put(0, null); pollOptions.put(1, null); pollOptions.put(2, null); doReturn(pollOptions).when(poll).getPollOptions(); PollCompleteSerializer pollCompleteSerializer = new PollCompleteSerializer(); pollCompleteSerializer.serialize(poll, jsonGenerator,null); jsonGenerator.close(); System.out.println(outputWriter.toString()); } |
### Question:
PollOptionCompleteSerializer extends JsonSerializer<PollOption> { @Override public void serialize(PollOption pollOption, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); Position position = pollOption.getPosition(); gen.writeStringField("type", "polloption"); gen.writeNumberField("id", pollOption.getID()); gen.writeNumberField("latitude", position.getLatitude()); gen.writeNumberField("longitude", position.getLatitude()); gen.writeNumberField("time-start", pollOption.getTimeStart().getTime()); gen.writeNumberField("time-end", pollOption.getTimeEnd().getTime()); gen.writeArrayFieldStart("supporters"); for (int voterID : pollOption.getVoters().keySet()) gen.writeNumber(voterID); gen.writeEndArray(); gen.writeEndObject(); } @Override void serialize(PollOption pollOption, JsonGenerator gen,
SerializerProvider serializers); }### Answer:
@Test public void serialize() throws IOException { StringWriter outputWriter = new StringWriter(); JsonGenerator jsonGenerator = new JsonFactory().createGenerator(outputWriter); jsonGenerator.useDefaultPrettyPrinter(); PollOption pollOption = mock(PollOption.class); when(pollOption.getID()).thenReturn(77); when(pollOption.getPosition()) .thenReturn(new Position(13.37, 42.00)); Calendar timeStart = new GregorianCalendar(); Calendar timeEnd = new GregorianCalendar(); timeStart.set(2018,Calendar.FEBRUARY,1,0,0,0); timeEnd.set(2018,Calendar.MARCH,4,5,6,7); when(pollOption.getTimeStart()) .thenReturn(timeStart.getTime()); when(pollOption.getTimeEnd()) .thenReturn(timeEnd.getTime()); Map<Integer, Account> voters = new HashMap<>(); doReturn(voters).when(pollOption).getVoters(); Account voter = mock(Account.class); when(voter.getID()).thenReturn(42); voters.put(42, voter); PollOptionCompleteSerializer pollOptionCompleteSerializer = new PollOptionCompleteSerializer(); pollOptionCompleteSerializer.serialize(pollOption, jsonGenerator, null); jsonGenerator.close(); System.out.println(outputWriter.toString()); } |
### Question:
ChatUpdate extends Update { @Override public void applyUpdate(RepositorySet repositorySet) { User sender = repositorySet.userRepository.getUser(creator); if (sender == null) sender = User.getPlaceholderAndScheduleQuery(creator, repositorySet.userRepository); ChatMessage chatMessage = new ChatMessage(groupId, message, sender.getUserId(), sender.getUsername(), timeCreated); repositorySet.chatRepository.addMessage(chatMessage); } ChatUpdate(@JsonProperty("time-created") Date timeCreated,
@JsonProperty("creator") int creator,
@JsonProperty("group-id") int groupId,
@JsonProperty("message") String message); @Override void applyUpdate(RepositorySet repositorySet); }### Answer:
@Test public void applyUpdate() throws Exception { ChatUpdate update = new ChatUpdate(date, creator1, group1, message1); update.applyUpdate(mockRepos); verify(mockUserRepository).getUser(creator1); verify(mockUser).getUserId(); verify(mockChatRepository).addMessage(mockMessage); } |
### Question:
FeatureServiceImpl { public Feature readFeature(Reader jsonReader) throws IOException { JsonObject json = Json.createReader(jsonReader).readObject(); String id = json.getString("id"); FeatureBuilder builder = builderFactory.newFeatureBuilder(ID.fromMavenID(id)); builder.setName(json.getString("title", null)); builder.setDescription(json.getString("description", null)); builder.setVendor(json.getString("vendor", null)); builder.setLicense(json.getString("license", null)); builder.setLocation(json.getString("location", null)); builder.setComplete(json.getBoolean("complete", false)); builder.setFinal(json.getBoolean("final", false)); builder.addBundles(getBundles(json)); builder.addConfigurations(getConfigurations(json)); builder.addExtensions(getExtensions(json)); return builder.build(); } BuilderFactory getBuilderFactory(); Feature readFeature(Reader jsonReader); void writeFeature(Feature feature, Writer jsonWriter); Feature mergeFeatures(ID targetID, Feature f1, Feature f2, MergeContext ctx); }### Answer:
@Test public void testReadFeature() throws IOException { BuilderFactory bf = Features.getBuilderFactory(); URL res = getClass().getResource("/features/test-feature.json"); try (Reader r = new InputStreamReader(res.openStream())) { Feature f = Features.readFeature(r); assertNull(f.getName()); assertEquals("The feature description", f.getDescription()); List<FeatureBundle> bundles = f.getBundles(); assertEquals(3, bundles.size()); FeatureBundle bundle = bf.newBundleBuilder(new ID("org.osgi", "osgi.promise", "7.0.1")) .addMetadata("hash", "4632463464363646436") .addMetadata("start-order", 1L) .build(); FeatureBundle ba = bundles.get(0); ba.equals(bundle); assertTrue(bundles.contains(bundle)); assertTrue(bundles.contains(bf.newBundleBuilder(new ID("org.slf4j", "slf4j-api", "1.7.29")).build())); assertTrue(bundles.contains(bf.newBundleBuilder(new ID("org.slf4j", "slf4j-simple", "1.7.29")).build())); } } |
### Question:
FeatureServiceImpl { public Feature mergeFeatures(ID targetID, Feature f1, Feature f2, MergeContext ctx) { FeatureBuilder fb = builderFactory.newFeatureBuilder(targetID); copyAttrs(f1, fb); copyAttrs(f2, fb); fb.addBundles(mergeBundles(f1, f2, ctx)); fb.addConfigurations(mergeConfigs(f1, f2, ctx)); fb.addExtensions(mergeExtensions(f1, f2, ctx)); return fb.build(); } BuilderFactory getBuilderFactory(); Feature readFeature(Reader jsonReader); void writeFeature(Feature feature, Writer jsonWriter); Feature mergeFeatures(ID targetID, Feature f1, Feature f2, MergeContext ctx); }### Answer:
@Test public void testMergeFeatures() throws IOException { BuilderFactory bf = Features.getBuilderFactory(); URL res1 = getClass().getResource("/features/test-feature.json"); Feature f1; try (Reader r = new InputStreamReader(res1.openStream())) { f1 = Features.readFeature(r); } URL res2 = getClass().getResource("/features/test-feature2.json"); Feature f2; try (Reader r = new InputStreamReader(res2.openStream())) { f2 = Features.readFeature(r); } MergeContext ctx = bf.newMergeContextBuilder() .bundleConflictHandler((cf1, b1, cf2, b2) -> Arrays.asList(b1, b2)) .configConflictHandler((cf1, c1, cf2, c2) -> new ConfigurationBuilderImpl(c1) .addValues(c2.getValues()).build()) .build(); ID tid = new ID("foo", "bar", "1.2.3"); Feature f3 = Features.mergeFeatures(tid, f1, f2, ctx); assertEquals(tid, f3.getID()); List<FeatureBundle> bundles = f3.getBundles(); assertEquals(5, bundles.size()); assertTrue(bundles.contains(bf.newBundleBuilder(new ID("org.slf4j", "slf4j-api", "1.7.29")).build())); assertTrue(bundles.contains(bf.newBundleBuilder(new ID("org.slf4j", "slf4j-api", "1.7.30")).build())); assertTrue(bundles.contains(bf.newBundleBuilder(new ID("org.slf4j", "slf4j-nop", "1.7.30")).build())); Map<String, FeatureConfiguration> configs = f3.getConfigurations(); assertEquals(2, configs.size()); FeatureConfiguration cfg1 = configs.get("my.factory.pid~name"); assertEquals("my.factory.pid~name", cfg1.getPid()); assertEquals("my.factory.pid", cfg1.getFactoryPid()); assertEquals(Collections.singletonMap("a.value", "yeah"), cfg1.getValues()); FeatureConfiguration cfg2 = configs.get("my.pid"); assertEquals("my.pid", cfg2.getPid()); assertNull(cfg2.getFactoryPid()); Map<String,Object> expected = new HashMap<>(); expected.put("foo", 5L); expected.put("bar", "toast"); expected.put("number:Integer", 7L); assertEquals(expected, cfg2.getValues()); } |
### Question:
FeatureServiceImpl { private FeatureExtension[] mergeExtensions(Feature f1, Feature f2, MergeContext ctx) { Map<String,FeatureExtension> extensions = new HashMap<>(f1.getExtensions()); Map<String,FeatureExtension> addExtensions = new HashMap<>(); for (Map.Entry<String,FeatureExtension> exEntry : f2.getExtensions().entrySet()) { String key = exEntry.getKey(); FeatureExtension newEx = exEntry.getValue(); FeatureExtension orgEx = extensions.get(key); if (orgEx != null) { FeatureExtension resEx = ctx.handleExtensionConflict(f1, orgEx, f2, newEx); if (!resEx.equals(orgEx)) { extensions.remove(key); addExtensions.put(key, resEx); } } else { addExtensions.put(key, newEx); } } extensions.putAll(addExtensions); return extensions.values().toArray(new FeatureExtension[] {}); } BuilderFactory getBuilderFactory(); Feature readFeature(Reader jsonReader); void writeFeature(Feature feature, Writer jsonWriter); Feature mergeFeatures(ID targetID, Feature f1, Feature f2, MergeContext ctx); }### Answer:
@Test public void testMergeExtensions() throws IOException { BuilderFactory bf = Features.getBuilderFactory(); URL res1 = getClass().getResource("/features/test-exfeat1.json"); Feature f1; try (Reader r = new InputStreamReader(res1.openStream())) { f1 = Features.readFeature(r); } URL res2 = getClass().getResource("/features/test-exfeat2.json"); Feature f2; try (Reader r = new InputStreamReader(res2.openStream())) { f2 = Features.readFeature(r); } MergeContext ctx = bf.newMergeContextBuilder() .extensionConflictHandler((cf1, e1, cf2, e2) -> new ExtensionBuilderImpl(e1.getName(), e1.getType(), e1.getKind()) .addText(e1.getText()) .addText(e2.getText()) .build()) .build(); ID tid = new ID("g", "a", "1.2.3"); Feature f3 = Features.mergeFeatures(tid, f1, f2, ctx); Map<String, FeatureExtension> extensions = f3.getExtensions(); assertEquals(3, extensions.size()); FeatureExtension txtEx = extensions.get("my-text-ex"); assertEquals("ABCDEF", txtEx.getText()); assertEquals(FeatureExtension.Kind.OPTIONAL, txtEx.getKind()); assertEquals(FeatureExtension.Type.TEXT, txtEx.getType()); FeatureExtension artEx = extensions.get("my-art-ex"); assertEquals(FeatureExtension.Kind.MANDATORY, artEx.getKind()); assertEquals(FeatureExtension.Type.ARTIFACTS, artEx.getType()); List<ID> artifacts = artEx.getArtifacts(); assertEquals(2, artifacts.size()); assertTrue(artifacts.contains(new ID("g", "a", "1"))); assertTrue(artifacts.contains(new ID("g", "a", "2"))); FeatureExtension jsonEx = extensions.get("my-json-ex"); assertEquals(FeatureExtension.Kind.TRANSIENT, jsonEx.getKind()); assertEquals(FeatureExtension.Type.JSON, jsonEx.getType()); assertEquals("{\"foo\":[1,2,3]}", jsonEx.getJSON()); } |
### Question:
MarkdownResourceProvider extends ResourceProvider<Object> { @Override public Resource getResource(ResolveContext<Object> ctx, String path, ResourceContext resourceContext, Resource parent) { Path filePath = Paths.get(fsPath, path, INDEX_FILE_NAME); File backingFile = filePath.toFile(); if ( !backingFile.canRead() ) { filePath = Paths.get(fsPath, path + MARKDOWN_EXTENSION); backingFile = filePath.toFile(); if ( !backingFile.canRead() ) return null; } return new MarkdownResource(ctx.getResourceResolver(), path, backingFile); } @Override Resource getResource(ResolveContext<Object> ctx, String path, ResourceContext resourceContext,
Resource parent); @Override Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent); }### Answer:
@Test public void loadSingleResourceFromRoot() { Resource resource = context.resourceResolver().getResource("/md-test"); assertThat("resource", resource, notNullValue()); assertThat("resource.getValueMap()", resource.getValueMap(), notNullValue()); assertThat("resource.getMetadata()", resource.getResourceMetadata(), notNullValue()); assertThat("resource.getMetadata().getPath()", resource.getResourceMetadata().getResolutionPath(), equalTo("/md-test2")); assertThat("valueMap[jcr:title]", resource.getValueMap().get("jcr:title", String.class), equalTo("Simple markdown file")); assertThat("valueMap[jcr:description]", resource.getValueMap().get("jcr:description", String.class), equalTo("<p>This is an example of a simple markdown file</p>\n")); assertThat("valueMap[sling:resourceType]", resource.getValueMap().get("sling:resourceType", String.class), equalTo("sling/markdown/file")); assertThat("valueMap[author]", resource.getValueMap().get("author", String.class), equalTo("John Doe")); assertThat("valueMap[keywords]", resource.getValueMap().get("keywords", String[].class), equalTo(new String[] {"news", "simple"})); ValueMap adapted = resource.adaptTo(ValueMap.class); assertThat("adapted ValueMap", adapted, notNullValue()); assertThat("adapted Map", resource.adaptTo(Map.class), notNullValue()); } |
### Question:
MarkdownResourceProvider extends ResourceProvider<Object> { @Override public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) { Path root = Paths.get(fsPath, parent.getPath()); try { return Files.list(root) .map( p -> asResource(p, Paths.get(parent.getPath()), ctx)) .filter( r -> r != null ) .collect(Collectors.toList()) .iterator(); } catch (IOException e) { throw new RuntimeException(e); } } @Override Resource getResource(ResolveContext<Object> ctx, String path, ResourceContext resourceContext,
Resource parent); @Override Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent); }### Answer:
@Test public void listChildren() { Resource resource = context.resourceResolver().getResource("/md-test/child-listing"); List<Resource> children = new ArrayList<>(); resource.getChildren().forEach( children::add ); assertThat("children", children, hasSize(3)); assertThat("children.paths", children.stream().map( r -> r.getPath()).collect(Collectors.toList()), hasItems("/md-test/child-listing/news", "/md-test/child-listing/spam", "/md-test/child-listing/comments")); Resource newsResource = children.stream() .filter( r -> r.getPath().equals("/md-test/child-listing/spam") ) .findFirst() .get(); assertThat("newsResource.valueMap[jcr:title]", newsResource.getValueMap().get("jcr:title", String.class), equalTo("Spam (correct)")); } |
### Question:
OakDescriptorSource implements CapabilitiesSource { @Override public Map<String, Object> getCapabilities() throws Exception { final SlingRepository localRepo = repository; if (localRepo == null) { return Collections.emptyMap(); } refreshCachedValues(); return cachedReadOnlyMap; } @Override Map<String, Object> getCapabilities(); @Override String getNamespace(); static final String NAMESPACE; }### Answer:
@Test public void testNull() throws Exception { registerOakDescriptorSource(); assertNotNull(source.getCapabilities()); assertNull(source.getCapabilities().get("foo")); }
@Test public void testDefaultJcrDescriptors_listed() throws Exception { registerOakDescriptorSource(Repository.REP_NAME_DESC, Repository.REP_VENDOR_DESC); assertNotNull(source.getCapabilities()); assertEquals("Apache Jackrabbit Oak", source.getCapabilities().get(Repository.REP_NAME_DESC)); assertEquals("The Apache Software Foundation", source.getCapabilities().get(Repository.REP_VENDOR_DESC)); }
@Test public void testDefaultJcrDescriptors_filtered() throws Exception { registerOakDescriptorSource(Repository.REP_NAME_DESC); assertNotNull(source.getCapabilities()); assertEquals("Apache Jackrabbit Oak", source.getCapabilities().get(Repository.REP_NAME_DESC)); assertNull(source.getCapabilities().get(Repository.REP_VENDOR_DESC)); } |
### Question:
ReflectionHelper { static <T> T instantiate(Class<T> type, Object... args) { try { if (args.length == 0) { return type.getDeclaredConstructor().newInstance(); } else { Class<?>[] classes = toClasses(args); return type.getDeclaredConstructor(classes).newInstance(args); } } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } return null; } private ReflectionHelper(); }### Answer:
@SuppressWarnings("ConstantConditions") @Test public void instantiate() { TestClass testClass = ReflectionHelper.instantiate(TestClass.class); Assert.assertEquals(0, testClass.getA()); Assert.assertEquals("", testClass.getS()); Assert.assertEquals(1, ReflectionHelper.instantiate(TestClass.class, 1).getA()); Assert.assertEquals("A", ReflectionHelper.instantiate(TestClass.class, 1, "A").getS()); } |
### Question:
GlusterOpenOption { public static GlusterOpenOption READ() { GlusterOpenOption o = new GlusterOpenOption(); o.value = O_RDONLY; o.options.add("read"); return o; } static GlusterOpenOption READ(); static GlusterOpenOption WRITE(); static GlusterOpenOption READWRITE(); GlusterOpenOption create(); GlusterOpenOption createNew(); GlusterOpenOption truncate(); GlusterOpenOption append(); GlusterOpenOption dsync(); GlusterOpenOption sync(); @JniField(flags = {FieldFlag.CONSTANT})
static int O_APPEND; @JniField(flags = {FieldFlag.CONSTANT})
static int O_SYNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_DSYNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_TRUNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_RDONLY; @JniField(flags = {FieldFlag.CONSTANT})
static int O_WRONLY; @JniField(flags = {FieldFlag.CONSTANT})
static int O_RDWR; @JniField(flags = {FieldFlag.CONSTANT})
static int O_CREAT; @JniField(flags = {FieldFlag.CONSTANT})
static int O_EXCL; }### Answer:
@Test public void testRead() { GlusterOpenOption openOption = GlusterOpenOption.READ(); openOption.append().create().createNew().dsync().sync().truncate(); assertEquals(rd | all, openOption.getValue()); } |
### Question:
GlusterOpenOption { public static GlusterOpenOption WRITE() { GlusterOpenOption o = new GlusterOpenOption(); o.value = O_WRONLY; o.options.add("write"); return o; } static GlusterOpenOption READ(); static GlusterOpenOption WRITE(); static GlusterOpenOption READWRITE(); GlusterOpenOption create(); GlusterOpenOption createNew(); GlusterOpenOption truncate(); GlusterOpenOption append(); GlusterOpenOption dsync(); GlusterOpenOption sync(); @JniField(flags = {FieldFlag.CONSTANT})
static int O_APPEND; @JniField(flags = {FieldFlag.CONSTANT})
static int O_SYNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_DSYNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_TRUNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_RDONLY; @JniField(flags = {FieldFlag.CONSTANT})
static int O_WRONLY; @JniField(flags = {FieldFlag.CONSTANT})
static int O_RDWR; @JniField(flags = {FieldFlag.CONSTANT})
static int O_CREAT; @JniField(flags = {FieldFlag.CONSTANT})
static int O_EXCL; }### Answer:
@Test public void testWrite() { GlusterOpenOption openOption = GlusterOpenOption.WRITE(); openOption.append().create().createNew().dsync().sync().truncate(); assertEquals(wr | all, openOption.getValue()); } |
### Question:
GlusterOpenOption { public static GlusterOpenOption READWRITE() { GlusterOpenOption o = new GlusterOpenOption(); o.value = O_RDWR; o.options.add("readwrite"); return o; } static GlusterOpenOption READ(); static GlusterOpenOption WRITE(); static GlusterOpenOption READWRITE(); GlusterOpenOption create(); GlusterOpenOption createNew(); GlusterOpenOption truncate(); GlusterOpenOption append(); GlusterOpenOption dsync(); GlusterOpenOption sync(); @JniField(flags = {FieldFlag.CONSTANT})
static int O_APPEND; @JniField(flags = {FieldFlag.CONSTANT})
static int O_SYNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_DSYNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_TRUNC; @JniField(flags = {FieldFlag.CONSTANT})
static int O_RDONLY; @JniField(flags = {FieldFlag.CONSTANT})
static int O_WRONLY; @JniField(flags = {FieldFlag.CONSTANT})
static int O_RDWR; @JniField(flags = {FieldFlag.CONSTANT})
static int O_CREAT; @JniField(flags = {FieldFlag.CONSTANT})
static int O_EXCL; }### Answer:
@Test public void testReadWrite() { GlusterOpenOption openOption = GlusterOpenOption.READWRITE(); openOption.append().create().createNew().dsync().sync().truncate(); assertEquals(rdwr | all, openOption.getValue()); } |
### Question:
BootstrapDataRepo implements DomainRepo { @Override public void recycle () { data.clear(); classMap.clear(); } BootstrapDataRepo(); void add(Object item); void add(List<Object> items); List<Object> getData(); List<Object> getData(Class<?> type); Competition getBootstrapCompetition(); Properties getBootState(); @Override void recycle(); void readBootRecord(URL bootUrl); }### Answer:
@Test public void testRecycle () { uut.add("test1"); uut.add("test2"); uut.add(42); uut.add(43); uut.add(44); List<?> result = uut.getData(); assertEquals(5, result.size(), "five"); uut.recycle(); result = uut.getData(); assertEquals(0, result.size(), "zero"); } |
### Question:
CapacityControlService extends TimeslotPhaseProcessor implements CapacityControl, InitializationService { @Override public RegulationAccumulator getRegulationCapacity (BalancingOrder order) { Tariff tariff = tariffRepo.findTariffById(order.getTariffId()); if (null == tariff) { log.warn("Null tariff " + order.getTariffId() + " for balancing order"); return new RegulationAccumulator(0.0, 0.0); } RegulationAccumulator result = new RegulationAccumulator(0.0, 0.0); List<TariffSubscription> subs = tariffSubscriptionRepo.findSubscriptionsForTariff(tariff); for (TariffSubscription sub : subs) { result.add(sub.getRemainingRegulationCapacity()); } log.info("BalancingOrder " + order.getId() + " capacity = (" + result.getUpRegulationCapacity() + "," + result.getDownRegulationCapacity() + ")"); return result; } @Override String initialize(Competition competition, List<String> completedInits); @Override void exerciseBalancingControl(BalancingOrder order,
double kwh, double payment); @Override void postEconomicControl(EconomicControlEvent event); @Override RegulationAccumulator getRegulationCapacity(BalancingOrder order); @Override void activate(Instant time, int phaseNumber); }### Answer:
@Test public void regulationCapacityRegRate () { TariffSpecification specRR = new TariffSpecification(broker, PowerType.THERMAL_STORAGE_CONSUMPTION) .withExpiration(baseTime.plus(TimeService.DAY * 10)) .withMinDuration(TimeService.DAY * 5) .addRate(new Rate().withValue(-0.11)) .addRate(new RegulationRate().withUpRegulationPayment(0.15) .withDownRegulationPayment(-0.05)); Tariff tariffRR = new Tariff(specRR); tariffRR.init(); TariffSubscription sub1 = tariffSubscriptionRepo.getSubscription(customer1, tariffRR); sub1.subscribe(100); TariffSubscription sub2 = tariffSubscriptionRepo.getSubscription(customer2, tariffRR); sub2.subscribe(200); sub1.setRegulationCapacity(new RegulationCapacity(sub1, 3.0, -1.5)); sub1.usePower(200); sub2.setRegulationCapacity(new RegulationCapacity(sub2, 2.0, -1.1)); sub2.usePower(300); BalancingOrder order = new BalancingOrder(broker, specRR, 1.0, 0.1); RegulationAccumulator cap = capacityControl.getRegulationCapacity(order); assertEquals(700.0, cap.getUpRegulationCapacity(), 1e-6, "correct up-regulation"); assertEquals(-370.0, cap.getDownRegulationCapacity(), 1e-6, "correct down-regulation"); }
@Test public void regulationCapacity () { TariffSubscription sub1 = tariffSubscriptionRepo.getSubscription(customer1, tariff); sub1.subscribe(100); TariffSubscription sub2 = tariffSubscriptionRepo.getSubscription(customer2, tariff); sub2.subscribe(200); sub1.usePower(200); sub2.usePower(300); BalancingOrder order = new BalancingOrder(broker, spec, 1.0, 0.1); RegulationAccumulator cap = capacityControl.getRegulationCapacity(order); assertEquals(0.4 * 500.0, cap.getUpRegulationCapacity(), 1e-6, "correct up-regulation"); assertEquals(0.0, cap.getDownRegulationCapacity(), 1e-6, "correct down-regulation"); } |
### Question:
Battery extends AbstractCustomer implements CustomerModelAccessor { public double getCapacityKWh () { return capacityKWh; } Battery(); Battery(String name); @Override void initialize(); @Override CustomerInfo getCustomerInfo(); @Override void step(); @Override String getName(); @Override void setName(String name); @ConfigurableValue(valueType = "Double", dump = false, description = "size of battery in kWh") @StateChange void setCapacityKWh(double value); double getCapacityKWh(); @ConfigurableValue(valueType = "Double", dump = false, description = "maximum charge rate") @StateChange void setMaxChargeKW(double value); double getMaxChargeKW(); @ConfigurableValue(valueType = "Double", dump = false, description = "Maximum discharge rate") void setMaxDischargeKW(double value); double getMaxDischargeKW(); @ConfigurableValue(valueType = "Double", dump = false, description = "ratio of charge energy to battery energy") @StateChange void setChargeEfficiency(double value); double getChargeEfficiency(); @ConfigurableValue(valueType = "Double", dump = false, description = "hourly charge lost as proportion of capacity") void setSelfDischargeRate(double value); double getSelfDischargeRate(); @Override double getBrokerSwitchFactor(boolean isSuperseding); @Override double getTariffChoiceSample(); @Override double getInertiaSample(); @Override void evaluateTariffs(List<Tariff> tariffs); @Override double getShiftingInconvenienceFactor(Tariff tariff); @Override CapacityProfile getCapacityProfile(Tariff tariff); }### Answer:
@Test public void testCreate () { Battery battery = new Battery("test"); assertNotNull(battery, "constructed"); assertEquals(50.0, battery.getCapacityKWh(), 1e-6, "correct capacity"); } |
### Question:
LiftTruck extends AbstractCustomer implements CustomerModelAccessor { public LiftTruck () { super(); } LiftTruck(); LiftTruck(String name); @Override void initialize(); @Override CustomerInfo getCustomerInfo(); @Override void step(); @Override String getName(); @Override void setName(String name); @ConfigurableValue(valueType = "Double", dump = false, description = "mean power usage when truck is in use") @StateChange void setTruckKW(double value); double getTruckKW(); @ConfigurableValue(valueType = "Double", dump = false, description = "Std dev of truck power usage") @StateChange void setTruckStd(double stdDev); double getTruckStd(); @ConfigurableValue(valueType = "List", dump = false, description = "shift spec [block, shift, ..., block, shift, ...]") void setShiftData(List<String> data); List<String> getShiftData(); @ConfigurableValue(valueType = "Double", dump = false, description = "size of battery pack in kWh") @StateChange void setBatteryCapacity(double value); double getBatteryCapacity(); @ConfigurableValue(valueType = "Integer", dump = false, description = "total number of battery packs") @StateChange void setNBatteries(int value); int getNBatteries(); @ConfigurableValue(valueType = "Integer", dump = false, description = "number of battery chargers") @StateChange void setNChargers(int value); int getNChargers(); @ConfigurableValue(valueType = "Double", dump = false, description = "maximum charge rate of one truck's battery pack") @StateChange void setMaxChargeKW(double value); double getMaxChargeKW(); @ConfigurableValue(valueType = "Double", dump = false, description = "ratio of charge energy to battery energy") @StateChange void setChargeEfficiency(double value); double getChargeEfficiency(); @ConfigurableValue(valueType = "Integer", dump = false, description = "planning horizon in timeslots - should be at least 48") @StateChange void setPlanningHorizon(int horizon); int getPlanningHorizon(); @ConfigurableValue(valueType = "Integer", dump = false, description = "minimum useful horizon of existing plan") @StateChange void setMinPlanningHorizon(int horizon); int getMinPlanningHorizon(); @StateChange void setEnergyCharging(double kwh); double getEnergyCharging(); void addEnergyCharging(double kwh); @StateChange void setEnergyInUse(double kwh); double getEnergyInUse(); void addEnergyInUse(double kwh); @StateChange void setCapacityInUse(double kwh); double getCapacityInUse(); @Override CapacityProfile getCapacityProfile(Tariff tariff); @Override double getBrokerSwitchFactor(boolean isSuperseding); @Override double getTariffChoiceSample(); @Override double getInertiaSample(); @Override void evaluateTariffs(List<Tariff> tariffs); @Override double getShiftingInconvenienceFactor(Tariff tariff); }### Answer:
@Test public void testLiftTruck () { LiftTruck truck = new LiftTruck("Test"); assertNotNull(truck, "constructed"); assertEquals(8, truck.getNChargers(), "1 trucks 2nd shift"); } |
### Question:
BootstrapDataRepo implements DomainRepo { public void readBootRecord (URL bootUrl) { Document document = getDocument(bootUrl); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); try { XPathExpression exp = xPath.compile("/powertac-bootstrap-data/config/competition"); NodeList nodes = (NodeList) exp.evaluate(document, XPathConstants.NODESET); String xml = nodeToString(nodes.item(0)); bootstrapCompetition = (Competition) messageConverter.fromXML(xml); add(bootstrapCompetition); for (CustomerInfo cust: bootstrapCompetition.getCustomers()) add(cust); exp = xPath.compile("/powertac-bootstrap-data/bootstrap-state/properties"); nodes = (NodeList) exp.evaluate(document, XPathConstants.NODESET); if (null != nodes && nodes.getLength() > 0) { xml = nodeToString(nodes.item(0)); bootState = (Properties) messageConverter.fromXML(xml); } } catch (XPathExpressionException xee) { log.error("Error reading boot record from {}: {}", bootUrl, xee.toString()); System.out.println("Error reading boot dataset: " + xee.toString()); } processBootDataset(document); } BootstrapDataRepo(); void add(Object item); void add(List<Object> items); List<Object> getData(); List<Object> getData(Class<?> type); Competition getBootstrapCompetition(); Properties getBootState(); @Override void recycle(); void readBootRecord(URL bootUrl); }### Answer:
@Test public void testReadBootRecord () { try { URL url = new URL("file:src/test/resources/boot.xml"); uut.readBootRecord(url);; } catch (MalformedURLException e) { fail(e.toString()); } List<Object> items; Competition bc = uut.getBootstrapCompetition(); assertNotNull(bc, "found bootstrap competition"); items = uut.getData(CustomerInfo.class); assertEquals(11, items.size(), "11 customers"); assertEquals(336, uut.getData(WeatherReport.class).size(), "24 weather reports"); } |
### Question:
ColdStorage extends AbstractCustomer implements CustomerModelAccessor { @Override public void evaluateTariffs (List<Tariff> tariffs) { log.info(getName() + ": evaluate tariffs"); tariffEvaluator.evaluateTariffs(); } ColdStorage(); ColdStorage(String name); @Override void initialize(); @Override CustomerInfo getCustomerInfo(); @Override void step(); @Override void evaluateTariffs(List<Tariff> tariffs); @Override CapacityProfile getCapacityProfile(Tariff tariff); @Override double getBrokerSwitchFactor(boolean isSuperseding); @Override double getTariffChoiceSample(); @Override double getInertiaSample(); double getCurrentTemp(); @StateChange void setCurrentTemp(double temp); double getMinTemp(); @ConfigurableValue(valueType = "Double", dump = false, description = "minimum allowable temperature") @StateChange ColdStorage withMinTemp(double temp); double getMaxTemp(); @ConfigurableValue(valueType = "Double", dump = false, description = "maximum allowable temperature") @StateChange ColdStorage withMaxTemp(double temp); double getNominalTemp(); @ConfigurableValue(valueType = "Double", description = "allowable temperature change to save money on TOU tariffs") @StateChange void setShiftSag(double deltaT); double getShiftSag(); @ConfigurableValue(valueType = "Double", dump = false, description = "assumed outdoor temp for tariff evaluation") @StateChange void setEvalEnvTemp(double temp); double getEvalEnvTemp(); @ConfigurableValue(valueType = "Double", dump = false, description = "nominal internal temperature") @StateChange ColdStorage withNominalTemp(double temp); double getNewStockTemp(); @ConfigurableValue(valueType = "Double", dump = false, description = "Temperature of incoming stock") @StateChange ColdStorage withNewStockTemp(double temp); double getStockCapacity(); @ConfigurableValue(valueType = "Double", dump = false, description = "Typical inventory in tonnes of H2O") @StateChange ColdStorage withStockCapacity(double value); double getTurnoverRatio(); @ConfigurableValue(valueType = "Double", description = "Ratio of stock that gets replaced daily") @StateChange ColdStorage withTurnoverRatio(double ratio); double getRoofArea(); @ConfigurableValue(valueType = "Double", dump = false, description = "Area of roof") @StateChange ColdStorage withRoofArea(double area); double getRoofRValue(); @ConfigurableValue(valueType = "Double", description = "R-value of roof insulation") @StateChange ColdStorage withRoofRValue(double value); double getWallArea(); @ConfigurableValue(valueType = "Double", dump = false, description = "Total area of outside walls") @StateChange ColdStorage withWallArea(double area); double getWallRValue(); @ConfigurableValue(valueType = "Double", description = "R-value of wall insulation") @StateChange ColdStorage withWallRValue(double value); double getFloorRValue(); @ConfigurableValue(valueType = "Double", description = "R-value of floor insulation") @StateChange ColdStorage withFloorRValue(double value); double getInfiltrationRatio(); @ConfigurableValue(valueType = "Double", dump = false, description = "Infiltration loss as proportion of wall + roof loss") @StateChange ColdStorage withInfiltrationRatio(double value); double getUnitSize(); @ConfigurableValue(valueType = "Double", dump = false, description = "Thermal capacity in tons of cooling plant") @StateChange ColdStorage withUnitSize(double cap); double getCop(); @ConfigurableValue(valueType = "Double", dump = false, description = "Coefficient of Performance of refrigeration unit") @StateChange ColdStorage withCop(double value); double getHysteresis(); @ConfigurableValue(valueType = "Double", dump = false, description = "Control range for refrigeration unit") @StateChange ColdStorage withHysteresis(double value); double getNonCoolingUsage(); @ConfigurableValue(valueType = "Double", dump = false, description = "Mean hourly energy usage for non-cooling purposes") @StateChange ColdStorage withNonCoolingUsage(double value); @Override double getShiftingInconvenienceFactor(Tariff tariff); }### Answer:
@Test public void testEvaluateTariffs () { } |
### Question:
Config { public synchronized static Config getInstance () { if (null == instance) { log.error("Unconfigured instance requested"); } return instance; } private Config(ServerConfiguration source); boolean isAllocationDetailsLogging(); boolean isCapacityDetailsLogging(); boolean isUsageChargesLogging(); List<String> getStructureTypes(); void configure(); Map<String, Map<String, StructureInstance>> getStructures(); synchronized static Config getInstance(); synchronized static void initializeInstance(ServerConfiguration configSource); }### Answer:
@Test public void testGetInstance () { Config item = Config.getInstance(); assertNotNull(item, "Config created"); } |
### Question:
MisoBuyer extends Broker { public MisoBuyer (String username) { super(username, true, true); } MisoBuyer(String username); void init(BrokerProxy proxy, int seedId, ContextService service); void generateOrders(Instant now, List<Timeslot> openSlots); double getCoolThreshold(); @ConfigurableValue(valueType = "Double", description = "temperature threshold for cooling") MisoBuyer withCoolThreshold(double value); double getCoolCoef(); @ConfigurableValue(valueType = "Double", description = "Multiplier: cooling MWh / degree-hour") MisoBuyer withCoolCoef(double value); double getHeatThreshold(); @ConfigurableValue(valueType = "Double", description = "temperature threshold for heating") MisoBuyer withHeatThreshold(double value); double getHeatCoef(); @ConfigurableValue(valueType = "Double", description = "multiplier: heating MWh / degree-hour (negative for heating)") MisoBuyer withHeatCoef(double value); double getTempAlpha(); @ConfigurableValue(valueType = "Double", description = "exponential smoothing parameter for temperature") MisoBuyer withTempAlpha(double value); double getScaleFactor(); @ConfigurableValue(valueType = "Double", description = "overall scale factor for demand profile") MisoBuyer withScaleFactor(double value); }### Answer:
@Test public void testMisoBuyer() { assertNotNull(buyer, "created something"); assertEquals(buyer.getUsername(), "Test", "correct name"); } |
### Question:
CpGenco extends Broker { public CpGenco (String username) { super(username, true, true); } CpGenco(String username); void init(BrokerProxy proxy, int seedId,
RandomSeedRepo randomSeedRepo,
TimeslotRepo timeslotRepo); void generateOrders(Instant now, List<Timeslot> openSlots); void saveBootstrapState(ServerConfiguration serverConfig); List<String> getCoefficients(); double[] getCoefficientArray(); @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange CpGenco withCoefficients(List<String> coeff); double getPSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange CpGenco withPSigma(double var); double getQSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange CpGenco withQSigma(double var); double getRwaSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for quadratic coefficient") @StateChange CpGenco withRwaSigma(double var); double getRwaOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for quadratic coefficient") @StateChange CpGenco withRwaOffset(double var); double getRwcSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for constant coefficient") @StateChange CpGenco withRwcSigma(double var); double getRwcOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for constant coefficient") @StateChange CpGenco withRwcOffset(double var); double getPriceInterval(); @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange CpGenco withPriceInterval(double interval); double getMinQuantity(); @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange CpGenco withMinQuantity(double qty); double getKneeDemand(); @ConfigurableValue(valueType = "Double", description = "congestion demand threshold") @StateChange CpGenco withKneeDemand(double demand); double getKneeSlope(); @ConfigurableValue(valueType = "Double", description = "congestion demand slope multiplier") @StateChange CpGenco withKneeSlope(double mult); }### Answer:
@Test public void testCpGenco () { assertNotNull(genco, "created something"); assertEquals(genco.getUsername(), "Test", "correct name"); assertEquals(4.0, genco.getPriceInterval(), 1e-6, "correct price interval"); } |
### Question:
CpGenco extends Broker { public void init (BrokerProxy proxy, int seedId, RandomSeedRepo randomSeedRepo, TimeslotRepo timeslotRepo) { log.info("init(" + seedId + ") " + getUsername()); this.brokerProxyService = proxy; this.timeslotRepo = timeslotRepo; this.seed = randomSeedRepo.getRandomSeed(CpGenco.class.getName(), seedId, "bid"); normal01 = new NormalDistribution(0.0, 1.0); normal01.reseedRandomGenerator(seed.nextLong()); if (!function.validateCoefficients(coefficients)) log.error("wrong number of coefficients for quadratic"); int to = Competition.currentCompetition().getTimeslotsOpen(); timeslotCoefficients = new double[to][getCoefficients().size()]; } CpGenco(String username); void init(BrokerProxy proxy, int seedId,
RandomSeedRepo randomSeedRepo,
TimeslotRepo timeslotRepo); void generateOrders(Instant now, List<Timeslot> openSlots); void saveBootstrapState(ServerConfiguration serverConfig); List<String> getCoefficients(); double[] getCoefficientArray(); @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange CpGenco withCoefficients(List<String> coeff); double getPSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange CpGenco withPSigma(double var); double getQSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange CpGenco withQSigma(double var); double getRwaSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for quadratic coefficient") @StateChange CpGenco withRwaSigma(double var); double getRwaOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for quadratic coefficient") @StateChange CpGenco withRwaOffset(double var); double getRwcSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for constant coefficient") @StateChange CpGenco withRwcSigma(double var); double getRwcOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for constant coefficient") @StateChange CpGenco withRwcOffset(double var); double getPriceInterval(); @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange CpGenco withPriceInterval(double interval); double getMinQuantity(); @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange CpGenco withMinQuantity(double qty); double getKneeDemand(); @ConfigurableValue(valueType = "Double", description = "congestion demand threshold") @StateChange CpGenco withKneeDemand(double demand); double getKneeSlope(); @ConfigurableValue(valueType = "Double", description = "congestion demand slope multiplier") @StateChange CpGenco withKneeSlope(double mult); }### Answer:
@Test public void testInit () { init(); verify(mockSeedRepo).getRandomSeed(eq(CpGenco.class.getName()), anyLong(), eq("bid")); double[] ca = genco.getCoefficientArray(); assertNotNull(ca, "initialized array"); assertEquals(3, ca.length, "3 elements"); assertEquals(0.007, ca[0], 1e-6, "correct 1st coeff"); assertEquals(0.1, ca[1], 1e-6, "correct 1st coeff"); assertEquals(16.0, ca[2], 1e-6, "correct 1st coeff"); } |
### Question:
CpGenco extends Broker { @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange public CpGenco withCoefficients (List<String> coeff) { if (function.validateCoefficients(coeff)) { coefficients = coeff; } else { log.error("incorrect number of coefficients"); } return this; } CpGenco(String username); void init(BrokerProxy proxy, int seedId,
RandomSeedRepo randomSeedRepo,
TimeslotRepo timeslotRepo); void generateOrders(Instant now, List<Timeslot> openSlots); void saveBootstrapState(ServerConfiguration serverConfig); List<String> getCoefficients(); double[] getCoefficientArray(); @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange CpGenco withCoefficients(List<String> coeff); double getPSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange CpGenco withPSigma(double var); double getQSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange CpGenco withQSigma(double var); double getRwaSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for quadratic coefficient") @StateChange CpGenco withRwaSigma(double var); double getRwaOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for quadratic coefficient") @StateChange CpGenco withRwaOffset(double var); double getRwcSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for constant coefficient") @StateChange CpGenco withRwcSigma(double var); double getRwcOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for constant coefficient") @StateChange CpGenco withRwcOffset(double var); double getPriceInterval(); @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange CpGenco withPriceInterval(double interval); double getMinQuantity(); @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange CpGenco withMinQuantity(double qty); double getKneeDemand(); @ConfigurableValue(valueType = "Double", description = "congestion demand threshold") @StateChange CpGenco withKneeDemand(double demand); double getKneeSlope(); @ConfigurableValue(valueType = "Double", description = "congestion demand slope multiplier") @StateChange CpGenco withKneeSlope(double mult); }### Answer:
@Test public void testWithCoefficients () { init(); List<String> coefficients = Arrays.asList("1.0", "1.1", "1.2"); genco.withCoefficients(coefficients); assertEquals(3, genco.getCoefficients().size(), "3-element list"); assertEquals(genco.getCoefficients().get(0), "1.0", "first element"); double[] ca = genco.getCoefficientArray(); assertEquals(3, ca.length, "3 elements"); assertEquals(1.0, ca[0], 1e-6, "correct 1st coeff"); assertEquals(1.1, ca[1], 1e-6, "correct 1st coeff"); assertEquals(1.2, ca[2], 1e-6, "correct 1st coeff"); } |
### Question:
CpGenco extends Broker { @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange public CpGenco withPSigma (double var) { this.pSigma = var; return this; } CpGenco(String username); void init(BrokerProxy proxy, int seedId,
RandomSeedRepo randomSeedRepo,
TimeslotRepo timeslotRepo); void generateOrders(Instant now, List<Timeslot> openSlots); void saveBootstrapState(ServerConfiguration serverConfig); List<String> getCoefficients(); double[] getCoefficientArray(); @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange CpGenco withCoefficients(List<String> coeff); double getPSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange CpGenco withPSigma(double var); double getQSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange CpGenco withQSigma(double var); double getRwaSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for quadratic coefficient") @StateChange CpGenco withRwaSigma(double var); double getRwaOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for quadratic coefficient") @StateChange CpGenco withRwaOffset(double var); double getRwcSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for constant coefficient") @StateChange CpGenco withRwcSigma(double var); double getRwcOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for constant coefficient") @StateChange CpGenco withRwcOffset(double var); double getPriceInterval(); @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange CpGenco withPriceInterval(double interval); double getMinQuantity(); @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange CpGenco withMinQuantity(double qty); double getKneeDemand(); @ConfigurableValue(valueType = "Double", description = "congestion demand threshold") @StateChange CpGenco withKneeDemand(double demand); double getKneeSlope(); @ConfigurableValue(valueType = "Double", description = "congestion demand slope multiplier") @StateChange CpGenco withKneeSlope(double mult); }### Answer:
@Test public void testWithPSigma () { init(); assertEquals(0.1, genco.getPSigma(), 1e-6, "correct initial"); genco.withPSigma(0.01); assertEquals(0.01, genco.getPSigma(), 1e-6, "correct post"); } |
### Question:
CpGenco extends Broker { @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange public CpGenco withQSigma (double var) { this.qSigma = var; return this; } CpGenco(String username); void init(BrokerProxy proxy, int seedId,
RandomSeedRepo randomSeedRepo,
TimeslotRepo timeslotRepo); void generateOrders(Instant now, List<Timeslot> openSlots); void saveBootstrapState(ServerConfiguration serverConfig); List<String> getCoefficients(); double[] getCoefficientArray(); @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange CpGenco withCoefficients(List<String> coeff); double getPSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange CpGenco withPSigma(double var); double getQSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange CpGenco withQSigma(double var); double getRwaSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for quadratic coefficient") @StateChange CpGenco withRwaSigma(double var); double getRwaOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for quadratic coefficient") @StateChange CpGenco withRwaOffset(double var); double getRwcSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for constant coefficient") @StateChange CpGenco withRwcSigma(double var); double getRwcOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for constant coefficient") @StateChange CpGenco withRwcOffset(double var); double getPriceInterval(); @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange CpGenco withPriceInterval(double interval); double getMinQuantity(); @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange CpGenco withMinQuantity(double qty); double getKneeDemand(); @ConfigurableValue(valueType = "Double", description = "congestion demand threshold") @StateChange CpGenco withKneeDemand(double demand); double getKneeSlope(); @ConfigurableValue(valueType = "Double", description = "congestion demand slope multiplier") @StateChange CpGenco withKneeSlope(double mult); }### Answer:
@Test public void testWithQSigma () { init(); assertEquals(0.1, genco.getQSigma(), 1e-6, "correct initial"); genco.withQSigma(0.01); assertEquals(0.01, genco.getQSigma(), 1e-6, "correct post"); } |
### Question:
CpGenco extends Broker { @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange public CpGenco withPriceInterval (double interval) { this.priceInterval = interval; return this; } CpGenco(String username); void init(BrokerProxy proxy, int seedId,
RandomSeedRepo randomSeedRepo,
TimeslotRepo timeslotRepo); void generateOrders(Instant now, List<Timeslot> openSlots); void saveBootstrapState(ServerConfiguration serverConfig); List<String> getCoefficients(); double[] getCoefficientArray(); @ConfigurableValue(valueType = "List", bootstrapState = true, dump=false, description = "Coefficients for the specified function type") @StateChange CpGenco withCoefficients(List<String> coeff); double getPSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid price") @StateChange CpGenco withPSigma(double var); double getQSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Standard Deviation ratio for bid quantity") @StateChange CpGenco withQSigma(double var); double getRwaSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for quadratic coefficient") @StateChange CpGenco withRwaSigma(double var); double getRwaOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for quadratic coefficient") @StateChange CpGenco withRwaOffset(double var); double getRwcSigma(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk std dev ratio for constant coefficient") @StateChange CpGenco withRwcSigma(double var); double getRwcOffset(); @ConfigurableValue(valueType = "Double", dump=false, description = "Random-walk offset ratio for constant coefficient") @StateChange CpGenco withRwcOffset(double var); double getPriceInterval(); @ConfigurableValue(valueType = "Double", description = "Nominal price interval between successive bids") @StateChange CpGenco withPriceInterval(double interval); double getMinQuantity(); @ConfigurableValue(valueType = "Double", description = "minimum leadtime for first commitment, in hours") @StateChange CpGenco withMinQuantity(double qty); double getKneeDemand(); @ConfigurableValue(valueType = "Double", description = "congestion demand threshold") @StateChange CpGenco withKneeDemand(double demand); double getKneeSlope(); @ConfigurableValue(valueType = "Double", description = "congestion demand slope multiplier") @StateChange CpGenco withKneeSlope(double mult); }### Answer:
@Test public void testWithPriceInterval () { init(); assertEquals(4.0, genco.getPriceInterval(), 1e-6, "correct initial"); genco.withPriceInterval(6.0); assertEquals(6.0, genco.getPriceInterval(), 1e-6, "correct post"); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.