method2testcases
stringlengths 118
3.08k
|
---|
### Question:
TeamService { @Transactional public boolean create(long userId, String teamName, String cluster, String path) throws ShepherException { long teamId = teamBiz.create(teamName, userId).getId(); userTeamBiz.create(userId, teamId, Role.MASTER, Status.AGREE); long permissionId = permissionBiz.createIfNotExists(cluster, path); permissionTeamBiz.create(permissionId, teamId, Status.PENDING); return true; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testCreate() throws Exception { long userId = 2; String teamName = "test_team"; String cluster = "local_test"; String path = "/test"; boolean createResult = teamService.create(userId, teamName, cluster, path); Assert.assertEquals(true, createResult); } |
### Question:
TeamService { public UserTeam addApply(long userId, long teamId, Role role) throws ShepherException { return userTeamBiz.create(userId, teamId, role, Status.PENDING); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testAddApplyForUserIdTeamIdRole() throws Exception { long userId = 2; long teamId = 5; Role role = Role.MEMBER; UserTeam userTeam = teamService.addApply(userId, teamId, role); Assert.assertNotNull(userTeam); Assert.assertNotEquals(1, userTeam.getId()); } |
### Question:
TeamService { @Transactional public void addMember(User member, long teamId, Role role, User creator) throws ShepherException { if (member == null || creator == null) { throw ShepherException.createIllegalParameterException(); } if (userTeamBiz.listUserByTeamId(teamId).contains(member.getName())) { throw ShepherException.createUserExistsException(); } userTeamBiz.create(member.getId(), teamId, role, Status.AGREE); Team team = this.get(teamId); if (team == null) { throw ShepherException.createNoSuchTeamException(); } Set<String> receivers = new HashSet<>(); receivers.add(member.getName()); mailSenderFactory.getMailSender().noticeJoinTeamHandled(receivers, creator.getName(), Status.AGREE, team.getName(), serverUrl + "/teams/" + teamId + "/members"); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testAddMember() throws Exception { } |
### Question:
TeamService { public List<UserTeam> listUserTeamsPending(Team team) throws ShepherException { if (team == null) { throw ShepherException.createIllegalParameterException(); } return userTeamBiz.listByTeam(team.getId(), Status.PENDING); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testListUserTeamsPending() throws Exception { long userId = 2; long teamId = 5; Role role = Role.MEMBER; Team team = teamService.get(teamId); teamService.addApply(userId, teamId, role); List<UserTeam> applies = teamService.listUserTeamsPending(team); Assert.assertNotNull(applies); Assert.assertEquals(1, applies.size()); } |
### Question:
TeamService { public List<UserTeam> listUserTeamsAgree(Team team) throws ShepherException { if (team == null) { throw ShepherException.createIllegalParameterException(); } return userTeamBiz.listByTeam(team.getId(), Status.AGREE); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testListUserTeamsAgree() throws Exception { long teamId = 1; Team team = teamService.get(teamId); List<UserTeam> applies = teamService.listUserTeamsAgree(team); Assert.assertNotNull(applies); Assert.assertEquals(3, applies.size()); } |
### Question:
TeamService { public List<UserTeam> listUserTeamsJoined(User user) throws ShepherException { if (user == null) { throw ShepherException.createIllegalParameterException(); } return userTeamBiz.listByUser(user.getId(), Status.AGREE); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testListUserTeamsJoined() throws Exception { long userId = 3; User user = new User(); user.setId(userId); List<UserTeam> joinedTeams = teamService.listUserTeamsJoined(user); Assert.assertNotNull(joinedTeams); Assert.assertEquals(2, joinedTeams.size()); } |
### Question:
TeamService { public List<Team> listTeamsToJoin(long userId, String cluster, String path) { return teamBiz.listTeamsByPathAndUser(userId, cluster, path, false); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testListTeamsToJoin() throws Exception { long userId = 4; String cluster = "local_test"; String path = "/test/sub1"; List<Team> teams = teamService.listTeamsToJoin(userId, cluster, path); Assert.assertNotNull(teams); Assert.assertEquals(1, teams.size()); } |
### Question:
TeamService { public List<Team> listTeamsJoined(long userId, String cluster, String path) { return teamBiz.listTeamsByPathAndUser(userId, cluster, path, true); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testListTeamsJoined() throws Exception { long userId = 3; String cluster = "local_test"; String path = "/test/sub1"; List<Team> teams = teamService.listTeamsJoined(userId, cluster, path); Assert.assertNotNull(teams); Assert.assertEquals(1, teams.size()); } |
### Question:
TeamService { public Team get(String teamName) throws ShepherException { return teamBiz.getByName(teamName); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testGetTeamName() throws Exception { String teamName = "admin"; Team team = teamService.get(teamName); Assert.assertNotNull(team); Assert.assertEquals(1, team.getId()); }
@Test public void testGetTeamId() throws Exception { long teamId = 1; Team team = teamService.get(teamId); Assert.assertNotNull(team); Assert.assertEquals("admin", team.getName()); } |
### Question:
NodeService { public String getData(String cluster, String path) throws ShepherException { return nodeDAO.getData(cluster, path); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer:
@Test public void testGetData() throws Exception { String data = nodeService.getData("local_test", "/test"); Assert.assertNull(data); } |
### Question:
TeamService { public int updateStatus(long id, Status status) throws ShepherException { return userTeamBiz.updateStatus(id, status); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testUpdateStatus() throws Exception { long id = 3; Status status = Status.DELETE; int updateResult = teamService.updateStatus(id, status); Assert.assertEquals(RESULT_OK, updateResult); } |
### Question:
TeamService { public int agreeJoin(User user, long id, long teamId) throws ShepherException { int result = this.updateStatus(id, Status.AGREE); this.noticeJoinTeamHandled(id, user, teamId, Status.AGREE); return result; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testAgreeJoin() throws Exception { } |
### Question:
TeamService { public int refuseJoin(User user, long id, long teamId) throws ShepherException { int result = this.updateStatus(id, Status.REFUSE); this.noticeJoinTeamHandled(id, user, teamId, Status.REFUSE); return result; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testRefuseJoin() throws Exception { } |
### Question:
TeamService { public int updateRole(long id, Role role) throws ShepherException { return userTeamBiz.updateRole(id, role); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testUpdateRole() throws Exception { long id = 3; Role role = Role.MEMBER; int updateResult = teamService.updateRole(id, role); Assert.assertEquals(RESULT_OK, updateResult); } |
### Question:
TeamService { public boolean hasApplied(long teamId, String cluster, String path) throws ShepherException { boolean accepted = permissionTeamBiz.get(teamId, cluster, path, Status.AGREE) != null; boolean pending = permissionTeamBiz.get(teamId, cluster, path, Status.PENDING) != null; return accepted || pending; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testHasApplied() throws Exception { long teamId = 5; String cluster = "local_test"; String path = "/test/sub1"; boolean hasApplied = teamService.hasApplied(teamId, cluster, path); Assert.assertEquals(true, hasApplied); } |
### Question:
TeamService { public boolean isMaster(long userId, long teamId) throws ShepherException { return userTeamBiz.getRoleValue(userId, teamId, Status.AGREE) == Role.MASTER.getValue(); } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testIsMaster() throws Exception { long userId = 1; long teamId = 1; boolean isMaster = teamService.isMaster(userId, teamId); Assert.assertEquals(true, isMaster); } |
### Question:
TeamService { public boolean isOwner(long userId, long teamId) { Team team = teamBiz.getById(teamId); return team != null && team.getOwner() == userId; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testIsOwner() throws Exception { long userId = 1; long teamId = 1; boolean isOwner = teamService.isOwner(userId, teamId); Assert.assertEquals(true, isOwner); } |
### Question:
TeamService { public boolean isAdmin(long userId) throws ShepherException { Team team = teamBiz.getByName(ShepherConstants.ADMIN); return userTeamBiz.getRoleValue(userId, team.getId(), Status.AGREE) > ShepherConstants.DEFAULT_ROLEVALUE; } @Transactional boolean create(long userId, String teamName, String cluster, String path); UserTeam addApply(long userId, long teamId, Role role); @Transactional void addApply(User user, long teamId, Role role); @Transactional void addMember(User member, long teamId, Role role, User creator); List<UserTeam> listUserTeamsPending(Team team); List<UserTeam> listUserTeamsAgree(Team team); List<UserTeam> listUserTeamsJoined(User user); List<Team> listTeamsToJoin(long userId, String cluster, String path); List<Team> listTeamsJoined(long userId, String cluster, String path); Team get(String teamName); Team get(long teamId); int updateStatus(long id, Status status); int agreeJoin(User user, long id, long teamId); int refuseJoin(User user, long id, long teamId); int updateRole(long id, Role role); boolean hasApplied(long teamId, String cluster, String path); boolean isMaster(long userId, long teamId); boolean isOwner(long userId, long teamId); boolean isAdmin(long userId); }### Answer:
@Test public void testIsAdmin() throws Exception { long userId = 1; boolean isAdmin = teamService.isAdmin(userId); Assert.assertEquals(true, isAdmin); } |
### Question:
ReviewService { @Transactional public long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus) throws ShepherException { if (creator == null) { throw ShepherException.createIllegalParameterException(); } Stat stat = nodeDAO.getStat(cluster, path, true); long snapshotId = snapshotBiz.getOriginalId(path, cluster, ReviewUtil.DEFAULT_CREATOR, stat, action, true); long newSnapshotId = snapshotBiz.create(cluster, path, data, creator.getName(), action, ReviewUtil.DEFAULT_MTIME, ReviewStatus.NEW, stat.getVersion() + 1, ReviewUtil.DEFAULT_REVIEWER).getId(); Set<String> masters = teamBiz.listUserNamesByPathAndUser(creator.getId(), cluster, path, Role.MASTER); String reviewers = this.asStringReviewers(masters); long reviewId = reviewBiz.create(cluster, path, snapshotId, newSnapshotId, reviewStatus, creator.getName(), ReviewUtil.DEFAULT_REVIEWER, action).getId(); logger.info("Create review request, reviewId={}, creator={}, reviewers={}", reviewId, creator, reviewers); mailSenderFactory.getMailSender().noticeUpdate(masters, creator.getName(), path, cluster, serverUrl + "/reviews/" + reviewId); return reviewId; } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer:
@Test public void testCreate() throws Exception { } |
### Question:
NodeService { public Stat getStat(String cluster, String path) throws ShepherException { return this.getStat(cluster, path, true); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer:
@Test public void testGetStatForClusterPath() throws Exception { Stat stat = nodeService.getStat("local_test", "/test"); Assert.assertNotNull(stat); }
@Test public void testGetStatForClusterPathReturnNullIfPathNotExists() throws Exception { Stat stat = nodeService.getStat("local_test", "/test", true); Assert.assertNotNull(stat); } |
### Question:
ReviewService { @Transactional public int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime) throws ShepherException { snapshotBiz.update(snapshotId, reviewStatus, reviewer, zkMtime); return reviewBiz.update(id, reviewStatus, reviewer); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer:
@Test public void testUpdate() throws Exception { int result = reviewService.update(ReviewStatus.ACCEPTED, 1L, "reviewer", 0L, 0L); Assert.assertNotEquals(0, result); } |
### Question:
ReviewService { @Transactional public int refuse(long id, String reviewer, ReviewRequest reviewRequest) throws ShepherException { if (reviewRequest == null) { throw ShepherException.createIllegalParameterException(); } if (!teamBiz.isAboveRole(reviewRequest.getCluster(), reviewRequest.getPath(), Role.MASTER, reviewer)) { throw ShepherException.createNoAuthorizationException(); } logger.info("Rejected review request, reviewId={}, reviewer={}", id, reviewer); mailSenderFactory.getMailSender().noticeReview(reviewRequest.getCreator(), reviewer, reviewRequest.getPath(), reviewRequest.getCluster(), serverUrl + "/reviews/" + id, ReviewStatus.REJECTED.getDescription()); return this.update(ReviewStatus.REJECTED, id, reviewer, reviewRequest.getNewSnapshot(), ReviewUtil.DEFAULT_MTIME); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer:
@Test public void testRefuse() throws Exception { int result = reviewService.refuse(1L, "testuser", new ReviewRequest("local_test", "/test/sub1", 0, 0, ReviewStatus.ACCEPTED.getValue(), "testuser", "testuser", new Date(), Action.UPDATE.getValue())); Assert.assertNotEquals(0, result); } |
### Question:
ReviewService { public ReviewRequest get(long id) { return reviewBiz.get(id); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer:
@Test public void testGet() throws Exception { ReviewRequest reviewRequest = reviewService.get(1); Assert.assertNotNull(reviewRequest); } |
### Question:
ReviewService { @Transactional public void rejectIfExpired(ReviewRequest reviewRequest) throws ShepherException { if (reviewRequest == null) { throw ShepherException.createIllegalParameterException(); } Snapshot snapshot = snapshotBiz.get(reviewRequest.getNewSnapshot()); if (snapshot != null && reviewRequest.getReviewStatus() == ReviewStatus.NEW.getValue()) { Stat stat = nodeDAO.getStat(snapshot.getCluster(), snapshot.getPath(), true); if (stat == null || stat.getVersion() >= snapshot.getZkVersion()) { this.update(ReviewStatus.REJECTED, reviewRequest.getId(), ReviewUtil.DEFAULT_CREATOR, reviewRequest.getNewSnapshot(), stat == null ? ReviewUtil.DEFAULT_MTIME : stat.getMtime()); reviewRequest.setReviewStatus(ReviewStatus.REJECTED.getValue()); } } } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer:
@Test public void testRejectIfExpired() throws Exception { reviewService.rejectIfExpired(new ReviewRequest("local_test", "/test/sub1", 0, 0, ReviewStatus.ACCEPTED.getValue(), "testuser", "testuser", new Date(), Action.UPDATE.getValue())); } |
### Question:
ReviewService { public int delete(long id) throws ShepherException { return reviewBiz.delete(id); } @Transactional long create(String cluster, String path, String data, User creator, Action action, ReviewStatus reviewStatus); @Transactional int update(ReviewStatus reviewStatus, long id, String reviewer, long snapshotId, long zkMtime); @Transactional int accept(long id, String reviewer, ReviewRequest reviewRequest); @Transactional int refuse(long id, String reviewer, ReviewRequest reviewRequest); ReviewRequest get(long id); @Transactional void rejectIfExpired(ReviewRequest reviewRequest); int delete(long id); }### Answer:
@Test public void testDelete() throws Exception { int result = reviewService.delete(1); Assert.assertEquals(RESULT_OK, result); } |
### Question:
SnapshotService { public List<Snapshot> getByPath(String path, String cluster, int offset, int limit) throws ShepherException { return snapshotBiz.listByPath(path, cluster, offset, limit); } List<Snapshot> getByPath(String path, String cluster, int offset, int limit); Snapshot getById(long id); }### Answer:
@Test public void testGetByPath() throws Exception { String path = "/test/test2"; String cluster = "local_test"; int offset = 0; int limit = 20; List<Snapshot> snapshots = snapshotService.getByPath(path, cluster, offset, limit); Assert.assertNotNull(snapshots); Assert.assertEquals(2, snapshots.size()); } |
### Question:
SnapshotService { public Snapshot getById(long id) { return snapshotBiz.get(id); } List<Snapshot> getByPath(String path, String cluster, int offset, int limit); Snapshot getById(long id); }### Answer:
@Test public void testGetById() throws Exception { Snapshot snapshot = snapshotService.getById(1); Assert.assertNotNull(snapshot); } |
### Question:
UserService { public User get(long id) { return userBiz.getById(id); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer:
@Test public void testGetId() throws Exception { long id = 1; User user = userService.get(id); Assert.assertNotNull(user); Assert.assertEquals("banchuanyu", user.getName()); }
@Test public void testGetName() throws Exception { String name = "banchuanyu"; User user = userService.get(name); Assert.assertNotNull(user); Assert.assertEquals(1, user.getId()); } |
### Question:
UserService { public User create(String name) throws ShepherException { return userBiz.create(name); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer:
@Test public void testCreate() throws Exception { String name = "test_user"; User user = userService.create(name); Assert.assertEquals(4, user.getId()); } |
### Question:
UserService { public User createIfNotExist(String name) throws ShepherException { User user = this.get(name); if (user == null) { user = this.create(name); } return user; } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer:
@Test public void testCreateIfNotExist() throws Exception { String existedName = "banchuanyu"; User user = userService.createIfNotExist(existedName); Assert.assertEquals(1, user.getId()); String name = "test_user"; user = userService.createIfNotExist(name); Assert.assertNotNull(user); Assert.assertEquals(4, user.getId()); } |
### Question:
UserService { public List<User> listByTeams(Set<Long> teams, Status status, Role role) throws ShepherException { return userBiz.list(teams, status, role); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer:
@Test public void testListByTeams() throws Exception { Set<Long> teams = new HashSet<>(); teams.add(1L); teams.add(2L); List<User> users = userService.listByTeams(teams, Status.AGREE, Role.MEMBER); Assert.assertNotNull(users); Assert.assertEquals(3, users.size()); } |
### Question:
UserService { public Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role) throws ShepherException { return userBiz.listNames(teamIds, status, role); } User get(long id); User get(String name); User create(String name); User createIfNotExist(String name); List<User> listByTeams(Set<Long> teams, Status status, Role role); Set<String> listNamesByTeams(Set<Long> teamIds, Status status, Role role); }### Answer:
@Test public void testListNamesByTeams() throws Exception { Set<Long> teams = new HashSet<>(); teams.add(1L); teams.add(2L); Set<String> names = userService.listNamesByTeams(teams, Status.AGREE, Role.MEMBER); Assert.assertNotNull(names); Assert.assertEquals(3, names.size()); } |
### Question:
PermissionService { public PermissionTeam add(long permissionId, long teamId, Status status) throws ShepherException { return permissionTeamBiz.create(permissionId, teamId, status); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testAddForPermissionIdTeamIdStatus() throws Exception { long permissionId = 3; long teamId = 5; Status status = Status.AGREE; PermissionTeam permissionTeam = permissionService.add(permissionId, teamId, status); Assert.assertNotNull(permissionTeam); Assert.assertEquals(4, permissionTeam.getId()); }
@Test public void testAddForTeamIdClusterPathStatus() throws Exception { long teamId = 5; Status status = Status.AGREE; String cluster = "local_test"; String path = "/test"; boolean addResult = permissionService.add(teamId, cluster, path, status); Assert.assertEquals(true, addResult); } |
### Question:
PermissionService { public boolean addPending(long teamId, String cluster, String path) throws ShepherException { return this.add(teamId, cluster, path, Status.PENDING); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testAddPending() throws Exception { long teamId = 5; String cluster = "local_test"; String path = "/test"; boolean addResult = permissionService.addPending(teamId, cluster, path); Assert.assertEquals(true, addResult); } |
### Question:
PermissionService { public boolean addAgree(long teamId, String cluster, String path) throws ShepherException { return this.add(teamId, cluster, path, Status.AGREE); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testAddAgree() throws Exception { long teamId = 5; String cluster = "local_test"; String path = "/test"; boolean addResult = permissionService.addAgree(teamId, cluster, path); Assert.assertEquals(true, addResult); } |
### Question:
PermissionService { public List<PermissionTeam> listPermissionTeamsAgree() throws ShepherException { return permissionTeamBiz.list(Status.AGREE); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testListPermissionTeamsAgree() throws Exception { List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsAgree(); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); } |
### Question:
PermissionService { public List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status) throws ShepherException { return permissionTeamBiz.listByTeam(teamId, status); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testListPermissionTeamsByTeam() throws Exception { long teamId = 5; List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsByTeam(teamId, Status.AGREE); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); } |
### Question:
NodeService { public void create(String cluster, String path, String data, String creator) throws ShepherException { nodeBiz.create(cluster, path, data); long zkCreationTime = nodeDAO.getCreationTime(cluster, path); snapshotBiz.create(cluster, path, data, creator, Action.ADD, zkCreationTime, ReviewStatus.ACCEPTED, ReviewUtil.NEW_CREATE_VERSION, ReviewUtil.DEFAULT_REVIEWER); logger.info("Create node, cluster={}, path={}, operator={}", cluster, path, creator); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer:
@Test public void testCreate() throws Exception { nodeService.create("local_test", "/test", "data", "creator"); } |
### Question:
PermissionService { public List<PermissionTeam> listPermissionTeamsPending() throws ShepherException { return permissionTeamBiz.list(Status.PENDING); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testListPermissionTeamsPending() throws Exception { List<PermissionTeam> permissionTeams = permissionService.listPermissionTeamsPending(); Assert.assertNotNull(permissionTeams); Assert.assertEquals(1, permissionTeams.size()); } |
### Question:
PermissionService { public int updateStatus(long id, Status status) throws ShepherException { return permissionTeamBiz.update(id, status); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testUpdateStatus() throws Exception { int id = 3; Status status = Status.AGREE; int updateResult = permissionService.updateStatus(id, status); Assert.assertEquals(RESULT_OK, updateResult); } |
### Question:
PermissionService { public boolean isPathMember(long userId, String cluster, String path) throws ShepherException { if (ClusterUtil.isPublicCluster(cluster)) { return true; } return teamBiz.isAboveRole(cluster, path, Role.MEMBER, userId); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testIsPathMember() throws Exception { long userId = 3; String cluster = "local_test"; String path = "/test/sub1"; boolean isMember = permissionService.isPathMember(userId, cluster, path); Assert.assertEquals(true, isMember); } |
### Question:
PermissionService { public boolean isPathMaster(long userId, String cluster, String path) throws ShepherException { if (ClusterUtil.isPublicCluster(cluster)) { return true; } return teamBiz.isAboveRole(cluster, path, Role.MASTER, userId); } PermissionTeam add(long permissionId, long teamId, Status status); @Transactional boolean add(long teamId, String cluster, String path, Status status); boolean addPending(long teamId, String cluster, String path); boolean addAgree(long teamId, String cluster, String path); List<PermissionTeam> listPermissionTeamsAgree(); List<PermissionTeam> listPermissionTeamsByTeam(long teamId, Status status); List<PermissionTeam> listPermissionTeamsPending(); int updateStatus(long id, Status status); boolean isPathMember(long userId, String cluster, String path); boolean isPathMaster(long userId, String cluster, String path); boolean isPathMaster(String userName, String cluster, String path); }### Answer:
@Test public void testIsPathMasterForUserIdClusterPath() throws Exception { long userId = 3; String cluster = "local_test"; String path = "/test/sub1"; boolean isMaster = permissionService.isPathMaster(userId, cluster, path); Assert.assertEquals(true, isMaster); }
@Test public void testIsPathMasterForUserNameClusterPath() throws Exception { String userName = "testuser"; String cluster = "local_test"; String path = "/test/sub1"; boolean isMaster = permissionService.isPathMaster(userName, cluster, path); Assert.assertEquals(true, isMaster); } |
### Question:
NodeService { public void update(String cluster, String path, String data, String creator) throws ShepherException { nodeBiz.update(cluster, path, data); Stat stat = nodeDAO.getStat(cluster, path, true); snapshotBiz.create(cluster, path, data, creator, Action.UPDATE, stat.getCtime(), ReviewStatus.ACCEPTED, stat.getVersion(), ReviewUtil.DEFAULT_REVIEWER); logger.info("Update node, cluster={}, path={}, operator={}", cluster, path, creator); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer:
@Test public void testUpdate() throws Exception { nodeService.update("local_test", "/test", "", ""); } |
### Question:
NodeService { public void delete(String cluster, String path, String creator) throws ShepherException { nodeBiz.delete(cluster, path); long snapshotId = snapshotBiz.create(cluster, path, ReviewUtil.EMPTY_CONTENT, creator, Action.DELETE, ReviewUtil.DEFAULT_MTIME, ReviewStatus.DELETED, ReviewUtil.NEW_CREATE_VERSION, ReviewUtil.DEFAULT_REVIEWER).getId(); Set<String> masters = teamBiz.listUserNamesByPath(cluster, path, Role.MASTER); mailSenderFactory.getMailSender().noticeDelete(masters, creator, path, cluster, serverUrl + "/snapshots/" + snapshotId); logger.info("Delete node, cluster={}, path={}, operator={}", cluster, path, creator); } List<String> getChildren(String cluster, String path); String getData(String cluster, String path); Stat getStat(String cluster, String path); Stat getStat(String cluster, String path, boolean returnNullIfPathNotExists); void create(String cluster, String path, String data, String creator); void create(String cluster, String path, String data, String creator, boolean createParents); void createEphemeral(String cluster, String path, String data, String creator); void updateWithPermission(String cluster, String path, String data, String creator); void update(String cluster, String path, String data, String creator); void delete(String cluster, String path, String creator); }### Answer:
@Test public void testDelete() throws Exception { nodeService.delete("local_test", "/test", ""); } |
### Question:
ClusterAdminService { public void create(String name, String config) throws ShepherException { clusterAdminBiz.create(name, config); logger.info("Create cluster, config={}, name={}, operator={}", config, name, userHolder.getUser().getName()); } void create(String name, String config); void update(String name, String config); void delete(String name); List<Cluster> all(); }### Answer:
@Test public void testCreate() throws Exception { clusterAdminService.create("name", "config"); List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(2, clusters.size()); thrown.expect(ShepherException.class); clusterAdminService.create(null, "config"); clusterAdminService.create("local_test", "config"); } |
### Question:
ClusterAdminService { public void update(String name, String config) throws ShepherException { clusterAdminBiz.update(name, config); logger.info("Update cluster, config={}, name={}, operator={}", config, name, userHolder.getUser().getName()); } void create(String name, String config); void update(String name, String config); void delete(String name); List<Cluster> all(); }### Answer:
@Test public void testUpdate() throws Exception { clusterAdminService.update("local_test", "config"); List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(1, clusters.size()); Assert.assertEquals("config", clusters.get(0).getConfig()); thrown.expect(ShepherException.class); clusterAdminService.update(null, "config"); } |
### Question:
ClusterAdminService { public void delete(String name) throws ShepherException { clusterAdminBiz.delete(name); logger.info("Delete cluster, name={}, operator={}", name, userHolder.getUser().getName()); } void create(String name, String config); void update(String name, String config); void delete(String name); List<Cluster> all(); }### Answer:
@Test public void testDelete() throws Exception { clusterAdminService.delete("local_test"); List<Cluster> clusters = clusterAdminService.all(); Assert.assertNotNull(clusters); Assert.assertEquals(0, clusters.size()); thrown.expect(ShepherException.class); clusterAdminService.delete(null); } |
### Question:
FsAccessOptions { public static BitField<FsAccessOption> of(FsAccessOption... options) { return 0 == options.length ? NONE : BitField.of(options[0], options); } private FsAccessOptions(); static BitField<FsAccessOption> of(FsAccessOption... options); static final BitField<FsAccessOption> NONE; static final BitField<FsAccessOption> ACCESS_PREFERENCES_MASK; }### Answer:
@Test public void testOf() { for (final Object[] params : new Object[][] { { new FsAccessOption[0], NONE }, { new FsAccessOption[] { CACHE, CREATE_PARENTS, STORE, COMPRESS, GROW, ENCRYPT }, ACCESS_PREFERENCES_MASK }, }) { final FsAccessOption[] array = (FsAccessOption[]) params[0]; final BitField<?> bits = (BitField<?>) params[1]; assertEquals(FsAccessOptions.of(array), bits); } } |
### Question:
FileBufferPoolFactory extends IoBufferPoolFactory { @Override public int getPriority() { return -100; } @Override IoBufferPool get(); @Override int getPriority(); }### Answer:
@Test public void testPriority() { assertTrue(new FileBufferPoolFactory().getPriority() < 0); } |
### Question:
UShort { public static boolean check( final int i, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= i && i <= MAX_VALUE) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(i) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private UShort(); static boolean check(
final int i,
final @CheckForNull String subject,
final @CheckForNull String error); static boolean check(final int i); static final int MIN_VALUE; static final int MAX_VALUE; static final int SIZE; }### Answer:
@Test public void testCheck() { try { UShort.check(UShort.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } UShort.check(UShort.MIN_VALUE); UShort.check(UShort.MAX_VALUE); try { UShort.check(UShort.MAX_VALUE + 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } } |
### Question:
ULong { public static boolean check( final long l, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= l) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(l) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private ULong(); static boolean check(
final long l,
final @CheckForNull String subject,
final @CheckForNull String error); static boolean check(final long l); static final long MIN_VALUE; static final long MAX_VALUE; static final int SIZE; }### Answer:
@Test public void testCheck() { try { ULong.check(ULong.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } ULong.check(ULong.MIN_VALUE); ULong.check(ULong.MAX_VALUE); } |
### Question:
ExtraField { static void register(final Class<? extends ExtraField> c) { final ExtraField ef; try { ef = c.getDeclaredConstructor().newInstance(); } catch (NullPointerException ex) { throw ex; } catch (Exception ex) { throw new IllegalArgumentException(ex); } final int headerId = ef.getHeaderId(); assert UShort.check(headerId); registry.put(headerId, c); } }### Answer:
@Test public void testRegister() { try { ExtraField.register(null); fail(); } catch (NullPointerException expected) { } try { ExtraField.register(TooSmallHeaderIDExtraField.class); fail(); } catch (IllegalArgumentException expected) { } try { ExtraField.register(TooLargeHeaderIDExtraField.class); fail(); } catch (IllegalArgumentException expected) { } ExtraField.register(NullExtraField.class); } |
### Question:
ExtraField { static ExtraField create(final int headerId) { assert UShort.check(headerId); final Class<? extends ExtraField> c = registry.get(headerId); final ExtraField ef; try { ef = null != c ? c.getDeclaredConstructor().newInstance() : new DefaultExtraField(headerId); } catch (final Exception cannotHappen) { throw new AssertionError(cannotHappen); } assert headerId == ef.getHeaderId(); return ef; } }### Answer:
@Test public void testCreate() { ExtraField ef; ExtraField.register(NullExtraField.class); ef = ExtraField.create(0x0000); assertTrue(ef instanceof NullExtraField); assertEquals(0x0000, ef.getHeaderId()); ef = ExtraField.create(0x0001); assertTrue(ef instanceof DefaultExtraField); assertEquals(0x0001, ef.getHeaderId()); ef = ExtraField.create(0x0002); assertTrue(ef instanceof DefaultExtraField); assertEquals(0x0002, ef.getHeaderId()); ef = ExtraField.create(UShort.MAX_VALUE); assertTrue(ef instanceof DefaultExtraField); assertEquals(UShort.MAX_VALUE, ef.getHeaderId()); try { ef = ExtraField.create(UShort.MIN_VALUE - 1); fail(); } catch (IllegalArgumentException expected) { } try { ef = ExtraField.create(UShort.MAX_VALUE + 1); fail(); } catch (IllegalArgumentException expected) { } } |
### Question:
UByte { public static boolean check( final int i, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= i && i <= MAX_VALUE) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(i) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private UByte(); static boolean check(
final int i,
final @CheckForNull String subject,
final @CheckForNull String error); static boolean check(final int i); static final short MIN_VALUE; static final short MAX_VALUE; static final int SIZE; }### Answer:
@Test public void testCheck() { try { UByte.check(UByte.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } UByte.check(UByte.MIN_VALUE); UByte.check(UByte.MAX_VALUE); try { UByte.check(UByte.MAX_VALUE + 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } } |
### Question:
UInt { public static boolean check( final long l, final @CheckForNull String subject, final @CheckForNull String error) { if (MIN_VALUE <= l && l <= MAX_VALUE) return true; final StringBuilder message = new StringBuilder(); if (null != subject) message.append(subject).append(": "); if (null != error) message.append(error).append(": "); throw new IllegalArgumentException(message .append(l) .append(" is not within ") .append(MIN_VALUE) .append(" and ") .append(MAX_VALUE) .append(" inclusive.") .toString()); } private UInt(); static boolean check(
final long l,
final @CheckForNull String subject,
final @CheckForNull String error); static boolean check(final long l); static final long MIN_VALUE; static final long MAX_VALUE; static final int SIZE; }### Answer:
@Test public void testCheck() { try { UInt.check(UInt.MIN_VALUE - 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } UInt.check(UInt.MIN_VALUE); UInt.check(UInt.MAX_VALUE); try { UInt.check(UInt.MAX_VALUE + 1); fail("Expected IllegalArgumentException!"); } catch (IllegalArgumentException expected) { } } |
### Question:
ZipEntry implements Cloneable { @Override @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") public ZipEntry clone() { final ZipEntry entry; try { entry = (ZipEntry) super.clone(); } catch (CloneNotSupportedException ex) { throw new AssertionError(ex); } final ExtraFields fields = this.fields; entry.fields = fields == null ? null : fields.clone(); return entry; } ZipEntry(final String name); @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") protected ZipEntry(final String name, final ZipEntry template); @Override @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") ZipEntry clone(); final String getName(); final boolean isDirectory(); final int getPlatform(); final void setPlatform(final int platform); final boolean isEncrypted(); final void setEncrypted(boolean encrypted); final void clearEncryption(); final int getMethod(); final void setMethod(final int method); final long getTime(); final void setTime(final long jtime); final long getCrc(); final void setCrc(final long crc); final long getCompressedSize(); final void setCompressedSize(final long csize); final long getSize(); final void setSize(final long size); final long getExternalAttributes(); final void setExternalAttributes(final long eattr); final byte[] getExtra(); final void setExtra(final @CheckForNull byte[] buf); final @CheckForNull String getComment(); final void setComment(final @CheckForNull String comment); @Override String toString(); static final byte UNKNOWN; static final short PLATFORM_FAT; static final short PLATFORM_UNIX; static final int STORED; static final int DEFLATED; static final int BZIP2; static final long MIN_DOS_TIME; static final long MAX_DOS_TIME; }### Answer:
@Test public void testClone() { ZipEntry clone = entry.clone(); assertNotSame(clone, entry); } |
### Question:
DefaultExtraField extends ExtraField { @Override int getDataSize() { final byte[] data = this.data; return null != data ? data.length : 0; } DefaultExtraField(final int headerId); }### Answer:
@Test public void testGetDataSize() { assertEquals(0, field.getDataSize()); } |
### Question:
FsScheme implements Serializable, Comparable<FsScheme> { public static FsScheme create(String scheme) { try { return new FsScheme(scheme); } catch (URISyntaxException ex) { throw new IllegalArgumentException(ex); } } @ConstructorProperties("scheme") FsScheme(final String scheme); static FsScheme create(String scheme); @Deprecated String getScheme(); @Override boolean equals(Object that); @Override int compareTo(FsScheme that); @Override int hashCode(); @Override String toString(); }### Answer:
@Test @SuppressWarnings("ResultOfObjectAllocationIgnored") public void testConstructorWithInvalidUri() throws URISyntaxException { try { FsScheme.create(null); fail(); } catch (NullPointerException expected) { } try { new FsScheme(null); fail(); } catch (NullPointerException expected) { } for (final String param : new String[] { "", "+", "-", ".", }) { try { FsScheme.create(param); fail(param); } catch (IllegalArgumentException expected) { } try { new FsScheme(param); fail(param); } catch (URISyntaxException expected) { } } } |
### Question:
TApplication { @SuppressWarnings("NoopMethodInAbstractClass") protected void setup() { } }### Answer:
@Test public void testSetup() { instance.setup(); } |
### Question:
TApplication { protected abstract int work(String[] args) throws E; }### Answer:
@Test public void testWork() { try { instance.work(null); } catch (NullPointerException expected) { } assertEquals(0, instance.work(new String[0])); } |
### Question:
FsSyncOptions { public static BitField<FsSyncOption> of(FsSyncOption... options) { return 0 == options.length ? NONE : BitField.of(options[0], options); } private FsSyncOptions(); static BitField<FsSyncOption> of(FsSyncOption... options); static final BitField<FsSyncOption> NONE; static final BitField<FsSyncOption> UMOUNT; static final BitField<FsSyncOption> SYNC; static final BitField<FsSyncOption> RESET; }### Answer:
@Test public void testOf() { for (final Object[] params : new Object[][] { { new FsSyncOption[0], NONE }, { new FsSyncOption[] { ABORT_CHANGES }, RESET }, { new FsSyncOption[] { WAIT_CLOSE_IO }, SYNC }, { new FsSyncOption[] { FORCE_CLOSE_IO, CLEAR_CACHE }, UMOUNT }, }) { final FsSyncOption[] array = (FsSyncOption[]) params[0]; final BitField<?> bits = (BitField<?>) params[1]; assertEquals(bits, FsSyncOptions.of(array)); } } |
### Question:
FsNodeName implements Serializable, Comparable<FsNodeName> { public boolean isRoot() { final URI uri = getUri(); final String path = uri.getRawPath(); if (null != path && !path.isEmpty()) return false; final String query = uri.getRawQuery(); return null == query; } @ConstructorProperties("uri") FsNodeName(URI uri); FsNodeName(URI uri, final FsUriModifier modifier); FsNodeName( final FsNodeName parent,
final FsNodeName member); static FsNodeName create(URI uri); static FsNodeName create(URI uri, FsUriModifier modifier); boolean isRoot(); URI getUri(); String getPath(); @CheckForNull String getQuery(); @Override int compareTo(FsNodeName that); @Override boolean equals(@CheckForNull Object that); @Override int hashCode(); @Override String toString(); static final String SEPARATOR; static final char SEPARATOR_CHAR; static final FsNodeName ROOT; }### Answer:
@Test public void testIsRoot() { for (final Object params[] : new Object[][] { { "", true }, { "?", false, }, }) { assertThat(FsNodeName.create(URI.create(params[0].toString())).isRoot(), is(params[1])); } } |
### Question:
User implements Serializable { public User(final String login, final String password) { this.login = login; this.password = password; } User(final String login, final String password); final void setLocale(final String locale); final Date getLastUpdate(); final void setLastUpdate(final Date lastUpdate); final void setDatePattern(final String datePattern); final String getLanguage(); final String getCountry(); final JsonObject getJSONObject(); }### Answer:
@Test public void testUser() { String login = "carl"; String password = "mypassword"; String email = "[email protected]"; User user = User.builder().login(login).password(password).email(email).build(); assertEquals(login, user.getLogin()); assertEquals(email, user.getEmail()); } |
### Question:
Portfolio { public final Optional<Account> getAccount(final String name) { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> account.getName().equals(name)).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer:
@Test public void testGetAccountByName() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getAccount(FIDELITY); assertTrue(actual.isPresent()); }
@Test public void testGetAccountById() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getAccount(2); assertTrue(actual.isPresent()); }
@Test public void testGetAccountByIdEmpty() { Optional<Account> actual = portfolio.getAccount(2); assertFalse(actual.isPresent()); } |
### Question:
Portfolio { public final Optional<Account> getFirstAccount() { return accounts == null ? Optional.empty() : accounts.stream().filter(account -> !account.getDel()).findFirst(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer:
@Test public void testGetFirstAccount() { portfolio.setAccounts(createAccounts()); Optional<Account> actual = portfolio.getFirstAccount(); assertTrue(actual.isPresent()); } |
### Question:
Portfolio { public final String getHTMLSectorByCompanies() { final Map<String, List<Equity>> map = getSectorByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer:
@Test public void testGetHTMLSectorByCompanies() { portfolio.setEquities(createEquities()); String actual = portfolio.getHTMLSectorByCompanies(); verifyHTML(actual); } |
### Question:
Portfolio { public final String getHTMLCapByCompanies() { final Map<String, List<Equity>> map = getGapByCompanies(); return extractHTMLfromMap(map); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer:
@Test public void testGetHTMLCapByCompanies() { portfolio.setEquities(createEquities()); String actual = portfolio.getHTMLCapByCompanies(); verifyHTML(actual); } |
### Question:
Portfolio { public final Double getTotalValue() { return totalValue + getLiquidity(); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer:
@Test public void testGetTotalValue() { Double actual = portfolio.getTotalValue(); assertEquals(0d, actual, 0.1); }
@Test public void testGetTotalValueWithLiquidity() { portfolio.setLiquidity(1000d); Double actual = portfolio.getTotalValue(); assertEquals(1000d, actual, 0.1); } |
### Question:
Portfolio { public final List<String> getCompaniesYahooIdRealTime() { return getEquities().stream() .filter(equity -> equity.getCompany().getRealTime()) .map(equity -> equity.getCompany().getYahooId()) .collect(Collectors.toList()); } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer:
@Test public void testGetCompaniesYahooIdRealTime() { portfolio.setEquities(createEquities()); List<String> actual = portfolio.getCompaniesYahooIdRealTime(); assertNotNull(actual); assertThat(actual, containsInAnyOrder(GOOGLE, APPLE)); } |
### Question:
Portfolio { public final void addIndexes(final List<Index> indexes) { if (indexes.size() > 0) { String index = indexes.get(0).getYahooId(); this.indexes.put(index, indexes); } } Portfolio(); final Double getTotalValue(); final Double getTotalPlusMinusValue(); final Double getTotalPlusMinusValueAbsolute(); final Double getYieldYear(); final Double getTotalGain(); final Double getYieldYearPerc(); final Date getLastCompanyUpdate(); final void setLastCompanyUpdate(final Date lastCompanyUpdate); final void compute(); final Double getTotalGainTodayAbsolute(); final List<String> getCompaniesYahooIdRealTime(); final void addIndexes(final List<Index> indexes); final String getPortfolioReview(); final IChart getPieChartSector(); final IChart getPieChartCap(); final IChart getTimeValueChart(); final IChart getTimeChart(); final Optional<Account> getAccount(final String name); final Optional<Account> getAccount(final int id); final Optional<Account> getFirstAccount(); final String getHTMLSectorByCompanies(); final String getHTMLCapByCompanies(); final Double getMaxShareValue(); final Date getMaxShareValueDate(); final Double getCurrentShareValuesYield(); final Double getCurrentShareValuesTaxes(); final Double getCurrentShareValuesVolume(); final Double getCurrenShareValuesGain(); final Double getCurrenShareValuesGainPorcentage(); final JsonObject getJSONObject(); }### Answer:
@Test public void testAddIndexes() { final List<Index> indexes = new ArrayList<>(); final Index index = Index.builder().yahooId(CAC40).build(); indexes.add(index); portfolio.addIndexes(indexes); final Map<String, List<Index>> actual = portfolio.getIndexes(); assertNotNull(actual); assertThat(actual.size(), is(1)); assertNotNull(actual.get(CAC40)); } |
### Question:
TokenUtils { public static PrivateKey readPrivateKey(String pemResName) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName); byte[] tmp = new byte[4096]; int length = contentIS.read(tmp); PrivateKey privateKey = decodePrivateKey(new String(tmp, 0, length)); return privateKey; } private TokenUtils(); static String generateTokenString(String jsonResName); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims); static PrivateKey readPrivateKey(String pemResName); static PublicKey readPublicKey(String pemResName); static KeyPair generateKeyPair(int keySize); static PrivateKey decodePrivateKey(String pemEncoded); static PublicKey decodePublicKey(String pemEncoded); }### Answer:
@Test public void testReadPrivateKey() throws Exception { PrivateKey privateKey = TokenUtils.readPrivateKey("/privateKey.pem"); System.out.println(privateKey); } |
### Question:
TokenUtils { public static PublicKey readPublicKey(String pemResName) throws Exception { InputStream contentIS = TokenUtils.class.getResourceAsStream(pemResName); byte[] tmp = new byte[4096]; int length = contentIS.read(tmp); PublicKey publicKey = decodePublicKey(new String(tmp, 0, length)); return publicKey; } private TokenUtils(); static String generateTokenString(String jsonResName); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims); static String generateTokenString(String jsonResName, Set<InvalidClaims> invalidClaims, Map<String, Long> timeClaims); static PrivateKey readPrivateKey(String pemResName); static PublicKey readPublicKey(String pemResName); static KeyPair generateKeyPair(int keySize); static PrivateKey decodePrivateKey(String pemEncoded); static PublicKey decodePublicKey(String pemEncoded); }### Answer:
@Test public void testReadPublicKey() throws Exception { RSAPublicKey publicKey = (RSAPublicKey) TokenUtils.readPublicKey("/publicKey.pem"); System.out.println(publicKey); System.out.printf("RSAPublicKey.bitLength: %s\n", publicKey.getModulus().bitLength()); } |
### Question:
MicrometerMetricsRegistry implements MetricsRegistry { @Override public <T> Gauge gauge(String name, Collection<Tag> tags, T obj, ToDoubleFunction<T> f) { return new MicrometerGauge<T>(io.micrometer.core.instrument.Gauge.builder(name, obj, f).tags(toTags(tags)).register(registry)); } MicrometerMetricsRegistry(MeterRegistry registry); @Override Gauge gauge(String name, Collection<Tag> tags, T obj, ToDoubleFunction<T> f); @Override Counter counter(String name, Collection<Tag> tags); @Override Timer timer(String name, Collection<Tag> tags); }### Answer:
@Test public void gaugeOnNullValue() { Gauge gauge = registry.gauge("gauge", emptyList(), null, obj -> 1.0); assertEquals(gauge.value(), Double.NaN, 0); } |
### Question:
Span implements io.opentracing.Span { @Override public void finish() { finishTrace(clock.microTime()); } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString(); @Override void finish(); @Override void finish(long finishMicros); Long getDuration(); Long getStartTime(); Tracer getTracer(); @Override SpanContext context(); String getServiceName(); String getOperationName(); @Override Span setOperationName(String operationName); @Override Span setBaggageItem(String key, String value); @Override String getBaggageItem(String key); Map<String, String> getBaggageItems(); @Override Span setTag(String key, Number value); @Override io.opentracing.Span setTag(Tag<T> tag, T value); @Override Span setTag(String key, boolean value); @Override Span setTag(String key, String value); Map<String, Object> getTags(); @Override Span log(long timestampMicroseconds, Map<String, ?> fields); @Override Span log(long timestampMicroseconds, String event); @Override Span log(Map<String, ?> fields); @Override Span log(String event); List<LogData> getLogs(); }### Answer:
@Test public void testFinishAfterFinish() { InMemoryDispatcher dispatcher = new InMemoryDispatcher.Builder(metrics).build(); tracer = new Tracer.Builder(metrics, "remote-dispatcher", dispatcher).build(); Span span = tracer.buildSpan("operation").start(); span.finish(); try { span.finish(); Assert.fail(); } catch (IllegalStateException ex) { } try { dispatcher.flush(); } catch (IOException ex) { Assert.fail(); } Assert.assertEquals(0, dispatcher.getReportedSpans().size()); Assert.assertEquals(1, dispatcher.getFlushedSpans().size()); Assert.assertEquals(1, dispatcher.getReceivedSpans().size()); } |
### Question:
GRPCAgentClient extends BaseGrpcClient<Span> { @Override public boolean send(Span span) throws ClientException { try (Sample timer = sendTimer.start()) { stub.dispatch(format.format(span), observer); } catch (Exception e) { sendExceptionCounter.increment(); throw new ClientException(e.getMessage(), e); } return true; } GRPCAgentClient(Metrics metrics, Format<com.expedia.open.tracing.Span> format, ManagedChannel channel, SpanAgentStub stub, StreamObserver<DispatchResult> observer, long shutdownTimeoutMS); @Override boolean send(Span span); }### Answer:
@Test public void testDispatch() throws Exception { final Span span = tracer.buildSpan("happy-path").start(); span.finish(); final ArgumentCaptor<com.expedia.open.tracing.Span> spanCapture = ArgumentCaptor.forClass(com.expedia.open.tracing.Span.class); client.send(span); verify(serviceImpl, times(1)).dispatch(spanCapture.capture(), Matchers.<StreamObserver<DispatchResult>>any()); } |
### Question:
RemoteDispatcher implements Dispatcher { @Override public void dispatch(Span span) { try (Sample timer = dispatchTimer.start()) { if (running.get()) { final boolean accepted = acceptQueue.offer(span); if (!accepted) { dispatchRejectedCounter.increment(); LOGGER.warn("Send queue is rejecting new spans"); } } else { dispatchRejectedCounter.increment(); LOGGER.warn("Dispatcher is shutting down and queue is now rejecting new spans"); } } } RemoteDispatcher(Metrics metrics, Client client, BlockingQueue<Span> queue, long flushInterval, long shutdownTimeout, ScheduledExecutorService executor); @Override String toString(); @Override void dispatch(Span span); @Override void close(); @Override void flush(); }### Answer:
@Test public void testFlushTimer() { Span span = tracer.buildSpan("happy-path").start(); dispatcher.dispatch(span); Awaitility.await() .atMost(flushInterval * 2, TimeUnit.MILLISECONDS) .until(() -> client.getFlushedSpans().size() > 0); Assert.assertEquals(0, client.getReceivedSpans().size()); Assert.assertEquals(1, client.getFlushedSpans().size()); Assert.assertEquals(1, client.getTotalSpans().size()); } |
### Question:
Span implements io.opentracing.Span { public String getServiceName() { synchronized (this) { return getTracer().getServiceName(); } } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString(); @Override void finish(); @Override void finish(long finishMicros); Long getDuration(); Long getStartTime(); Tracer getTracer(); @Override SpanContext context(); String getServiceName(); String getOperationName(); @Override Span setOperationName(String operationName); @Override Span setBaggageItem(String key, String value); @Override String getBaggageItem(String key); Map<String, String> getBaggageItems(); @Override Span setTag(String key, Number value); @Override io.opentracing.Span setTag(Tag<T> tag, T value); @Override Span setTag(String key, boolean value); @Override Span setTag(String key, String value); Map<String, Object> getTags(); @Override Span log(long timestampMicroseconds, Map<String, ?> fields); @Override Span log(long timestampMicroseconds, String event); @Override Span log(Map<String, ?> fields); @Override Span log(String event); List<LogData> getLogs(); }### Answer:
@Test public void testServiceName() { String expected = "service-name"; Span span = new Tracer.Builder(metrics, expected, dispatcher).build().buildSpan(expected).start(); Assert.assertEquals(expected, span.getServiceName()); } |
### Question:
Span implements io.opentracing.Span { public Map<String, Object> getTags() { synchronized (this) { return Collections.unmodifiableMap(tags); } } Span(Tracer tracer, Clock clock, String operationName, SpanContext context, long startTime, Map<String, Object> tags, List<Reference> references); @Override String toString(); @Override void finish(); @Override void finish(long finishMicros); Long getDuration(); Long getStartTime(); Tracer getTracer(); @Override SpanContext context(); String getServiceName(); String getOperationName(); @Override Span setOperationName(String operationName); @Override Span setBaggageItem(String key, String value); @Override String getBaggageItem(String key); Map<String, String> getBaggageItems(); @Override Span setTag(String key, Number value); @Override io.opentracing.Span setTag(Tag<T> tag, T value); @Override Span setTag(String key, boolean value); @Override Span setTag(String key, String value); Map<String, Object> getTags(); @Override Span log(long timestampMicroseconds, Map<String, ?> fields); @Override Span log(long timestampMicroseconds, String event); @Override Span log(Map<String, ?> fields); @Override Span log(String event); List<LogData> getLogs(); }### Answer:
@Test public void testTagForTagType() { String key = "typed-key-name"; String value = "typed-tag-value-value"; StringTag stringTag = new StringTag(key); stringTag.set(span, value); Assert.assertEquals(value, span.getTags().get(key)); } |
### Question:
Item { public Long getId() { return id; } Item(); Item(String title, Float price, String description); Long getId(); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); }### Answer:
@Test public void shouldCreateSeveralItems() throws Exception { Item item = new Item("Junk", 52.50f, "A piece of junk"); CD cd01 = new CD("St Pepper", 12.80f, "Beatles master piece", "Apple", 1, 53.32f, "Pop/Rock"); CD cd02 = new CD("Love SUpreme", 20f, "John Coltrane love moment", "Blue Note", 2, 87.45f, "Jazz"); Book book01 = new Book("H2G2", 21f, "Best IT book", "123-456-789", "Pinguin", 321, false); Book book02 = new Book("The Robots of Dawn", 37.5f, "Robots, again and again", "0-553-29949-2 ", "Foundation", 264, true); tx.begin(); em.persist(item); em.persist(cd01); em.persist(cd02); em.persist(book01); em.persist(book02); tx.commit(); assertNotNull(item.getId(), "Item Id should not be null"); assertNotNull(cd01.getId(), "CD1 Id should not be null"); assertNotNull(cd02.getId(), "CD2 Id should not be null"); assertNotNull(book01.getId(), "Book1 Id should not be null"); assertNotNull(book02.getId(), "Book2 Id should not be null"); } |
### Question:
CreditCard { public String getNumber() { return number; } CreditCard(); CreditCard(String number, String expiryDate, Integer controlNumber, CreditCardType creditCardType); String getNumber(); void setNumber(String number); String getExpiryDate(); void setExpiryDate(String expiryDate); Integer getControlNumber(); void setControlNumber(Integer controlNumber); CreditCardType getType(); void setType(CreditCardType creditCardType); }### Answer:
@Test public void shouldCreateACreditCard() throws Exception { CreditCard creditCard = new CreditCard("123412341234", "12/12", 1253, AMERICAN_EXPRESS); tx.begin(); em.persist(creditCard); tx.commit(); assertNotNull(creditCard.getNumber(), "Id should not be null"); String dbCreditCardType = (String) em.createNativeQuery("select creditCardType from CreditCard where number = '123412341234'").getSingleResult(); assertEquals("A", dbCreditCardType, "Should be A for American Express"); }
@Test public void shouldCreateACreditCard() throws Exception { CreditCard creditCard = new CreditCard("123412341234", "12/12", 1253, CreditCardType.AMERICAN_EXPRESS); tx.begin(); em.persist(creditCard); tx.commit(); assertNotNull(creditCard.getNumber(), "Id should not be null"); } |
### Question:
Address { public Long getId() { return id; } Address(); Address(Long id, String street1, String street2, String city, String state, String zipcode, String country); Long getId(); void setId(Long id); String getStreet1(); void setStreet1(String street1); String getStreet2(); void setStreet2(String street2); String getCity(); void setCity(String city); String getState(); void setState(String state); String getZipcode(); void setZipcode(String zipcode); String getCountry(); void setCountry(String country); }### Answer:
@Test public void shouldCreateAnAddress() throws Exception { Address address = new Address(getRandomId(), "65B Ritherdon Rd", "At James place", "London", "LDN", "7QE554", "UK"); tx.begin(); em.persist(address); tx.commit(); assertNotNull(address.getId(), "Id should not be null"); } |
### Question:
Book { public Long getId() { return id; } Book(); Book(Long id, String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); void setId(Long id); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); String getIsbn(); void setIsbn(String isbn); Integer getNbOfPages(); void setNbOfPages(Integer nbOfPages); Boolean getIllustrations(); void setIllustrations(Boolean illustrations); }### Answer:
@Test public void shouldCreateABook() throws Exception { Book book = new Book(getRandomId(), "The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); } |
### Question:
Book { public Long getId() { return id; } Book(); Book(String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); void setId(Long id); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); String getIsbn(); void setIsbn(String isbn); Integer getNbOfPages(); void setNbOfPages(Integer nbOfPages); Boolean getIllustrations(); void setIllustrations(Boolean illustrations); }### Answer:
@Test public void shouldCreateABook() throws Exception { Book book = new Book("The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); } |
### Question:
News { public String getContent() { return content; } News(); News(NewsId id, String content); NewsId getId(); void setId(NewsId id); String getContent(); void setContent(String content); }### Answer:
@Test public void shouldCreateANews() throws Exception { News news = new News(new NewsId("Richard Wright has died", "EN"), "The keyboard of Pink Floyd has died today"); tx.begin(); em.persist(news); tx.commit(); news = em.find(News.class, new NewsId("Richard Wright has died", "EN")); assertEquals("The keyboard of Pink Floyd has died today", news.getContent()); } |
### Question:
AddressEndpoint { @PostMapping("/addresses") public Address createAddress(@RequestBody Address address) { return addressRepository.save(address); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address address); @GetMapping(value = "/addresses/count") Long countAll(); @GetMapping(value = "/addresses/country/{country}") List<Address> getAddressesByCountry(@PathVariable String country); @GetMapping(value = "/addresses/like/{zip}") List<Address> getAddressesLikeZip(@PathVariable String zip); }### Answer:
@Test @Transactional public void createAddress() throws Exception { mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string(ALL_ADDRESSES)); Address address = new Address().street1("233 Spring Street").city("New York").state("NY").zipcode("12345").country("USA"); mockAddressEndpoint.perform(post("/addresses") .contentType("application/json") .content(convertObjectToJsonBytes(address))) .andExpect(status().isOk()); mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string("8")); } |
### Question:
Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber, Date dateOfBirth, Date creationDate); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); Date getDateOfBirth(); void setDateOfBirth(Date dateOfBirth); Date getCreationDate(); void setCreationDate(Date creationDate); }### Answer:
@Test public void shoulCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565", new Date(), new Date()); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); } |
### Question:
BookService { public void createBook() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("cdbookstorePU"); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); Book book = new Book().title("H2G2").price(12.5F).isbn("1-84023-742-2").nbOfPages(354); tx.begin(); em.persist(book); tx.commit(); em.close(); emf.close(); } void createBook(); }### Answer:
@Test void shouldCreateABook() { BookService bookService = new BookService(); bookService.createBook(); } |
### Question:
Customer { public void setAddress(Address address) { this.address = address; } Customer(); Customer(String firstName, String lastName, String email); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); Address getAddress(); void setAddress(Address address); }### Answer:
@Test public void shouldPersistWithFlush() throws Exception { Customer customer = new Customer("Anthony", "Balla", "[email protected]"); Address address = new Address("Ritherdon Rd", "London", "8QE", "UK"); customer.setAddress(address); assertThrows(IllegalStateException.class, () -> { tx.begin(); em.persist(customer); em.flush(); em.persist(address); tx.commit(); }); } |
### Question:
Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); Address getAddress(); void setAddress(Address address); }### Answer:
@Test public void shouldPersistACustomer() throws Exception { Customer customer = new Customer("Anthony", "Balla", "[email protected]"); tx.begin(); em.persist(customer); tx.commit(); assertNotNull(customer.getId()); }
@Test public void shouldPersistAnAddress() throws Exception { Address address = new Address("Ritherdon Rd", "London", "8QE", "UK"); tx.begin(); em.persist(address); tx.commit(); assertNotNull(address.getId()); }
@Test public void shouldPersistACustomerTwice() throws Exception { Customer customer = new Customer("Anthony", "Balla", "[email protected]"); tx.begin(); em.persist(customer); tx.commit(); assertNotNull(customer.getId()); em.clear(); assertThrows(RollbackException.class, () -> { tx.begin(); em.persist(customer); tx.commit(); }); } |
### Question:
Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); void setPhoneNumber(String phoneNumber); @Access(AccessType.PROPERTY) @Column(name = "phone_number", length = 555) String getPhoneNumber(); }### Answer:
@Test public void shouldCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565"); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); } |
### Question:
Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); }### Answer:
@Test public void shouldCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565"); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); } |
### Question:
Customer { @Id @GeneratedValue public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber); void setId(Long id); void setFirstName(String firstName); void setLastName(String lastName); void setEmail(String email); void setPhoneNumber(String phoneNumber); @Id @GeneratedValue Long getId(); @Column(name = "first_name", nullable = false, length = 50) String getFirstName(); @Column(name = "last_name", nullable = false, length = 50) String getLastName(); String getEmail(); @Column(name = "phone_number", length = 15) String getPhoneNumber(); }### Answer:
@Test public void shouldCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565"); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); } |
### Question:
AddressEndpoint { @GetMapping(value = "/addresses/country/{country}") public List<Address> getAddressesByCountry(@PathVariable String country) { return addressRepository.findAllByCountry(country); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address address); @GetMapping(value = "/addresses/count") Long countAll(); @GetMapping(value = "/addresses/country/{country}") List<Address> getAddressesByCountry(@PathVariable String country); @GetMapping(value = "/addresses/like/{zip}") List<Address> getAddressesLikeZip(@PathVariable String zip); }### Answer:
@Test @Transactional public void getAddressesByCountry() throws Exception { mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string(ALL_ADDRESSES)); mockAddressEndpoint.perform(get("/addresses/country/AU")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].country").isArray()); mockAddressEndpoint.perform(get("/addresses/country/dummy")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].country").isEmpty()); } |
### Question:
Author { public Author firstName(String firstName) { this.firstName = firstName; return this; } Long getId(); void setId(Long id); String getFirstName(); void setFirstName(String firstName); Author firstName(String firstName); String getLastName(); void setLastName(String lastName); Author lastName(String lastName); String getBio(); void setBio(String bio); Author surnbioame(String bio); String getEmail(); void setEmail(String email); Author email(String email); }### Answer:
@Test void shouldNotCreateAnAuthorWithNullFirstname() { Author author = new Author().firstName(null); tx.begin(); em.persist(author); assertThrows(RollbackException.class, () -> tx.commit()); } |
### Question:
AddressEndpoint { @GetMapping(value = "/addresses/like/{zip}") public List<Address> getAddressesLikeZip(@PathVariable String zip) { return addressRepository.findAllLikeZip(zip); } AddressEndpoint(AddressRepository addressRepository); @PostMapping("/addresses") Address createAddress(@RequestBody Address address); @GetMapping(value = "/addresses/count") Long countAll(); @GetMapping(value = "/addresses/country/{country}") List<Address> getAddressesByCountry(@PathVariable String country); @GetMapping(value = "/addresses/like/{zip}") List<Address> getAddressesLikeZip(@PathVariable String zip); }### Answer:
@Test @Transactional public void getAddressesLikeZip() throws Exception { mockAddressEndpoint.perform(get("/addresses/count")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(content().string(ALL_ADDRESSES)); mockAddressEndpoint.perform(get("/addresses/like/8QE")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").value("8QE")); mockAddressEndpoint.perform(get("/addresses/like/Q")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").value("8QE")); mockAddressEndpoint.perform(get("/addresses/like/E")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").isArray()); mockAddressEndpoint.perform(get("/addresses/like/dummy")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].zipcode").isEmpty()); } |
### Question:
Artist { public Artist firstName(String firstName) { this.firstName = firstName; return this; } Artist(); Artist(String firstName, String lastName, String email, String bio, LocalDate dateOfBirth); Long getId(); String getFirstName(); void setFirstName(String firstName); Artist firstName(String firstName); String getLastName(); void setLastName(String lastName); Artist lastName(String lastName); String getEmail(); void setEmail(String email); Artist email(String email); String getBio(); void setBio(String bio); Artist bio(String bio); LocalDate getDateOfBirth(); void setDateOfBirth(LocalDate dateOfBirth); Artist dateOfBirth(LocalDate dateOfBirth); @Override String toString(); }### Answer:
@Test void shouldNotCreateAnArtistWithNullFirstname() { Artist artist = new Artist().firstName(null); tx.begin(); em.persist(artist); assertThrows(RollbackException.class, () -> tx.commit()); } |
### Question:
Customer { public Long getId() { return id; } Customer(); Customer(String firstName, String lastName, String email, String phoneNumber, LocalDate dateOfBirth, LocalDateTime creationDate); Long getId(); String getFirstName(); void setFirstName(String firstName); String getLastName(); void setLastName(String lastName); String getEmail(); void setEmail(String email); String getPhoneNumber(); void setPhoneNumber(String phoneNumber); LocalDate getDateOfBirth(); void setDateOfBirth(LocalDate dateOfBirth); Integer getAge(); void setAge(Integer age); LocalDateTime getCreationDate(); void setCreationDate(LocalDateTime creationDate); }### Answer:
@Test public void shoulCreateACustomer() throws Exception { Customer customer = new Customer("John", "Smith", "[email protected]", "1234565", LocalDate.now(), LocalDateTime.now()); tx.begin(); em.persist(customer); tx.commit(); Assertions.assertNotNull(customer.getId(), "Id should not be null"); } |
### Question:
Book { public Long getId() { return id; } Book(); Book(String title, Float price, String description, String isbn, Integer nbOfPages, Boolean illustrations); Long getId(); String getTitle(); void setTitle(String title); Float getPrice(); void setPrice(Float price); String getDescription(); void setDescription(String description); String getIsbn(); void setIsbn(String isbn); Integer getNbOfPages(); void setNbOfPages(Integer nbOfPages); Boolean getIllustrations(); void setIllustrations(Boolean illustrations); }### Answer:
@Test public void shouldCreateABook() throws Exception { Book book = new Book("The Hitchhiker's Guide to the Galaxy", 12.5F, "The Hitchhiker's Guide to the Galaxy is a science fiction comedy series created by Douglas Adams.", "1-84023-742-2", 354, false); tx.begin(); em.persist(book); tx.commit(); assertNotNull(book.getId(), "Id should not be null"); } |
### Question:
Track { public Long getId() { return id; } Track(); Track(String title, Float duration, String description); Long getId(); String getTitle(); void setTitle(String title); Float getDuration(); void setDuration(Float duration); byte[] getWav(); void setWav(byte[] wav); String getDescription(); void setDescription(String description); }### Answer:
@Test public void shouldCreateATrack() throws Exception { Track track = new Track("Sgt Pepper Lonely Heart Club Ban", 4.53f, "Listen to the trumpet carefully, it's George Harrison playing"); tx.begin(); em.persist(track); tx.commit(); assertNotNull(track.getId(), "Id should not be null"); } |
### Question:
News { public String getTitle() { return title; } News(); News(String title, String language, String content); String getTitle(); void setTitle(String title); String getLanguage(); void setLanguage(String language); String getContent(); void setContent(String content); }### Answer:
@Test public void shouldCreateANews() throws Exception { News news = new News("Richard Wright has died", "EN", "The keyboard of Pink Floyd has died today"); tx.begin(); em.persist(news); tx.commit(); assertNotNull(news.getTitle(), "Id should not be null"); } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.