method2testcases
stringlengths 118
3.08k
|
---|
### Question:
DaoVersionedString extends DaoIdentifiable { public void addVersion(final String content, final DaoMember author) { this.currentVersion = new DaoStringVersion(content, this, author); versions.add(currentVersion); } private DaoVersionedString(final String content, final DaoMember author); protected DaoVersionedString(); static DaoVersionedString createAndPersist(final String content, final DaoMember author); void addVersion(final String content, final DaoMember author); void useVersion(final DaoStringVersion version); String getContent(); PageIterable<DaoStringVersion> getVersions(); DaoStringVersion getCurrentVersion(); void compact(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public final void testAddVersion() { final DaoVersionedString str = DaoVersionedString.createAndPersist("plop", fred); str.addVersion("plip", tom); assertEquals(str.getContent(), "plip"); assertEquals(str.getCurrentVersion().getAuthor(), tom); } |
### Question:
Actor extends Identifiable<T> { public final String getLogin() { return getDao().getLogin(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testGetLogin() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getLogin(), db.getTom().getLogin()); final Team publicTeam = Team.create(db.getPublicGroup()); assertEquals(publicTeam.getLogin(), db.getPublicGroup().getLogin()); } |
### Question:
Actor extends Identifiable<T> { public final Date getDateCreation() throws UnauthorizedPublicReadOnlyAccessException { tryAccess(new RgtActor.DateCreation(), Action.READ); return getDao().getDateCreation(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testGetDateCreation() { final Member tom = Member.create(db.getTom()); try { assertEquals(tom.getDateCreation().getTime(), db.getTom().getDateCreation().getTime()); } catch (final UnauthorizedPublicReadOnlyAccessException e) { fail(); } final Team publicTeam = Team.create(db.getPublicGroup()); try { assertEquals(publicTeam.getDateCreation(), db.getPublicGroup().getDateCreation()); } catch (final UnauthorizedPublicReadOnlyAccessException e) { fail(); } } |
### Question:
Actor extends Identifiable<T> { public PageIterable<Contribution> getContributions() { return doGetContributions(); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testGetContributions() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getContributions().size(), db.getTom().getContributions(true).size()); final Team publicTeam = Team.create(db.getPublicGroup()); assertEquals(publicTeam.getContributions().size(), db.getPublicGroup().getContributions().size()); } |
### Question:
Actor extends Identifiable<T> { public abstract String getDisplayName(); protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testGetDisplayName() { final Member tom = Member.create(db.getTom()); assertEquals(tom.getDisplayName(), db.getTom().getFullname()); } |
### Question:
Actor extends Identifiable<T> { public final boolean canAccessDateCreation() { return canAccess(new RgtActor.DateCreation(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testCanAccessDateCreation() { final Member tom = Member.create(db.getTom()); assertTrue(tom.canAccessDateCreation()); } |
### Question:
Actor extends Identifiable<T> { public final boolean canGetInternalAccount() { return canAccess(new RgtActor.InternalAccount(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testCanGetInternalAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetInternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetInternalAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetInternalAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetInternalAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetInternalAccount()); } |
### Question:
Actor extends Identifiable<T> { public final boolean canGetExternalAccount() { return canAccess(new RgtActor.ExternalAccount(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testCanGetExternalAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetExternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetExternalAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetExternalAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetExternalAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetExternalAccount()); } |
### Question:
Actor extends Identifiable<T> { public final boolean canGetBankTransactionAccount() { return canAccess(new RgtActor.BankTransaction(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testCanGetBankTransactionAccount() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertFalse(tom.canGetBankTransactionAccount()); AuthToken.authenticate(memeberFred); assertFalse(tom.canGetBankTransactionAccount()); AuthToken.authenticate(memberTom); assertTrue(tom.canGetBankTransactionAccount()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memeberFred); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(loser); assertFalse(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memberTom); assertTrue(publicTeam.canGetBankTransactionAccount()); AuthToken.authenticate(memberYo); assertTrue(publicTeam.canGetBankTransactionAccount()); } |
### Question:
Actor extends Identifiable<T> { public final boolean canGetContributions() { return canAccess(new RgtActor.Contribution(), Action.READ); } protected Actor(final T id); static Actor<?> getActorFromDao(final DaoActor dao); final void setLogin(final String login); final String getLogin(); final Date getDateCreation(); final InternalAccount getInternalAccount(); final ExternalAccount getExternalAccount(); final PageIterable<BankTransaction> getBankTransactions(); PageIterable<Contribution> getContributions(); Contact getContact(); Contact getContactUnprotected(); abstract PageIterable<Contribution> doGetContributions(); PageIterable<MoneyWithdrawal> getMoneyWithdrawals(); abstract PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); abstract String getDisplayName(); abstract Image getAvatar(); FollowList getFollowedContent(); final boolean canAccessDateCreation(); final boolean canGetInternalAccount(); final boolean canGetExternalAccount(); final boolean canGetBankTransactionAccount(); final boolean canGetContributions(); final boolean isTeam(); boolean hasInvoicingContact(); boolean hasInvoicingContact(final boolean all); }### Answer:
@Test public final void testCanGetContributions() { final Member tom = Member.create(db.getTom()); AuthToken.unAuthenticate(); assertTrue(tom.canGetContributions()); final Team publicTeam = Team.create(db.getPublicGroup()); AuthToken.unAuthenticate(); assertTrue(publicTeam.canGetContributions()); } |
### Question:
Account extends Identifiable<T> { public final boolean canAccessTransaction() { return canAccess(new RgtAccount.Transaction(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testCanAccessTransaction() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessTransaction()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessTransaction()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessTransaction()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessTransaction()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessTransaction()); } |
### Question:
Account extends Identifiable<T> { public final boolean canAccessAmount() { return canAccess(new RgtAccount.Amount(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testCanAccessAmount() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessAmount()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessAmount()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessAmount()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessAmount()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessAmount()); } |
### Question:
Account extends Identifiable<T> { public final boolean canAccessActor() { return canAccess(new RgtAccount.Actor(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testCanAccessActor() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessActor()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessActor()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessActor()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessActor()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessActor()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessActor()); } |
### Question:
Account extends Identifiable<T> { public final boolean canAccessCreationDate() { return canAccess(new RgtAccount.CreationDate(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testCanAccessCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessCreationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessCreationDate()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessCreationDate()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessCreationDate()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessCreationDate()); } |
### Question:
Account extends Identifiable<T> { public final boolean canAccessLastModificationDate() { return canAccess(new RgtAccount.LastModificationDate(), Action.READ); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testCanAccessLastModificationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(tomAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberTom); assertTrue(tomAccount.canAccessLastModificationDate()); AuthToken.authenticate(loser); assertFalse(tomAccount.canAccessLastModificationDate()); final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); AuthToken.unAuthenticate(); assertFalse(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberTom); assertTrue(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memberYo); assertTrue(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(memeberFred); assertFalse(publicGroupAccount.canAccessLastModificationDate()); AuthToken.authenticate(loser); assertFalse(publicGroupAccount.canAccessLastModificationDate()); } |
### Question:
Account extends Identifiable<T> { public final BigDecimal getAmount() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Amount(), Action.READ); return getDao().getAmount(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testGetAmount() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getAmount(); assertEquals(tomAccount.getAmount(), db.getTom().getInternalAccount().getAmount()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getAmount(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getAmount(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getAmount(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
### Question:
Account extends Identifiable<T> { public final PageIterable<Transaction> getTransactions() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Transaction(), Action.READ); return new TransactionList(getDao().getTransactions()); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testGetTransactions() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getTransactions(); assertEquals(tomAccount.getTransactions().size(), db.getTom().getInternalAccount().getTransactions().size()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getTransactions(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getTransactions(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getTransactions(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
### Question:
Account extends Identifiable<T> { public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testGetActor() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getActor(); assertEquals(tomAccount.getActor().getId(), db.getTom().getInternalAccount().getActor().getId()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
### Question:
Account extends Identifiable<T> { public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }### Answer:
@Test public void testGetCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getCreationDate(); assertEquals(tomAccount.getCreationDate(), db.getTom().getInternalAccount().getCreationDate()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } } |
### Question:
DaoUserContent extends DaoIdentifiable { public DaoActor getAuthor() { return asTeam == null ? member : asTeam; } protected DaoUserContent(final DaoMember member, final DaoTeam team); protected DaoUserContent(); DaoMember getMember(); DaoActor getAuthor(); Date getCreationDate(); DaoTeam getAsTeam(); PageIterable<DaoFileMetadata> getFiles(); boolean isDeleted(); void setIsDeleted(final Boolean isDeleted); void addFile(final DaoFileMetadata daoFileMetadata); @Override int hashCode(); @Override boolean equals(final Object obj); }### Answer:
@Test public void testGetAuthor() { assertEquals(yo, feature.getMember()); } |
### Question:
JsDocParser { public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }### Answer:
@Test public void testExtractAttributesMultiline() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("bar jim", doc.getAttribute("foo")); } |
### Question:
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } static String extractFromFilename(String fileName); static File createExtractableTempFile(String key, String suffix); static final String SPEAKEASY_KEY_SEPARATOR; }### Answer:
@Test public void testKeyFromFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.jar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1-bar-2.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.0.zip")); assertEquals("foo-bar", KeyExtractor.extractFromFilename("foo-bar.zip")); }
@Test public void testKeyFromTempFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar.zip")); assertEquals("foo-1", KeyExtractor.extractFromFilename("foo-1----speakeasy-jim.jar")); } |
### Question:
RepositoryDirectoryUtil { public static List<String> getEntries(File root) { return walk(root.toURI(), root); } static List<String> getEntries(File root); static List<String> walk(URI root, File dir); }### Answer:
@Test public void testGetEntries() throws IOException { final File dir = tmp.newFolder("names"); new File(dir, "foo.txt").createNewFile(); new File(dir, "a/b").mkdirs(); new File(dir, "a/bar.txt").createNewFile(); new File(dir, "c").mkdirs(); assertEquals(newArrayList("a/", "a/b/", "a/bar.txt", "c/", "foo.txt"), RepositoryDirectoryUtil.getEntries(dir)); } |
### Question:
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }### Answer:
@Test public void testStripStarsJsDocMultilineComment() { assertEquals("foo", JsDocParser.stripStars("")); }
@Test public void testStripStarsJsDocMultilineCommentWithStars() { assertEquals("foo", JsDocParser.stripStars("")); }
@Test public void testStripStarsJsDocMultilineCommentWithSpaceStars() { assertEquals("foo", JsDocParser.stripStars("")); }
@Test public void testStripStarsJsDocOneLineComment() { assertEquals("foo", JsDocParser.stripStars("")); } |
### Question:
JsDocParser { static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }### Answer:
@Test public void testExtractAttributes() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("Desc", doc.getDescription()); assertEquals("bar", doc.getAttribute("foo")); assertEquals("jim bob", doc.getAttribute("baz")); } |
### Question:
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() { @Override protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) { return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS; } }).put(entity.getTimestamp().getTime(), entity); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource,
long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }### Answer:
@Test public void testSave() { MetricEntity entry = new MetricEntity(); entry.setApp("testSave"); entry.setResource("testResource"); entry.setTimestamp(new Date(System.currentTimeMillis())); entry.setPassQps(1L); entry.setExceptionQps(1L); entry.setBlockQps(0L); entry.setSuccessQps(1L); inMemoryMetricsRepository.save(entry); List<String> resources = inMemoryMetricsRepository.listResourcesOfApp("testSave"); Assert.assertTrue(resources.size() == 1 && "testResource".equals(resources.get(0))); } |
### Question:
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource,
long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }### Answer:
@Test public void testSaveAll() { List<MetricEntity> entities = new ArrayList<>(10000); for (int i = 0; i < 10000; i++) { MetricEntity entry = new MetricEntity(); entry.setApp("testSaveAll"); entry.setResource("testResource" + i); entry.setTimestamp(new Date(System.currentTimeMillis())); entry.setPassQps(1L); entry.setExceptionQps(1L); entry.setBlockQps(0L); entry.setSuccessQps(1L); entities.add(entry); } inMemoryMetricsRepository.saveAll(entities); List<String> result = inMemoryMetricsRepository.listResourcesOfApp("testSaveAll"); Assert.assertTrue(result.size() == entities.size()); } |
### Question:
SpringContextHolder implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; } @Override void setApplicationContext(ApplicationContext applicationContext); static ApplicationContext getApplicationContext(); static T getBean(String name); static T getBean(Class<T> clazz); }### Answer:
@Test public void testGetApplicationContext() { ApplicationContext context = SpringContextHolder.getApplicationContext(); PersonMapper personMapper = SpringContextHolder.getBean(PersonMapper.class); personMapper.findAll(); personMapper.findAll(); logger.info(personMapper.getClass().getName()); } |
### Question:
DashboardConfig { protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; } static String getAuthUsername(); static String getAuthPassword(); static int getHideAppNoMachineMillis(); static int getRemoveAppNoMachineMillis(); static int getAutoRemoveMachineMillis(); static int getUnhealthyMachineMillis(); static void clearCache(); static final int DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS; static final String CONFIG_AUTH_USERNAME; static final String CONFIG_AUTH_PASSWORD; static final String CONFIG_HIDE_APP_NO_MACHINE_MILLIS; static final String CONFIG_REMOVE_APP_NO_MACHINE_MILLIS; static final String CONFIG_UNHEALTHY_MACHINE_MILLIS; static final String CONFIG_AUTO_REMOVE_MACHINE_MILLIS; }### Answer:
@Test public void testGetConfigStr() { DashboardConfig.clearCache(); assertEquals(null, DashboardConfig.getConfigStr("a")); System.setProperty("a", "111"); assertEquals("111", DashboardConfig.getConfigStr("a")); environmentVariables.set("a", "222"); assertEquals("111", DashboardConfig.getConfigStr("a")); DashboardConfig.clearCache(); assertEquals("222", DashboardConfig.getConfigStr("a")); } |
### Question:
ImageConversion { @Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }### Answer:
@Test public void RGB_to_3ByteBGR() { new ImageConversion().RGB_to_3ByteBGR(); } |
### Question:
ImageConversion { @Benchmark public BufferedImage RGBA_to_4ByteABGR() { DataBuffer buffer = new DataBufferByte(RGBA_SRC, RGBA_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[]{0, 1, 2, 3}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }### Answer:
@Test public void RGBA_to_4ByteABGR() { new ImageConversion().RGBA_to_4ByteABGR(); } |
### Question:
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_arraycopy() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); DataBufferByte buffer = (DataBufferByte)(image.getRaster().getDataBuffer()); byte[] data = buffer.getData(); System.arraycopy(ABGR_SRC, 0, data, 0, ABGR_SRC.length); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }### Answer:
@Test public void ABGR_to_4ByteABGR() { new ImageConversion().ABGR_to_4ByteABGR_arraycopy(); } |
### Question:
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_instantiate() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel colorModel; WritableRaster raster; int[] nBits = {8, 8, 8, 8}; int[] bOffs = {3, 2, 1, 0}; colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); DataBufferByte buffer = new DataBufferByte(ABGR_SRC, ABGR_SRC.length); raster = Raster.createInterleavedRaster(buffer, WIDTH, HEIGHT, WIDTH*4, 4, bOffs, null); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }### Answer:
@Test public void ABGR_to_4ByteABGR_instantiate() { new ImageConversion().ABGR_to_4ByteABGR_instantiate(); } |
### Question:
TextDisplay { public void displayText(String text) throws IOException { BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB); Graphics2D graphics = image.createGraphics(); if (big) { text = text.toUpperCase(); } Font sansSerif = new Font("SansSerif", Font.PLAIN, big ? 10 : 8); graphics.setFont(sansSerif); int i = graphics.getFontMetrics().stringWidth(text) - 8; if (i <= 0) { i = 1; } long durationInMillis = duration.toMillis(); for (int j = 0; j <= i; j++) { long start = System.currentTimeMillis(); graphics.setColor(background); graphics.setPaint(background); graphics.fillRect(0, 0, 8, 8); graphics.setColor(foreground); graphics.setPaint(foreground); graphics.drawString(text, -j, big ? 8 : 7); senseHat.fadeTo(image, duration.dividedBy(2)); long timeToSleep = durationInMillis - (System.currentTimeMillis() - start); if(timeToSleep > 0) { try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { log.error(e.getLocalizedMessage(), e); } } } graphics.dispose(); } void displayText(String text); void setForeground(SenseHatColor foreground); void setBackground(SenseHatColor background); }### Answer:
@Test public void displayText() throws Exception { new TextDisplay(senseHat).displayText("Hallo Welt!"); } |
### Question:
FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); failedRegistered.remove(url); failedUnregistered.remove(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } failedRegistered.add(url); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }### Answer:
@Test public void testDoRetry_subscribe() throws Exception { final CountDownLatch latch = new CountDownLatch(1); registry = new MockRegistry(registryUrl, latch); registry.setBad(true); registry.register(serviceUrl); registry.setBad(false); for (int i = 0; i < trytimes; i++) { System.out.println("failback registry retry ,times:" + i); if (latch.getCount() == 0) break; Thread.sleep(sleeptime); } assertEquals(0, latch.getCount()); } |
### Question:
Wrapper { public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; } static Wrapper getWrapper(Class<?> c); abstract String[] getPropertyNames(); abstract Class<?> getPropertyType(String pn); abstract boolean hasProperty(String name); abstract Object getPropertyValue(Object instance, String pn); abstract void setPropertyValue(Object instance, String pn, Object pv); Object[] getPropertyValues(Object instance, String[] pns); void setPropertyValues(Object instance, String[] pns, Object[] pvs); abstract String[] getMethodNames(); abstract String[] getDeclaredMethodNames(); boolean hasMethod(String name); abstract Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args); }### Answer:
@Test public void test_makeEmptyClass() throws Exception { Wrapper.getWrapper(EmptyServiceImpl.class); } |
### Question:
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }### Answer:
@Test public void test_realize_LongPararmter_IllegalArgumentException() throws Exception { Method method = PojoUtilsTest.class.getMethod("setLong", long.class); assertNotNull(method); Object value = PojoUtils.realize("563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); }
@Test public void test_realize_IntPararmter_IllegalArgumentException() throws Exception { Method method = PojoUtilsTest.class.getMethod("setInt", int.class); assertNotNull(method); Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); }
@Test public void testRealize() throws Exception { Map<String, String> inputMap = new LinkedHashMap<String, String>(); inputMap.put("key", "value"); Object obj = PojoUtils.generalize(inputMap); Assert.assertTrue(obj instanceof LinkedHashMap); Object outputObject = PojoUtils.realize(inputMap, LinkedHashMap.class); System.out.println(outputObject.getClass().getName()); Assert.assertTrue(outputObject instanceof LinkedHashMap); } |
### Question:
CollectionUtils { public static List<String> join(Map<String, String> map, String separator) { if (map == null) { return null; } List<String> list = new ArrayList<String>(); if (map == null || map.size() == 0) { return list; } for (Map.Entry<String, String> entry : map.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (value == null || value.length() == 0) { list.add(key); } else { list.add(key + separator + value); } } return list; } private CollectionUtils(); @SuppressWarnings({"unchecked", "rawtypes"}) static List<T> sort(List<T> list); static List<String> sortSimpleName(List<String> list); static Map<String, Map<String, String>> splitAll(Map<String, List<String>> list, String separator); static Map<String, List<String>> joinAll(Map<String, Map<String, String>> map, String separator); static Map<String, String> split(List<String> list, String separator); static List<String> join(Map<String, String> map, String separator); static String join(List<String> list, String separator); static boolean mapEquals(Map<?, ?> map1, Map<?, ?> map2); static Map<String, String> toStringMap(String... pairs); @SuppressWarnings("unchecked") static Map<K, V> toMap(Object... pairs); static boolean isEmpty(Collection<?> collection); static boolean isNotEmpty(Collection<?> collection); }### Answer:
@Test public void test_joinList() throws Exception { List<String> list = Arrays.asList(); assertEquals("", CollectionUtils.join(list, "/")); list = Arrays.asList("x"); assertEquals("x", CollectionUtils.join(list, "-")); list = Arrays.asList("a", "b"); assertEquals("a/b", CollectionUtils.join(list, "/")); } |
### Question:
PageList implements Serializable { public int getPageCount() { int lim = limit; if (limit < 1) { lim = 1; } int page = total / lim; if (page < 1) { return 1; } int remain = total % lim; if (remain > 0) { page += 1; } return page; } PageList(); PageList(int start, int limit, int total, List<T> list); int getStart(); void setStart(int start); int getLimit(); void setLimit(int limit); int getTotal(); void setTotal(int total); List<T> getList(); void setList(List<T> list); int getPageCount(); }### Answer:
@Test public void testGetPageCount() { PageList<Object> pl = new PageList<Object>(0, 100, 52, null); Assert.assertEquals(1, pl.getPageCount()); pl = new PageList<Object>(0, -100, -3, null); Assert.assertEquals(1, pl.getPageCount()); pl = new PageList<Object>(0, 30, 100, null); Assert.assertEquals(4, pl.getPageCount()); } |
### Question:
ReferenceConfigCache { public void destroyAll() { Set<String> set = new HashSet<String>(cache.keySet()); for (String key : set) { destroyKey(key); } } private ReferenceConfigCache(String name, KeyGenerator generator); static ReferenceConfigCache getCache(); static ReferenceConfigCache getCache(String name); static ReferenceConfigCache getCache(String name, KeyGenerator keyGenerator); @SuppressWarnings("unchecked") T get(ReferenceConfig<T> referenceConfig); void destroy(ReferenceConfig<T> referenceConfig); void destroyAll(); @Override String toString(); static final String DEFAULT_NAME; static final KeyGenerator DEFAULT_KEY_GENERATOR; }### Answer:
@Test public void testDestroyAll() throws Exception { ReferenceConfigCache cache = ReferenceConfigCache.getCache(); MockReferenceConfig config = new MockReferenceConfig(); config.setInterface("FooService"); config.setGroup("group1"); config.setVersion("1.0.0"); cache.get(config); MockReferenceConfig configCopy = new MockReferenceConfig(); configCopy.setInterface("XxxService"); configCopy.setGroup("group1"); configCopy.setVersion("1.0.0"); cache.get(configCopy); assertEquals(2, cache.cache.size()); cache.destroyAll(); assertTrue(config.isDestroyMethodRun()); assertTrue(configCopy.isDestroyMethodRun()); assertEquals(0, cache.cache.size()); } |
### Question:
InjvmProtocol extends AbstractProtocol implements Protocol { public boolean isInjvmRefer(URL url) { final boolean isJvmRefer; String scope = url.getParameter(Constants.SCOPE_KEY); if (Constants.LOCAL_PROTOCOL.toString().equals(url.getProtocol())) { isJvmRefer = false; } else if (Constants.SCOPE_LOCAL.equals(scope) || (url.getParameter("injvm", false))) { isJvmRefer = true; } else if (Constants.SCOPE_REMOTE.equals(scope)) { isJvmRefer = false; } else if (url.getParameter(Constants.GENERIC_KEY, false)) { isJvmRefer = false; } else if (getExporter(exporterMap, url) != null) { isJvmRefer = true; } else { isJvmRefer = false; } return isJvmRefer; } InjvmProtocol(); int getDefaultPort(); static InjvmProtocol getInjvmProtocol(); Exporter<T> export(Invoker<T> invoker); Invoker<T> refer(Class<T> serviceType, URL url); boolean isInjvmRefer(URL url); static final String NAME; static final int DEFAULT_PORT; }### Answer:
@Test public void testIsInjvmRefer() throws Exception { DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm: .addParameter(Constants.INTERFACE_KEY, DemoService.class.getName()); Exporter<?> exporter = protocol.export(proxy.getInvoker(service, DemoService.class, url)); exporters.add(exporter); url = url.setProtocol("dubbo"); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); url = url.addParameter(Constants.GROUP_KEY, "*") .addParameter(Constants.VERSION_KEY, "*"); assertTrue(InjvmProtocol.getInjvmProtocol().isInjvmRefer(url)); } |
### Question:
ThriftProtocol extends AbstractProtocol { public <T> Invoker<T> refer(Class<T> type, URL url) throws RpcException { ThriftInvoker<T> invoker = new ThriftInvoker<T>(type, url, getClients(url), invokers); invokers.add(invoker); return invoker; } int getDefaultPort(); Exporter<T> export(Invoker<T> invoker); void destroy(); Invoker<T> refer(Class<T> type, URL url); static final int DEFAULT_PORT; static final String NAME; }### Answer:
@Test public void testRefer() throws Exception { } |
### Question:
DeprecatedFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { String key = invoker.getInterface().getName() + "." + invocation.getMethodName(); if (!logged.contains(key)) { logged.add(key); if (invoker.getUrl().getMethodParameter(invocation.getMethodName(), Constants.DEPRECATED_KEY, false)) { LOGGER.error("The service method " + invoker.getInterface().getName() + "." + getMethodSignature(invocation) + " is DEPRECATED! Declare from " + invoker.getUrl()); } } return invoker.invoke(invocation); } Result invoke(Invoker<?> invoker, Invocation invocation); }### Answer:
@Test public void testDeprecatedFilter() { URL url = URL.valueOf("test: LogUtil.start(); deprecatedFilter.invoke(new MyInvoker<DemoService>(url), new MockInvocation()); assertEquals(1, LogUtil.findMessage("The service method com.alibaba.dubbo.rpc.support.DemoService.echo(String) is DEPRECATED")); LogUtil.stop(); } |
### Question:
ConsumerContextFilter implements Filter { public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { RpcContext.getContext() .setInvoker(invoker) .setInvocation(invocation) .setLocalAddress(NetUtils.getLocalHost(), 0) .setRemoteAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(invoker); } try { return invoker.invoke(invocation); } finally { RpcContext.getContext().clearAttachments(); } } Result invoke(Invoker<?> invoker, Invocation invocation); }### Answer:
@Test public void testSetContext() { URL url = URL.valueOf("test: Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); consumerContextFilter.invoke(invoker, invocation); assertEquals(invoker, RpcContext.getContext().getInvoker()); assertEquals(invocation, RpcContext.getContext().getInvocation()); assertEquals(NetUtils.getLocalHost() + ":0", RpcContext.getContext().getLocalAddressString()); assertEquals("test:11", RpcContext.getContext().getRemoteAddressString()); } |
### Question:
ExplorerApiHelper { static HashCode parseSubmitTxResponse(String json) { SubmitTxResponse response = JSON.fromJson(json, SubmitTxResponse.class); return response.getTxHash(); } private ExplorerApiHelper(); }### Answer:
@Test void parseSubmitTxResponse() { String expected = "f128c720e04b8243"; String json = "{'tx_hash':'" + expected + "'}"; HashCode actual = ExplorerApiHelper.parseSubmitTxResponse(json); assertThat(actual, equalTo(HashCode.fromString(expected))); } |
### Question:
Funnels { public static Funnel<byte[]> byteArrayFunnel() { return ByteArrayFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }### Answer:
@Test void testForBytes() { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.byteArrayFunnel().funnel(new byte[]{4, 3, 2, 1}, primitiveSink); verify(primitiveSink).putBytes(new byte[]{4, 3, 2, 1}); }
@Test void testForBytes_null() { assertNullsThrowException(Funnels.byteArrayFunnel()); } |
### Question:
Funnels { public static Funnel<CharSequence> unencodedCharsFunnel() { return UnencodedCharsFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }### Answer:
@Test void testForStrings() { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.unencodedCharsFunnel().funnel("test", primitiveSink); verify(primitiveSink).putUnencodedChars("test"); }
@Test void testForStrings_null() { assertNullsThrowException(Funnels.unencodedCharsFunnel()); } |
### Question:
ApiController { private void getCounter(RoutingContext rc) { String counterName = getRequiredParameter(rc.request(), COUNTER_NAME_PARAM, identity()); Optional<Counter> counter = service.getValue(counterName); respondWithJson(rc, counter); } ApiController(QaService service); }### Answer:
@Test void getCounter(VertxTestContext context) { String name = "counter"; long value = 10L; Counter counter = new Counter(name, value); when(qaService.getValue(name)).thenReturn(Optional.of(counter)); String getCounterUri = getCounterUri(name); get(getCounterUri) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); Counter actualCounter = JSON_SERIALIZER.fromJson(body, Counter.class); assertThat(actualCounter).isEqualTo(counter); context.completeNow(); }))); } |
### Question:
Funnels { public static Funnel<CharSequence> stringFunnel(Charset charset) { return new StringCharsetFunnel(charset); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }### Answer:
@Test void testForStringsCharset() { for (Charset charset : Charset.availableCharsets().values()) { PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.stringFunnel(charset).funnel("test", primitiveSink); verify(primitiveSink).putString("test", charset); } }
@Test void testForStringsCharset_null() { for (Charset charset : Charset.availableCharsets().values()) { assertNullsThrowException(Funnels.stringFunnel(charset)); } } |
### Question:
Funnels { public static Funnel<Integer> integerFunnel() { return IntegerFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }### Answer:
@Test void testForInts() { Integer value = 1234; PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.integerFunnel().funnel(value, primitiveSink); verify(primitiveSink).putInt(1234); }
@Test void testForInts_null() { assertNullsThrowException(Funnels.integerFunnel()); } |
### Question:
Funnels { public static Funnel<Long> longFunnel() { return LongFunnel.INSTANCE; } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }### Answer:
@Test void testForLongs() { Long value = 1234L; PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnels.longFunnel().funnel(value, primitiveSink); verify(primitiveSink).putLong(1234); }
@Test void testForLongs_null() { assertNullsThrowException(Funnels.longFunnel()); } |
### Question:
Funnels { public static <E> Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel) { return new SequentialFunnel<>(elementFunnel); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }### Answer:
@Test void testSequential() { @SuppressWarnings("unchecked") Funnel<Object> elementFunnel = mock(Funnel.class); PrimitiveSink primitiveSink = mock(PrimitiveSink.class); Funnel<Iterable<?>> sequential = Funnels.sequentialFunnel(elementFunnel); sequential.funnel(Arrays.asList("foo", "bar", "baz", "quux"), primitiveSink); InOrder inOrder = inOrder(elementFunnel); inOrder.verify(elementFunnel).funnel("foo", primitiveSink); inOrder.verify(elementFunnel).funnel("bar", primitiveSink); inOrder.verify(elementFunnel).funnel("baz", primitiveSink); inOrder.verify(elementFunnel).funnel("quux", primitiveSink); } |
### Question:
Funnels { public static OutputStream asOutputStream(PrimitiveSink sink) { return new SinkAsStream(sink); } private Funnels(); static Funnel<byte[]> byteArrayFunnel(); static Funnel<CharSequence> unencodedCharsFunnel(); static Funnel<CharSequence> stringFunnel(Charset charset); static Funnel<Integer> integerFunnel(); static Funnel<Iterable<? extends E>> sequentialFunnel(Funnel<E> elementFunnel); static Funnel<Long> longFunnel(); static OutputStream asOutputStream(PrimitiveSink sink); static Funnel<HashCode> hashCodeFunnel(); }### Answer:
@Test void testAsOutputStream() throws Exception { PrimitiveSink sink = mock(PrimitiveSink.class); OutputStream out = Funnels.asOutputStream(sink); byte[] bytes = {1, 2, 3, 4}; out.write(255); out.write(bytes); out.write(bytes, 1, 2); verify(sink).putByte((byte) 255); verify(sink).putBytes(bytes); verify(sink).putBytes(bytes, 1, 2); } |
### Question:
Cleaner implements AutoCloseable { @Override public String toString() { String hash = Integer.toHexString(System.identityHashCode(this)); MoreObjects.ToStringHelper sb = MoreObjects.toStringHelper(this); sb.add("hash", hash); if (!description.isEmpty()) { sb.add("description", description); } return sb .add("numRegisteredActions", getNumRegisteredActions()) .add("closed", closed) .toString(); } Cleaner(); Cleaner(String description); boolean isClosed(); void add(CleanAction<?> cleanAction); @Override void close(); String getDescription(); int getNumRegisteredActions(); @Override String toString(); }### Answer:
@Test void toStringIncludesContextInformation() { String r = context.toString(); assertThat(r).contains("hash"); assertThat(r).contains("numRegisteredActions=0"); assertThat(r).contains("closed=false"); }
@Test void toStringWithDescriptionIncludesContextInformation() { String description = "Transaction#execute"; context = new Cleaner(description); String r = context.toString(); assertThat(r).contains("description=" + description); } |
### Question:
ApiController { private void getConsensusConfiguration(RoutingContext rc) { Config configuration = service.getConsensusConfiguration(); rc.response() .putHeader(CONTENT_TYPE, OCTET_STREAM.toString()) .end(Buffer.buffer(configuration.toByteArray())); } ApiController(QaService service); }### Answer:
@Test void getConsensusConfiguration(VertxTestContext context) { Config configuration = createConfiguration(); when(qaService.getConsensusConfiguration()).thenReturn(configuration); get(GET_CONSENSUS_CONFIGURATION_PATH) .send(context.succeeding(response -> context.verify(() -> { assertAll( () -> assertThat(response.statusCode()).isEqualTo(HTTP_OK), () -> { Buffer body = response.bodyAsBuffer(); Config consensusConfig = Config.parseFrom(body.getBytes()); assertThat(consensusConfig).isEqualTo(configuration); }); context.completeNow(); }))); } |
### Question:
NativeHandle implements AutoCloseable { @Override public void close() { if (isValid()) { invalidate(); } } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); static final long INVALID_NATIVE_HANDLE; }### Answer:
@Test void close() { nativeHandle = new NativeHandle(HANDLE); nativeHandle.close(); assertFalse(nativeHandle.isValid()); assertThat(nativeHandle.toString()).contains(HANDLE_STRING_REPRESENTATION); } |
### Question:
NativeHandle implements AutoCloseable { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("pointer", Long.toHexString(nativeHandle).toUpperCase()) .toString(); } NativeHandle(long nativeHandle); long get(); @Override void close(); @Override String toString(); static final long INVALID_NATIVE_HANDLE; }### Answer:
@Test void toStringHexRepresentation() { nativeHandle = new NativeHandle(HANDLE); assertThat(nativeHandle.toString()).contains(HANDLE_STRING_REPRESENTATION); } |
### Question:
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override public final void close() { if (isValidHandle()) { try { checkAllRefsValid(); if (dispose) { disposeInternal(); } } finally { invalidate(); } } } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose,
AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose,
Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }### Answer:
@Test void closeShallCallDispose() { proxy = new NativeProxyFake(1L, true); proxy.close(); assertThat(proxy.timesDisposed, equalTo(1)); }
@Test void closeShallCallDisposeOnce() { proxy = new NativeProxyFake(1L, true); proxy.close(); proxy.close(); assertThat(proxy.timesDisposed, equalTo(1)); }
@Test void closeShallNotDisposeNotOwningHandle() { proxy = new NativeProxyFake(1L, false); proxy.close(); assertThat(proxy.timesDisposed, equalTo(0)); }
@Test void closeShallThrowIfReferencedObjectInvalid() { NativeProxyFake reference = makeProxy(2L); proxy = new NativeProxyFake(1L, true, reference); reference.close(); assertThrows(IllegalStateException.class, () -> proxy.close()); }
@Test void shallNotBeValidOnceClosed() { proxy = new NativeProxyFake(1L, true); proxy.close(); assertFalse(proxy.isValidHandle()); }
@Test void notOwningShallNotBeValidOnceClosed() { proxy = new NativeProxyFake(1L, false); proxy.close(); assertFalse(proxy.isValidHandle()); } |
### Question:
AbstractCloseableNativeProxy extends AbstractNativeProxy implements CloseableNativeProxy { @Override protected final long getNativeHandle() { checkAllRefsValid(); return super.getNativeHandle(); } protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose,
AbstractCloseableNativeProxy referenced); protected AbstractCloseableNativeProxy(long nativeHandle, boolean dispose,
Collection<AbstractCloseableNativeProxy> referenced); @Override final void close(); }### Answer:
@Test void getNativeHandle() { long expectedNativeHandle = 0x1FL; proxy = new NativeProxyFake(expectedNativeHandle, true); assertThat(proxy.getNativeHandle(), equalTo(expectedNativeHandle)); }
@Test void getNativeHandle_DirectMultiReferencedAll() { long nativeHandle = 1L; List<AbstractCloseableNativeProxy> referenced = asList(makeProxy(20L), makeProxy(21L), makeProxy(22L) ); proxy = new NativeProxyFake(nativeHandle, true, referenced); assertThat(proxy.getNativeHandle(), equalTo(nativeHandle)); referenced.forEach(CloseableNativeProxy::close); assertThat(proxy, hasInvalidReferences(referenced)); assertThrows(IllegalStateException.class, () -> proxy.getNativeHandle()); } |
### Question:
ApiController { private void getTime(RoutingContext rc) { Optional<TimeDto> time = service.getTime().map(TimeDto::new); respondWithJson(rc, time); } ApiController(QaService service); }### Answer:
@Test void getTime(VertxTestContext context) { ZonedDateTime time = ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); when(qaService.getTime()).thenReturn(Optional.of(time)); get(TIME_PATH) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); TimeDto actualTime = JSON_SERIALIZER .fromJson(body, TimeDto.class); assertThat(actualTime.getTime()).isEqualTo(time); context.completeNow(); }))); } |
### Question:
ProxyDestructor implements CancellableCleanAction<Class<?>> { @CanIgnoreReturnValue public static ProxyDestructor newRegistered(Cleaner cleaner, NativeHandle nativeHandle, Class<?> proxyClass, LongConsumer destructorFunction) { ProxyDestructor d = new ProxyDestructor(nativeHandle, proxyClass, destructorFunction); cleaner.add(d); return d; } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass,
LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner,
NativeHandle nativeHandle,
Class<?> proxyClass,
LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }### Answer:
@Test void newRegistered() { Cleaner cleaner = mock(Cleaner.class); NativeHandle handle = new NativeHandle(1L); LongConsumer destructor = (nh) -> { }; ProxyDestructor d = ProxyDestructor.newRegistered(cleaner, handle, CloseableNativeProxy.class, destructor); assertNotNull(d); verify(cleaner).add(d); } |
### Question:
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); nativeHandle.close(); cleanFunction.accept(handle); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass,
LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner,
NativeHandle nativeHandle,
Class<?> proxyClass,
LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }### Answer:
@Test void clean() { long rawNativeHandle = 1L; NativeHandle handle = new NativeHandle(rawNativeHandle); LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = newDestructor(handle, destructor); d.clean(); assertFalse(handle.isValid()); verify(destructor).accept(rawNativeHandle); }
@Test void cleanIdempotent() { long rawNativeHandle = 1L; NativeHandle handle = spy(new NativeHandle(rawNativeHandle)); LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = newDestructor(handle, destructor); int attemptsToClean = 3; for (int i = 0; i < attemptsToClean; i++) { d.clean(); } assertFalse(handle.isValid()); verify(handle).close(); verify(destructor).accept(rawNativeHandle); } |
### Question:
ProxyDestructor implements CancellableCleanAction<Class<?>> { @Override public Optional<Class<?>> resourceType() { return Optional.of(proxyClass); } ProxyDestructor(NativeHandle nativeHandle, Class<?> proxyClass,
LongConsumer destructorFunction); @CanIgnoreReturnValue static ProxyDestructor newRegistered(Cleaner cleaner,
NativeHandle nativeHandle,
Class<?> proxyClass,
LongConsumer destructorFunction); @Override void clean(); @Override Optional<Class<?>> resourceType(); @Override void cancel(); @Override String toString(); }### Answer:
@Test void getResourceType() { NativeHandle handle = new NativeHandle(1L); Class<?> proxyClass = CloseableNativeProxy.class; LongConsumer destructor = mock(LongConsumer.class); ProxyDestructor d = new ProxyDestructor(handle, proxyClass, destructor); assertThat(d.resourceType()).hasValue(proxyClass); } |
### Question:
ApiController { private void getValidatorsTimes(RoutingContext rc) { Map<PublicKey, ZonedDateTime> validatorsTimes = service.getValidatorsTimes(); respondWithJson(rc, validatorsTimes); } ApiController(QaService service); }### Answer:
@Test void getValidatorsTimes(VertxTestContext context) { Map<PublicKey, ZonedDateTime> validatorsTimes = ImmutableMap.of( PublicKey.fromHexString("11"), ZonedDateTime.of(2018, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC), PublicKey.fromHexString("22"), ZonedDateTime.of(2018, 1, 1, 0, 0, 1, 0, ZoneOffset.UTC)); when(qaService.getValidatorsTimes()).thenReturn(validatorsTimes); get(VALIDATORS_TIMES_PATH) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); Map<PublicKey, ZonedDateTime> actualValidatorsTimes = JSON_SERIALIZER .fromJson(body, new TypeToken<Map<PublicKey, ZonedDateTime>>() { }.getType()); assertThat(actualValidatorsTimes).isEqualTo(validatorsTimes); context.completeNow(); }))); } |
### Question:
AbstractService implements Service { protected final String getName() { return instanceSpec.getName(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }### Answer:
@Test void getName() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getName()).isEqualTo(NAME); } |
### Question:
AbstractService implements Service { protected final int getId() { return instanceSpec.getId(); } protected AbstractService(ServiceInstanceSpec instanceSpec); }### Answer:
@Test void getId() { AbstractService service = new ServiceUnderTest(INSTANCE_SPEC); assertThat(service.getId()).isEqualTo(ID); } |
### Question:
GuiceServicesFactory implements ServicesFactory { @Override public ServiceWrapper createService(LoadedServiceDefinition definition, ServiceInstanceSpec instanceSpec, Node node) { Supplier<ServiceModule> serviceModuleSupplier = definition.getModuleSupplier(); Module serviceModule = serviceModuleSupplier.get(); Module serviceFrameworkModule = new ServiceFrameworkModule(instanceSpec, node); Injector serviceInjector = frameworkInjector.createChildInjector(serviceModule, serviceFrameworkModule); return serviceInjector.getInstance(ServiceWrapper.class); } @Inject GuiceServicesFactory(Injector frameworkInjector); @Override ServiceWrapper createService(LoadedServiceDefinition definition,
ServiceInstanceSpec instanceSpec, Node node); }### Answer:
@Test void createService() { ServiceArtifactId artifactId = ServiceArtifactId.newJavaId("com.acme/foo-service", "1.0.0"); LoadedServiceDefinition serviceDefinition = LoadedServiceDefinition .newInstance(artifactId, TestServiceModule::new); ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(TEST_NAME, TEST_ID, artifactId); Node node = mock(Node.class); ServiceWrapper service = factory.createService(serviceDefinition, instanceSpec, node); assertThat(service.getName()).isEqualTo(TEST_NAME); assertThat(service.getService()).isInstanceOf(TestService.class); }
@Test void createServiceFailsIfNoServiceBindingsInModule() { ServiceArtifactId artifactId = ServiceArtifactId .newJavaId("com.acme/incomplete-service", "1.0.0"); LoadedServiceDefinition serviceDefinition = LoadedServiceDefinition .newInstance(artifactId, IncompleteServiceModule::new); ServiceInstanceSpec instanceSpec = ServiceInstanceSpec.newInstance(TEST_NAME, TEST_ID, artifactId); Node node = mock(Node.class); Exception e = assertThrows(ConfigurationException.class, () -> factory.createService(serviceDefinition, instanceSpec, node)); assertThat(e).hasMessageContaining(Service.class.getSimpleName()); } |
### Question:
RuntimeTransport implements AutoCloseable { void start() { try { server.start(port).get(); } catch (ExecutionException e) { throw new IllegalStateException(e); } catch (InterruptedException e) { logger.error("Start services API server was interrupted", e); Thread.currentThread().interrupt(); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }### Answer:
@Test void start() { when(server.start(PORT)).thenReturn(CompletableFuture.completedFuture(PORT)); transport.start(); verify(server).start(PORT); } |
### Question:
RuntimeTransport implements AutoCloseable { void connectServiceApi(ServiceWrapper service) { Router router = server.createRouter(); service.createPublicApiHandlers(router); String serviceApiPath = createServiceApiPath(service); server.mountSubRouter(serviceApiPath, router); logApiMountEvent(service, serviceApiPath, router); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }### Answer:
@Test void connectServiceApi() { Router serviceRouter = mock(Router.class); when(serviceRouter.getRoutes()).thenReturn(emptyList()); when(server.createRouter()).thenReturn(serviceRouter); String serviceApiPath = "test-service"; ServiceWrapper service = mock(ServiceWrapper.class); when(service.getPublicApiRelativePath()).thenReturn(serviceApiPath); transport.connectServiceApi(service); verify(service).createPublicApiHandlers(serviceRouter); verify(server).mountSubRouter(API_ROOT_PATH + "/" + serviceApiPath, serviceRouter); } |
### Question:
RuntimeTransport implements AutoCloseable { void disconnectServiceApi(ServiceWrapper service) { String serviceApiPath = createServiceApiPath(service); server.removeSubRouter(serviceApiPath); logger.info("Removed the service API endpoints at {}", serviceApiPath); } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }### Answer:
@Test void disconnectServiceApi() { String serviceApiPath = "test-service"; ServiceWrapper service = mock(ServiceWrapper.class); when(service.getPublicApiRelativePath()).thenReturn(serviceApiPath); transport.disconnectServiceApi(service); verify(server).removeSubRouter(API_ROOT_PATH + "/" + serviceApiPath); } |
### Question:
RuntimeTransport implements AutoCloseable { @Override public void close() throws InterruptedException { try { server.stop().get(); } catch (ExecutionException e) { throw new IllegalStateException(e.getCause()); } } @Inject RuntimeTransport(Server server, @Named(SERVICE_WEB_SERVER_PORT) int port); @Override void close(); }### Answer:
@Test void close() throws InterruptedException { when(server.stop()).thenReturn(CompletableFuture.completedFuture(null)); transport.close(); verify(server).stop(); }
@Test void closeReportsOtherFailures() { CompletableFuture<Void> stopResult = new CompletableFuture<>(); Throwable stopCause = new RuntimeException("Stop failure cause"); stopResult.completeExceptionally(stopCause); when(server.stop()).thenReturn(stopResult); IllegalStateException e = assertThrows(IllegalStateException.class, () -> transport.close()); assertThat(e).hasCause(stopCause); } |
### Question:
ReflectiveModuleSupplier implements Supplier<ServiceModule> { @Override public ServiceModule get() { return newServiceModule(); } ReflectiveModuleSupplier(Class<? extends ServiceModule> moduleClass); @Override ServiceModule get(); @Override String toString(); }### Answer:
@Test void get() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(Good.class); ServiceModule serviceModule = supplier.get(); assertThat(serviceModule, instanceOf(Good.class)); }
@Test void getProducesFreshInstances() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(Good.class); ServiceModule serviceModule1 = supplier.get(); ServiceModule serviceModule2 = supplier.get(); assertThat(serviceModule1, instanceOf(Good.class)); assertThat(serviceModule2, instanceOf(Good.class)); assertThat(serviceModule1, not(sameInstance(serviceModule2))); }
@Test void getPropagatesExceptions() throws NoSuchMethodException, IllegalAccessException { supplier = new ReflectiveModuleSupplier(BadThrowsInCtor.class); IllegalStateException e = assertThrows(IllegalStateException.class, () -> supplier.get()); Throwable cause = e.getCause(); assertThat(cause, instanceOf(RuntimeException.class)); assertThat(cause.getMessage(), equalTo("BadThrowsInCtor indeed")); } |
### Question:
ServiceConfiguration implements Configuration { @Override public <MessageT extends MessageLite> MessageT getAsMessage(Class<MessageT> parametersType) { Serializer<MessageT> serializer = StandardSerializers.protobuf(parametersType); return serializer.fromBytes(configuration); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test void getAsMessage() { Id config = anyId(); byte[] serializedConfig = config.toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(serializedConfig); Id unpackedConfig = serviceConfiguration.getAsMessage(Id.class); assertThat(unpackedConfig).isEqualTo(config); }
@Test void getAsMessageNotMessage() { byte[] serializedConfig = bytes(1, 2, 3, 4); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(serializedConfig); Exception e = assertThrows(IllegalArgumentException.class, () -> serviceConfiguration.getAsMessage(Id.class)); assertThat(e).hasCauseInstanceOf(InvalidProtocolBufferException.class); } |
### Question:
ServiceConfiguration implements Configuration { @Override public <T> T getAsJson(Class<T> configType) { String configuration = getServiceConfigurationInFormat(Format.JSON); return JsonSerializer.json().fromJson(configuration, configType); } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test void getAsJson() { byte[] configuration = Service.ServiceConfiguration.newBuilder() .setFormat(Format.JSON) .setValue("{'foo' : 'bar'}") .build() .toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(configuration); Foo actualConfig = serviceConfiguration.getAsJson(Foo.class); assertThat(actualConfig.foo).isEqualTo("bar"); } |
### Question:
ServiceConfiguration implements Configuration { @Override public Properties getAsProperties() { String configuration = getServiceConfigurationInFormat(Format.PROPERTIES); Properties properties = new Properties(); try { properties.load(new StringReader(configuration)); } catch (IOException e) { throw new IllegalArgumentException("Error reading properties configuration", e); } return properties; } ServiceConfiguration(byte[] configuration); @Override MessageT getAsMessage(Class<MessageT> parametersType); @Override Format getConfigurationFormat(); @Override String getAsString(); @Override T getAsJson(Class<T> configType); @Override Properties getAsProperties(); @Override String toString(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer:
@Test void getAsProperties() { byte[] configuration = Service.ServiceConfiguration.newBuilder() .setFormat(Format.PROPERTIES) .setValue("foo=foo\nbar=bar") .build() .toByteArray(); ServiceConfiguration serviceConfiguration = new ServiceConfiguration(configuration); Properties properties = serviceConfiguration.getAsProperties(); assertThat(properties).contains(entry("foo", "foo"), entry("bar", "bar")); } |
### Question:
TransactionExtractor { @VisibleForTesting static Map<Integer, Method> findTransactionMethods(Class<?> serviceClass) { Map<Integer, Method> transactionMethods = new HashMap<>(); while (serviceClass != Object.class) { Method[] classMethods = serviceClass.getDeclaredMethods(); for (Method method : classMethods) { if (method.isAnnotationPresent(Transaction.class)) { Transaction annotation = method.getAnnotation(Transaction.class); int transactionId = annotation.value(); checkDuplicates(transactionMethods, transactionId, serviceClass, method); transactionMethods.put(transactionId, method); } } serviceClass = serviceClass.getSuperclass(); } return transactionMethods; } private TransactionExtractor(); }### Answer:
@Test void findTransactionMethodsValidService() throws Exception { Map<Integer, Method> transactions = TransactionExtractor.findTransactionMethods(ValidService.class); assertThat(transactions).hasSize(1); Method transactionMethod = ValidService.class.getMethod("transactionMethod", byte[].class, ExecutionContext.class); assertThat(singletonList(transactionMethod)) .containsExactlyElementsOf(transactions.values()); }
@Test void findMethodsValidServiceInterfaceImplementation() throws Exception { Map<Integer, Method> transactions = TransactionExtractor.findTransactionMethods( ValidServiceInterfaceImplementation.class); assertThat(transactions).hasSize(2); Method transactionMethod = ValidServiceInterfaceImplementation.class.getMethod( "transactionMethod", byte[].class, ExecutionContext.class); Method transactionMethod2 = ValidServiceInterfaceImplementation.class.getMethod( "transactionMethod2", byte[].class, ExecutionContext.class); List<Method> actualMethods = Arrays.asList(transactionMethod, transactionMethod2); assertThat(actualMethods).containsExactlyInAnyOrderElementsOf(transactions.values()); }
@Test void findTransactionMethodsValidServiceProtobufArguments() throws Exception { Map<Integer, Method> transactions = TransactionExtractor.findTransactionMethods(ValidServiceProtobufArgument.class); assertThat(transactions).hasSize(1); Method transactionMethod = ValidServiceProtobufArgument.class.getMethod("transactionMethod", TestProtoMessages.Point.class, ExecutionContext.class); assertThat(transactions.values()) .containsExactlyElementsOf(singletonList(transactionMethod)); } |
### Question:
Fork extends AbstractAccess { public static Fork newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Fork(NativeHandle nativeHandle, ProxyDestructor destructor, Cleaner parentCleaner); static Fork newInstance(long nativeHandle, Cleaner cleaner); static Fork newInstance(long nativeHandle, boolean owningHandle, Cleaner cleaner); @Override Cleaner getCleaner(); void createCheckpoint(); void rollback(); }### Answer:
@Test void canModify() { Fork fork = Fork.newInstance(0x0A, false, new Cleaner()); assertTrue(fork.canModify()); } |
### Question:
OpenIndexRegistry { Optional<StorageIndex> findIndex(Long id) { return Optional.ofNullable(indexes.get(id)); } }### Answer:
@Test void findUnknownIndex() { long unknownId = 1024L; Optional<StorageIndex> index = registry.findIndex(unknownId); assertThat(index).isEmpty(); } |
### Question:
Snapshot extends AbstractAccess { public static Snapshot newInstance(long nativeHandle, Cleaner cleaner) { return newInstance(nativeHandle, true, cleaner); } private Snapshot(NativeHandle nativeHandle, Cleaner cleaner); static Snapshot newInstance(long nativeHandle, Cleaner cleaner); static Snapshot newInstance(long nativeHandle, boolean owningHandle, Cleaner cleaner); @Override Cleaner getCleaner(); }### Answer:
@Test void cannotModify() { Snapshot s = Snapshot.newInstance(0x0A, false, new Cleaner()); assertFalse(s.canModify()); } |
### Question:
ConfigurableRustIter extends AbstractNativeProxy implements RustIter<E> { @Override public Optional<E> next() { checkNotModified(); return Optional.ofNullable(nextFunction.apply(getNativeHandle())); } ConfigurableRustIter(NativeHandle nativeHandle,
LongFunction<E> nextFunction,
ModificationCounter modificationCounter); @Override Optional<E> next(); }### Answer:
@Test void nextFailsIfModifiedBeforeFirstNext() { createFromIterable(emptyList()); notifyModified(); assertThrows(ConcurrentModificationException.class, () -> iter.next()); }
@Test void nextFailsIfModifiedAfterFirstNext() { createFromIterable(asList(1, 2)); iter.next(); notifyModified(); assertThrows(ConcurrentModificationException.class, () -> iter.next()); }
@Test void nextFailsIfHandleClosed() { NativeHandle nh = new NativeHandle(DEFAULT_NATIVE_HANDLE); createFromIterable(nh, asList(1, 2)); nh.close(); assertThrows(IllegalStateException.class, () -> iter.next()); }
@Test void accessModificationResultsInTerminalState() { createFromIterable(asList(1, 2)); notifyModified(); assertThrows(ConcurrentModificationException.class, () -> iter.next()); assertThrows(ConcurrentModificationException.class, () -> iter.next()); } |
### Question:
QaServiceImpl extends AbstractService implements QaService { @Override public void beforeTransactions(ExecutionContext context) { incrementCounter(BEFORE_TXS_COUNTER_NAME, context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments,
ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments,
ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }### Answer:
@Test void beforeTransactions(TestKit testKit) { checkCounter(testKit, BEFORE_TXS_COUNTER_NAME, 0L); for (int i = 1; i <= 2; i++) { testKit.createBlock(); checkCounter(testKit, BEFORE_TXS_COUNTER_NAME, i); } } |
### Question:
AbstractIndexProxy extends AbstractNativeProxy implements StorageIndex { void notifyModified() { checkCanModify(); modCounter.notifyModified(); } AbstractIndexProxy(NativeHandle nativeHandle, IndexAddress address, AbstractAccess access); @Override IndexAddress getAddress(); @Override String toString(); }### Answer:
@Test void notifyModifiedThrowsIfSnapshotPassed() { Snapshot dbView = createSnapshot(); proxy = new IndexProxyImpl(dbView); UnsupportedOperationException thrown = assertThrows(UnsupportedOperationException.class, () -> proxy.notifyModified()); Pattern pattern = Pattern.compile("Cannot modify the access: .*[Ss]napshot.*" + "\\nUse a Fork to modify any collection\\.", Pattern.MULTILINE); assertThat(thrown, hasMessage(matchesPattern(pattern))); } |
### Question:
RustIterAdapter implements Iterator<E> { @Override public E next() { E element = nextItem.orElseThrow( () -> new NoSuchElementException("Reached the end of the underlying collection. " + "Use #hasNext to check if you have reached the end of the collection.")); nextItem = rustIter.next(); return element; } RustIterAdapter(RustIter<E> rustIter); @Override boolean hasNext(); @Override E next(); }### Answer:
@Test void nextThrowsIfNoNextItem0() { adapter = new RustIterAdapter<>( new RustIterTestFake(emptyList())); assertThrows(NoSuchElementException.class, () -> adapter.next()); }
@Test void nextThrowsIfNoNextItem1() { adapter = new RustIterAdapter<>( new RustIterTestFake(singletonList(1))); adapter.next(); assertThrows(NoSuchElementException.class, () -> adapter.next()); } |
### Question:
StoragePreconditions { @CanIgnoreReturnValue static String checkIndexName(String name) { checkArgument(!name.isEmpty(), "name is empty"); return name; } private StoragePreconditions(); }### Answer:
@Test void checkIndexNameAcceptsNonEmpty() { String name = "table1"; assertThat(name, sameInstance(StoragePreconditions.checkIndexName(name))); }
@Test void checkIndexNameDoesNotAcceptNull() { assertThrows(NullPointerException.class, () -> StoragePreconditions.checkIndexName(null)); }
@Test void checkIndexNameDoesNotAcceptEmpty() { assertThrows(IllegalArgumentException.class, () -> { String name = ""; StoragePreconditions.checkIndexName(name); }); } |
### Question:
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkIdInGroup(byte[] indexId) { checkArgument(indexId.length > 0, "index identifier must not be empty"); return indexId; } private StoragePreconditions(); }### Answer:
@Test void checkIdInGroup() { byte[] validId = bytes("id1"); assertThat(StoragePreconditions.checkIdInGroup(validId), sameInstance(validId)); }
@Test void checkIdInGroupNull() { assertThrows(NullPointerException.class, () -> StoragePreconditions.checkIdInGroup(null)); }
@Test void checkIdInGroupEmpty() { byte[] emptyId = new byte[0]; assertThrows(IllegalArgumentException.class, () -> StoragePreconditions.checkIdInGroup(emptyId)); } |
### Question:
QaServiceImpl extends AbstractService implements QaService { @Override public void afterTransactions(ExecutionContext context) { incrementCounter(AFTER_TXS_COUNTER_NAME, context); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments,
ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments,
ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }### Answer:
@Test void afterTransactions(TestKit testKit) { checkCounter(testKit, AFTER_TXS_COUNTER_NAME, 1L); for (int i = 1; i <= 2; i++) { testKit.createBlock(); checkCounter(testKit, AFTER_TXS_COUNTER_NAME, 1L + i); } } |
### Question:
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkStorageKey(byte[] key) { return checkNotNull(key, "Storage key is null"); } private StoragePreconditions(); }### Answer:
@Test void checkStorageKeyAcceptsEmpty() { byte[] key = new byte[]{}; assertThat(key, sameInstance(StoragePreconditions.checkStorageKey(key))); }
@Test void checkStorageKeyAcceptsNonEmpty() { byte[] key = bytes('k'); assertThat(key, sameInstance(StoragePreconditions.checkStorageKey(key))); }
@Test void checkStorageKeyDoesNotAcceptNull() { assertThrows(NullPointerException.class, () -> StoragePreconditions.checkStorageKey(null)); }
@Test void checkStorageValueDoesNotAcceptNull() { assertThrows(NullPointerException.class, () -> StoragePreconditions.checkStorageKey(null)); } |
### Question:
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkProofKey(byte[] key) { checkNotNull(key, "Proof map key is null"); checkArgument(key.length == PROOF_MAP_KEY_SIZE, "Proof map key has invalid size (%s), must be 32 bytes", key.length); return key; } private StoragePreconditions(); }### Answer:
@Test void checkProofKeyAccepts32ByteZeroKey() { byte[] key = new byte[32]; assertThat(key, sameInstance(StoragePreconditions.checkProofKey(key))); }
@Test void checkProofKeyAccepts32ByteNonZeroKey() { byte[] key = bytes("0123456789abcdef0123456789abcdef"); assertThat(key, sameInstance(StoragePreconditions.checkProofKey(key))); }
@Test void checkProofKeyDoesNotAcceptNull() { NullPointerException thrown = assertThrows(NullPointerException.class, () -> StoragePreconditions.checkProofKey(null)); assertThat(thrown.getLocalizedMessage(), containsString("Proof map key is null")); }
@Test void checkProofKeyDoesNotAcceptSmallerKeys() { byte[] key = new byte[1]; IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> StoragePreconditions.checkProofKey(key)); assertThat(thrown.getLocalizedMessage(), containsString("Proof map key has invalid size (1)")); }
@Test void checkProofKeyDoesNotAcceptBiggerKeys() { byte[] key = new byte[64]; IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> StoragePreconditions.checkProofKey(key)); assertThat(thrown.getLocalizedMessage(), containsString("Proof map key has invalid size (64)")); } |
### Question:
StoragePreconditions { @CanIgnoreReturnValue static byte[] checkStorageValue(byte[] value) { return checkNotNull(value, "Storage value is null"); } private StoragePreconditions(); }### Answer:
@Test void checkStorageValueAcceptsEmpty() { byte[] value = new byte[]{}; assertThat(value, sameInstance(StoragePreconditions.checkStorageValue(value))); }
@Test void checkStorageValueAcceptsNonEmpty() { byte[] value = bytes('v'); assertThat(value, sameInstance(StoragePreconditions.checkStorageValue(value))); } |
### Question:
QaServiceImpl extends AbstractService implements QaService { @Override public void afterCommit(BlockCommittedEvent event) { long seed = event.getHeight(); submitIncrementCounter(seed, AFTER_COMMIT_COUNTER_NAME); } @Inject QaServiceImpl(ServiceInstanceSpec instanceSpec); @Override void initialize(ExecutionContext context, Configuration configuration); @Override void resume(ExecutionContext context, byte[] arguments); @Override void createPublicApiHandlers(Node node, Router router); @Override void beforeTransactions(ExecutionContext context); @Override void afterTransactions(ExecutionContext context); @Override void afterCommit(BlockCommittedEvent event); @Override HashCode submitIncrementCounter(long requestSeed, String counterName); @Override HashCode submitUnknownTx(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<Counter> getValue(String counterName); @Override Config getConsensusConfiguration(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Optional<ZonedDateTime> getTime(); @Override @SuppressWarnings("ConstantConditions") // Node is not null. Map<PublicKey, ZonedDateTime> getValidatorsTimes(); @Override void verifyConfiguration(ExecutionContext context, Configuration configuration); @Override void applyConfiguration(ExecutionContext context, Configuration configuration); @Override @Transaction(CREATE_COUNTER_TX_ID) void createCounter(TxMessageProtos.CreateCounterTxBody arguments,
ExecutionContext context); @Override @Transaction(INCREMENT_COUNTER_TX_ID) void incrementCounter(TxMessageProtos.IncrementCounterTxBody arguments,
ExecutionContext context); @Override @Transaction(VALID_THROWING_TX_ID) void throwing(TxMessageProtos.ThrowingTxBody arguments, ExecutionContext context); @Override @Transaction(VALID_ERROR_TX_ID) void error(TxMessageProtos.ErrorTxBody arguments, ExecutionContext context); }### Answer:
@Test void afterCommit(TestKit testKit) { testKit.createBlock(); checkAfterCommitCounter(testKit, 1L); testKit.createBlock(); checkAfterCommitCounter(testKit, 2L); } |
### Question:
ExplorerApiHelper { static TransactionResponse parseGetTxResponse(String json) { GetTxResponse response = JSON.fromJson(json, GetTxResponse.class); ExecutionStatus executionResult = getExecutionStatus(response.getStatus()); return new TransactionResponse( response.getType(), response.getMessage(), executionResult, response.getLocation() ); } private ExplorerApiHelper(); }### Answer:
@Test void parseGetTxResponseInPool() { String json = "{\n" + " 'type': 'in-pool',\n" + " 'message': '" + toHex(TRANSACTION_MESSAGE) + "'\n" + "}"; TransactionResponse transactionResponse = ExplorerApiHelper.parseGetTxResponse(json); assertThat(transactionResponse.getStatus(), is(TransactionStatus.IN_POOL)); assertThat(transactionResponse.getMessage(), is(TRANSACTION_MESSAGE)); assertThrows(IllegalStateException.class, transactionResponse::getExecutionResult); assertThrows(IllegalStateException.class, transactionResponse::getLocation); } |
### Question:
StoragePreconditions { static <E> void checkNoNulls(Collection<E> collection) { checkNotNull(collection, "Collection is null"); if (collection.contains(null)) { throw new NullPointerException("Collection contains nulls"); } } private StoragePreconditions(); }### Answer:
@Test void checkNoNulls() { assertThrows(NullPointerException.class, () -> { Collection<String> c = Arrays.asList("hello", null); StoragePreconditions.checkNoNulls(c); }); } |
### Question:
StoragePreconditions { @CanIgnoreReturnValue static long checkPositionIndex(long index, long size) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size)); } return index; } private StoragePreconditions(); }### Answer:
@Test void checkPositionIndexSize0_Valid() { long index = 0; long size = 0; assertThat(StoragePreconditions.checkPositionIndex(index, size), equalTo(index)); }
@Test void checkPositionIndexSize0_NotValid() { long index = 1; long size = 0; IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> StoragePreconditions.checkPositionIndex(index, size)); assertThat(thrown.getLocalizedMessage(), containsString("index (1) is greater than size (0)")); }
@Test void checkPositionIndexSize0_NotValidNegative() { long index = -1; long size = 0; IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> StoragePreconditions.checkPositionIndex(index, size)); assertThat(thrown.getLocalizedMessage(), containsString("index (-1) is negative")); }
@Test void checkPositionIndexSize3_AllValid() { long size = 3; long[] validIndices = {0, 1, 2, 3}; for (long index : validIndices) { assertThat(StoragePreconditions.checkPositionIndex(index, size), equalTo(index)); } }
@Test void checkPositionIndexSize3_NotValid() { long index = 4; long size = 3; IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> StoragePreconditions.checkPositionIndex(index, size)); assertThat(thrown.getLocalizedMessage(), containsString("index (4) is greater than size (3)")); }
@Test void checkPositionIndex_NegativeSize() { long index = 0; long size = -1; IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> StoragePreconditions.checkPositionIndex(index, size)); assertThat(thrown.getLocalizedMessage(), containsString("size (-1) is negative")); } |
### Question:
CryptoUtils { static boolean hasLength(byte[] data, int size) { return data.length == size; } private CryptoUtils(); }### Answer:
@Test void hasLength() { byte[] bytes = new byte[10]; assertTrue(CryptoUtils.hasLength(bytes, 10)); } |
### Question:
StoragePreconditions { static void checkRange(long from, long to) { if (from < 0 || from >= to) { throw new IndexOutOfBoundsException("Proof range first element index " + from + " must be in range [0, " + to + ")"); } } private StoragePreconditions(); }### Answer:
@Test void checkRangeFromNegative() { IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> checkRange(-1, 2)); assertThat(thrown.getLocalizedMessage(), containsString("Proof range first element index -1 must be in range [0, 2)")); }
@Test void checkRangeFromEqualToTo() { IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> checkRange(2, 2)); assertThat(thrown.getLocalizedMessage(), containsString("Proof range first element index 2 must be in range [0, 2)")); }
@Test void checkRangeFromGreaterThanTo() { IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> checkRange(3, 2)); assertThat(thrown.getLocalizedMessage(), containsString("Proof range first element index 3 must be in range [0, 2)")); }
@Test void checkRangeFromMaxLong() { IndexOutOfBoundsException thrown = assertThrows(IndexOutOfBoundsException.class, () -> checkRange(Long.MAX_VALUE, 2)); assertThat(thrown.getLocalizedMessage(), containsString("Proof range first element index " + Long.MAX_VALUE + " must be in range [0, 2)")); }
@Test void checkRangeFrom0MinValid() { long from = 0; long to = 3; checkRange(from, to); }
@Test void checkRangeFrom1() { long from = 1; long to = 3; checkRange(from, to); }
@Test void checkRangeFrom2MaxValid() { long from = 2; long to = 3; checkRange(from, to); } |
### Question:
CryptoUtils { static byte[] hexToByteArray(String hex) { return HEX_ENCODING.decode(hex); } private CryptoUtils(); }### Answer:
@Test void hexToByteArray() { byte[] bytes = CryptoUtils.hexToByteArray("abcd"); assertEquals(2, bytes.length); assertEquals(-85, bytes[0]); assertEquals(-51, bytes[1]); } |
### Question:
ListSpliterator implements Spliterator<ElementT> { @Override public Spliterator<ElementT> trySplit() { bindOrCheckModifications(); if (estimateSize() < MIN_SPLITTABLE_SIZE) { return null; } long mid = nextIndex + (fence - nextIndex) / 2; Spliterator<ElementT> prefix = new ListSpliterator<>(list, counter, hasCharacteristics(IMMUTABLE), nextIndex, mid, initialCounterValue); this.nextIndex = mid; return prefix; } ListSpliterator(ListIndex<ElementT> list, ModificationCounter counter, boolean immutable); private ListSpliterator(ListIndex<ElementT> list, ModificationCounter counter, boolean immutable,
long nextIndex, long fence, Integer initialCounterValue); @Override boolean tryAdvance(Consumer<? super ElementT> action); @Override Spliterator<ElementT> trySplit(); @Override long estimateSize(); @Override int characteristics(); }### Answer:
@Test void trySplit_Empty() { int[] source = new int[0]; Spliterator<Integer> spliterator = createSpliteratorOf(source); assertNull(spliterator.trySplit()); }
@Test @DisplayName("trySplit if there are less than minimal splittable size (1 element)") void trySplit_OneElement() { Spliterator<Integer> spliterator = createSpliteratorOf(new int[1]); assertNull(spliterator.trySplit()); }
@Test void spliteratorRemainsBoundToTheSourceAfterSplit() { ListIndex<Integer> list = createListMock(); when(list.size()).thenReturn(10L); ModificationCounter counter = new IncrementalModificationCounter(); Spliterator<Integer> spliterator = new ListSpliterator<>(list, counter, true); Spliterator<Integer> other = spliterator.trySplit(); counter.notifyModified(); assertHasDetectedModification(spliterator); assertHasDetectedModification(other); } |
### Question:
ListSpliterator implements Spliterator<ElementT> { @Override public long estimateSize() { bindOrCheckModifications(); return fence - nextIndex; } ListSpliterator(ListIndex<ElementT> list, ModificationCounter counter, boolean immutable); private ListSpliterator(ListIndex<ElementT> list, ModificationCounter counter, boolean immutable,
long nextIndex, long fence, Integer initialCounterValue); @Override boolean tryAdvance(Consumer<? super ElementT> action); @Override Spliterator<ElementT> trySplit(); @Override long estimateSize(); @Override int characteristics(); }### Answer:
@Test @DisplayName("spliterator uses the list size at bind time, allowing for structural modifications") void spliteratorIsLateBindingUsesProperSize() { ListIndex<Integer> list = createListMock(); long initialSize = 10; lenient().when(list.size()).thenReturn(initialSize); ModificationCounter counter = new IncrementalModificationCounter(); Spliterator<Integer> spliterator = new ListSpliterator<>(list, counter, true); long size = initialSize + 1; when(list.size()).thenReturn(size); counter.notifyModified(); assertThat(spliterator.estimateSize()).isEqualTo(size); }
@Test void estimateSizeIsZeroAfterSpliteratorIsConsumed() { ListIndex<Integer> list = createListMock(); long listSize = 5; when(list.size()).thenReturn(listSize); ModificationCounter counter = mock(ModificationCounter.class); Spliterator<Integer> spliterator = new ListSpliterator<>(list, counter, true); spliterator.forEachRemaining(NULL_CONSUMER); assertThat(spliterator.estimateSize()).isEqualTo(0); } |
### Question:
Block { public final boolean isEmpty() { return getNumTransactions() == 0; } abstract HashCode getBlockHash(); abstract int getProposerId(); abstract long getHeight(); final boolean isEmpty(); abstract int getNumTransactions(); abstract HashCode getPreviousBlockHash(); abstract HashCode getTxRootHash(); abstract HashCode getStateHash(); abstract HashCode getErrorHash(); abstract ImmutableMap<String, ByteString> getAdditionalHeaders(); @SuppressWarnings("squid:S1206") @Override int hashCode(); static TypeAdapter<Block> typeAdapter(Gson gson); static Block fromMessage(com.exonum.messages.core.Blockchain.Block blockMessage); static Block parseFrom(byte[] serializedBlock); static Builder builder(); }### Answer:
@Test void isEmpty() { Block emptyBlock = Blocks.aBlock() .numTransactions(0) .build(); assertTrue(emptyBlock.isEmpty()); } |
### Question:
ApiController { private void getWallet(RoutingContext rc) { PublicKey walletId = getRequiredParameter(rc.request(), WALLET_ID_PARAM, PublicKey::fromHexString); Optional<Wallet> wallet = service.getWallet(walletId); if (wallet.isPresent()) { rc.response() .putHeader(CONTENT_TYPE, "application/json") .end(json().toJson(wallet.get())); } else { rc.response() .setStatusCode(HTTP_NOT_FOUND) .end(); } } ApiController(CryptocurrencyService service); }### Answer:
@Test void getWallet(VertxTestContext context) { long balance = 200L; Wallet wallet = new Wallet(balance); when(service.getWallet(eq(FROM_KEY))) .thenReturn(Optional.of(wallet)); String getWalletUri = getWalletUri(FROM_KEY); get(getWalletUri) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()) .isEqualTo(HTTP_OK); String body = response.bodyAsString(); Wallet actualWallet = json() .fromJson(body, Wallet.class); assertThat(actualWallet.getBalance()).isEqualTo(wallet.getBalance()); context.completeNow(); }))); }
@Test void getNonexistentWallet(VertxTestContext context) { when(service.getWallet(FROM_KEY)) .thenReturn(Optional.empty()); String getWalletUri = getWalletUri(FROM_KEY); get(getWalletUri) .send(context.succeeding(response -> context.verify(() -> { assertThat(response.statusCode()).isEqualTo(HTTP_NOT_FOUND); context.completeNow(); }))); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.