method2testcases stringlengths 118 6.63k |
|---|
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public String getServiceCode () { return trailer != null && trailer.length() >= 3 ? trailer.substring (0, 3) : " "; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testGetServiceCode() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.parseTrack2(" trk1=\"true\""); String result = cardHolder.getServiceCode(); assertEquals(" ", result, "result"); }
@Test public void testGetServiceCode2() throws Throwable { String result = new CardHolder("testCardHolderPan", "4Cha").getServiceCode(); assertEquals(" ", result, "result"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public String getTrack1() { return track1; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testGetTrack1() throws Throwable { CardHolder cardHolder = new CardHolder("testCardHolderPan", "4Cha"); cardHolder.setTrack1("testCardHolderTrack1"); String result = cardHolder.getTrack1(); assertEquals("testCardHolderTrack1", result, "result"); }
@Test public void testGetTrack11() throws Throwable { String result = new CardHolder("testCardHolderPan", "4Cha").getTrack1(); assertNull(result, "result"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public String getTrack2() { if (hasTrack2()) return pan + TRACK2_SEPARATOR + exp + trailer; else return null; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testGetTrack2() throws Throwable { String result = new CardHolder().getTrack2(); assertNull(result, "result"); }
@Test public void testGetTrack21() throws Throwable { String result = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,").getTrack2(); assertEquals("k'X9|=H:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,", result, "result"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public String getTrailer() { return trailer; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testGetTrailer() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.setTrailer("testCardHolderTrailler"); String result = cardHolder.getTrailer(); assertEquals("testCardHolderTrailler", result, "result"); }
@Test public void testGetTrailer1() throws Throwable { String result = new CardHolder().getTrailer(); assertNull(result, "result"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public boolean hasSecurityCode() { return securityCode != null; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testHasSecurityCode() throws Throwable { CardHolder cardHolder = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,"); cardHolder.setSecurityCode("testCardHolderSecurityCode"); boolean result = cardHolder.hasSecurityCode(); assertTrue(result, "result"); }
@Test public void testHasSecurityCode1() throws Throwable { boolean result = new CardHolder("testCardHolderPan", "4Cha").hasSecurityCode(); assertFalse(result, "result"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public boolean hasTrack1() { return track1!=null; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testHasTrack1() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.setTrack1("testCardHolderTrack1"); boolean result = cardHolder.hasTrack1(); assertTrue(result, "result"); }
@Test public void testHasTrack11() throws Throwable { boolean result = new CardHolder("testCardHolderPan", "4Cha").hasTrack1(); assertFalse(result, "result"); } |
### Question:
SpaceLet extends QBeanSupport implements Space { public void startService() { NameRegistrar.register (uri, this); Iterator iter = getPersist().getChildren("run").iterator(); while (iter.hasNext ()) launch ((Element) iter.next ()); } void initService(); void startService(); void stopService(); void out(Object key, Object value); void out(Object key, Object value, long timeout); void push(Object key, Object value); void push(Object key, Object value, long timeout); void put(Object key, Object value); void put(Object key, Object value, long timeout); Object in(Object key); Object rd(Object key); Object in(Object key, long timeout); Object rd(Object key, long timeout); Object inp(Object key); Object rdp(Object key); boolean existAny(Object[] keys); boolean existAny(Object[] keys, long timeout); void nrd(Object key); Object nrd(Object key, long timeout); }### Answer:
@Test public void testStartServiceThrowsNullPointerException() throws Throwable { SpaceLet spaceLet = new SpaceLet(); try { spaceLet.startService(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { } } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public boolean isExpired () { return isExpired(new Date()); } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testIsExpired() throws Throwable { boolean result = new CardHolder("testCardHolderPan", "4Cha").isExpired(); assertTrue(result, "result"); }
@Test public void testIsExpired4() throws Throwable { boolean result = new CardHolder().isExpired(); assertTrue(result, "result"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public boolean isValidCRC () { return isValidCRC(this.pan); } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testIsValidCRC() throws Throwable { boolean result = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,").isValidCRC(); assertFalse(result, "result"); }
@Test public void testIsValidCRC1() throws Throwable { boolean result = CardHolder.isValidCRC("42"); assertTrue(result, "result"); }
@Test public void testIsValidCRC2() throws Throwable { boolean result = CardHolder.isValidCRC("0"); assertTrue(result, "result"); }
@Test public void testIsValidCRC3() throws Throwable { boolean result = CardHolder.isValidCRC(""); assertTrue(result, "result"); }
@Test public void testIsValidCRC4() throws Throwable { boolean result = CardHolder.isValidCRC("1"); assertFalse(result, "result"); }
@Test public void testIsValidCRC5() throws Throwable { boolean result = CardHolder.isValidCRC("testCardHolderp"); assertFalse(result, "result"); }
@Test public void testIsValidCRC6() throws Throwable { boolean result = CardHolder.isValidCRC("41CharactersXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); assertFalse(result, "result"); }
@Test public void testIsValidCRC7() throws Throwable { boolean result = CardHolder.isValidCRC("2C"); assertFalse(result, "result"); }
@Test public void testIsValidCRCThrowsNullPointerException() throws Throwable { try { new CardHolder().isValidCRC(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"String.length()\" because \"p\" is null", ex.getMessage(), "ex.getMessage()"); } } }
@Test public void testIsValidCRCThrowsNullPointerException1() throws Throwable { try { CardHolder.isValidCRC(null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"String.length()\" because \"p\" is null", ex.getMessage(), "ex.getMessage()"); } } } |
### Question:
BSH extends QBeanSupport implements Runnable { public void initService() { bsh = new Interpreter (); BshClassManager bcm = bsh.getClassManager(); try { bcm.setClassPath(getServer().getLoader().getURLs()); } catch (UtilEvalError e) { e.printStackTrace(); } bcm.setClassLoader(getServer().getLoader()); } void initService(); void startService(); void run(); }### Answer:
@Test public void testInitServiceThrowsNullPointerException() throws Throwable { BSH bSH = new BSH(); try { bSH.initService(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"org.jpos.q2.Q2.getLoader()\" because the return value of \"org.jpos.q2.qbean.BSH.getServer()\" is null", ex.getMessage(), "ex.getMessage()"); } } } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public void parseTrack2 (String s) throws InvalidCardException { if (s == null) throw new InvalidCardException ("null track2 data"); int separatorIndex = s.replace ('D','=').indexOf(TRACK2_SEPARATOR); if (separatorIndex > 0 && s.length() > separatorIndex+4) { pan = s.substring(0, separatorIndex); exp = s.substring(separatorIndex+1, separatorIndex+1+4); trailer = s.substring(separatorIndex+1+4); } else throw new InvalidCardException ("Invalid track2 format"); } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testParseTrack2() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.parseTrack2("uD|kOAf(Ls@RaT\f4_3[l\f#mF*'7-yeK^S?qBK ~G"); assertEquals("u", cardHolder.pan, "cardHolder.pan"); assertEquals("|kOA", cardHolder.exp, "cardHolder.exp"); assertEquals("f(Ls@RaT\f4_3[l\f#mF*'7-yeK^S?qBK ~G", cardHolder.trailer, "cardHolder.trailler"); }
@Test public void testParseTrack2ThrowsInvalidCardException() throws Throwable { CardHolder cardHolder = new CardHolder("testCardHolderPan", "4Cha"); assertThrows(InvalidCardException.class, () -> cardHolder.parseTrack2("D0")); assertEquals("4Cha", cardHolder.exp, "cardHolder.exp"); assertEquals("testCardHolderPan", cardHolder.pan, "cardHolder.pan"); assertNull(cardHolder.trailer, "cardHolder.trailler"); }
@Test public void testParseTrack2ThrowsInvalidCardException1() throws Throwable { CardHolder cardHolder = new CardHolder(); assertThrows(InvalidCardException.class, () -> cardHolder.parseTrack2("testCardHolders")); assertNull(cardHolder.exp, "cardHolder.exp"); assertNull(cardHolder.pan, "cardHolder.pan"); assertNull(cardHolder.trailer, "cardHolder.trailler"); }
@Test public void testParseTrack2ThrowsInvalidCardException2() throws Throwable { CardHolder cardHolder = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,"); try { cardHolder.parseTrack2(null); fail("Expected InvalidCardException to be thrown"); } catch (InvalidCardException ex) { assertEquals("null track2 data", ex.getMessage(), "ex.getMessage()"); assertEquals("H:!;", cardHolder.exp, "cardHolder.exp"); assertEquals("k'X9|", cardHolder.pan, "cardHolder.pan"); assertEquals("uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,", cardHolder.trailer, "cardHolder.trailler"); } } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public boolean seemsManualEntry() { return trailer == null || trailer.trim().length() == 0; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSeemsManualEntry() throws Throwable { CardHolder cardHolder = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,"); cardHolder.setTrailer(""); boolean result = cardHolder.seemsManualEntry(); assertTrue(result, "result"); }
@Test public void testSeemsManualEntry2() throws Throwable { boolean result = new CardHolder().seemsManualEntry(); assertTrue(result, "result"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public void setEXP (String exp) throws InvalidCardException { if (exp.length() != 4) throw new InvalidCardException ("Invalid Exp length, must be 4"); this.exp = exp; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSetEXP() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.setEXP("9913"); assertEquals("9913", cardHolder.exp, "cardHolder.exp"); }
@Test public void testSetEXPThrowsInvalidCardException() throws Throwable { CardHolder cardHolder = new CardHolder("testCardHolderPan", "4Cha"); assertThrows(InvalidCardException.class, () -> cardHolder.setEXP("5Char")); assertEquals("4Cha", cardHolder.exp, "cardHolder.exp"); }
@Test public void testSetEXPThrowsInvalidCardException1() throws Throwable { CardHolder cardHolder = new CardHolder("testCardHolderPan", "4Cha"); assertThrows(InvalidCardException.class, () -> cardHolder.setEXP("3Ch")); assertEquals("4Cha", cardHolder.exp, "cardHolder.exp"); }
@Test public void testSetEXPThrowsNullPointerException() throws Throwable { CardHolder cardHolder = new CardHolder("testCardHolderPan", "4Cha"); try { cardHolder.setEXP(null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"String.length()\" because \"exp\" is null", ex.getMessage(), "ex.getMessage()"); } assertEquals("4Cha", cardHolder.exp, "cardHolder.exp"); } } |
### Question:
BSH extends QBeanSupport implements Runnable { public void run () { Element config = getPersist(); try { bsh.set ("qbean", this); bsh.set ("log", getLog()); bsh.set ("cfg", getConfiguration()); bsh.eval (config.getText()); String source = config.getAttributeValue ("source"); if (source != null) bsh.source (source); } catch (Throwable e) { getLog().warn (e); } } void initService(); void startService(); void run(); }### Answer:
@Test public void testRun() throws Throwable { BSH bSH = new BSH(); bSH.run(); assertNull(bSH.bsh, "bSH.bsh"); assertFalse(bSH.isModified(), "bSH.isModified()"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public void setPAN (String pan) throws InvalidCardException { if (pan.length() < MINPANLEN) throw new InvalidCardException ("PAN length smaller than min required"); this.pan = pan; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSetPAN() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.setPAN("10Characte"); assertEquals("10Characte", cardHolder.pan, "cardHolder.pan"); }
@Test public void testSetPAN1() throws Throwable { CardHolder cardHolder = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,"); cardHolder.setPAN("11Character"); assertEquals("11Character", cardHolder.pan, "cardHolder.pan"); }
@Test public void testSetPANThrowsInvalidCardException() throws Throwable { CardHolder cardHolder = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,"); assertThrows(InvalidCardException.class, () -> cardHolder.setPAN("9Characte")); assertEquals("k'X9|", cardHolder.pan, "cardHolder.pan"); }
@Test public void testSetPANThrowsNullPointerException() throws Throwable { CardHolder cardHolder = new CardHolder("k'X9|DH:!;uQ<kG8!P?- ,\"Y!u`r;jB^)>3AbS9,"); try { cardHolder.setPAN(null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"String.length()\" because \"pan\" is null", ex.getMessage(), "ex.getMessage()"); } assertEquals("k'X9|", cardHolder.pan, "cardHolder.pan"); } } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public void setSecurityCode(String securityCode) { this.securityCode = securityCode; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSetSecurityCode() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.setSecurityCode("testCardHolderSecurityCode"); assertEquals("testCardHolderSecurityCode", cardHolder.securityCode, "cardHolder.securityCode"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { public void setTrack1(String track1) { this.track1 = track1; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSetTrack1() throws Throwable { CardHolder cardHolder = new CardHolder("testCardHolderPan", "4Cha"); cardHolder.setTrack1("testCardHolderTrack1"); assertEquals("testCardHolderTrack1", cardHolder.track1, "cardHolder.track1"); } |
### Question:
CardHolder implements Cloneable, Serializable, Loggeable { @SuppressWarnings("unused") public void setTrailler (String trailer) { this.trailer = trailer; } CardHolder(); CardHolder(String track2); CardHolder(String pan, String exp); CardHolder(ISOMsg m); void parseTrack2(String s); void setTrack1(String track1); String getTrack1(); boolean hasTrack1(); String getNameOnCard(); String getTrack2(); boolean hasTrack2(); void setSecurityCode(String securityCode); String getSecurityCode(); boolean hasSecurityCode(); @SuppressWarnings("unused") String getTrailler(); @SuppressWarnings("unused") void setTrailler(String trailer); String getTrailer(); void setTrailer(String trailer); void setPAN(String pan); String getPAN(); String getBIN(); void setEXP(String exp); String getEXP(); boolean isExpired(); boolean isExpired(Date currentDate); boolean isValidCRC(); static boolean isValidCRC(String p); void dump(PrintStream p, String indent); String getServiceCode(); boolean seemsManualEntry(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testSetTrailler() throws Throwable { CardHolder cardHolder = new CardHolder(); cardHolder.setTrailer("testCardHolderTrailler"); assertEquals("testCardHolderTrailler", cardHolder.trailer, "cardHolder.trailler"); } |
### Question:
BSHFilter implements RawIncomingFilter, Configurable { public ISOMsg filter (ISOChannel channel, ISOMsg m, LogEvent evt) throws VetoException { return filter (channel, m, null, null, evt); } BSHFilter(); void setConfiguration(Configuration cfg); ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt); ISOMsg filter(ISOChannel channel, ISOMsg m, byte[] header, byte[] image, LogEvent evt); }### Answer:
@Test public void testFilter() throws Throwable { Configuration cfg = new SimpleConfiguration(); BSHFilter bSHFilter = new BSHFilter(); bSHFilter.setConfiguration(cfg); ISOMsg result = bSHFilter.filter(new PADChannel(), null, new LogEvent("testBSHFilterTag", "testString")); assertNull(result, "result"); assertSame(cfg, bSHFilter.cfg, "bSHFilter.cfg"); }
@Test public void testFilterThrowsNullPointerException() throws Throwable { BSHFilter bSHFilter = new BSHFilter(); LogEvent evt = new LogEvent(); try { bSHFilter.filter(new CSChannel("testBSHFilterHost", 100, new PostPackager()), new ISOMsg("testBSHFilterMti"), evt); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"org.jpos.core.Configuration.getAll(String)\" because \"this.cfg\" is null", ex.getMessage(), "ex.getMessage()"); } assertNull(bSHFilter.cfg, "bSHFilter.cfg"); } } |
### Question:
BSH extends QBeanSupport implements Runnable { public void startService() { new Thread (this, "BSH-" + getName()).start (); } void initService(); void startService(); void run(); }### Answer:
@Test public void testStartService() throws Throwable { BSH bSH = new BSH(); bSH.startService(); assertNull(bSH.getName(), "bSH.getName()"); } |
### Question:
BSHFilter implements RawIncomingFilter, Configurable { public void setConfiguration (Configuration cfg) throws ConfigurationException { this.cfg = cfg; } BSHFilter(); void setConfiguration(Configuration cfg); ISOMsg filter(ISOChannel channel, ISOMsg m, LogEvent evt); ISOMsg filter(ISOChannel channel, ISOMsg m, byte[] header, byte[] image, LogEvent evt); }### Answer:
@Test public void testSetConfiguration() throws Throwable { BSHFilter bSHFilter = new BSHFilter(); Configuration cfg = new SimpleConfiguration(); bSHFilter.setConfiguration(cfg); assertSame(cfg, bSHFilter.cfg, "bSHFilter.cfg"); } |
### Question:
BSHRequestListener extends Log implements ISORequestListener, Configurable { public boolean process (ISOSource source, ISOMsg m) { try{ String mti = m.getMTI (); if (!whitelist.contains(mti) && !whitelist.contains("*")) mti = "unsupported"; for (String aBshSource : bshSource) { try { Interpreter bsh = new Interpreter(); bsh.set("source", source); bsh.set("message", m); bsh.set("log", this); bsh.set("cfg", cfg); int idx = aBshSource.indexOf(MTI_MACRO); String script; if (idx >= 0) { script = aBshSource.substring(0, idx) + mti + aBshSource.substring(idx + MTI_MACRO.length()); } else { script = aBshSource; } Object ret= bsh.source(script); if (ret != null && (!(ret instanceof Boolean) || (Boolean)ret)) { return true; } } catch (Exception e) { warn(e); } } }catch (Exception e){ warn(e); return false; } return false; } BSHRequestListener(); void setConfiguration(Configuration cfg); boolean process(ISOSource source, ISOMsg m); }### Answer:
@Test public void testProcess() throws Throwable { BSHRequestListener bSHRequestListener = new BSHRequestListener(); bSHRequestListener.setConfiguration(new SimpleConfiguration()); boolean result = bSHRequestListener.process(new PostChannel(), new ISOMsg("testBSHRequestListenerMti")); assertFalse(result, "result should be false"); assertEquals(1, bSHRequestListener.whitelist.size(), "bSHRequestListener.whitelist.size()"); }
@Test public void testProcess1() throws Throwable { BSHRequestListener bSHRequestListener = new BSHRequestListener(); boolean result = bSHRequestListener.process(new CSChannel(), new ISOMsg()); assertFalse(result, "result"); assertNull(bSHRequestListener.whitelist, "bSHRequestListener.whitelist"); }
@Test public void testProcess2() throws Throwable { BSHRequestListener bSHRequestListener = new BSHRequestListener(); ISOMsg m = new ISOMsg(); m.setMTI("testBSHRequestListenerMti"); boolean result = bSHRequestListener.process(new LogChannel(), m); assertFalse(result, "result"); assertNull(bSHRequestListener.whitelist, "bSHRequestListener.whitelist"); } |
### Question:
BSHRequestListener extends Log implements ISORequestListener, Configurable { public void setConfiguration (Configuration cfg) throws ConfigurationException { this.cfg = cfg; bshSource = cfg.getAll ("source"); String[] mti = cfg.get ("whitelist", "*").split(","); whitelist = new HashSet<>( Arrays.asList(mti) ); } BSHRequestListener(); void setConfiguration(Configuration cfg); boolean process(ISOSource source, ISOMsg m); }### Answer:
@Test public void testSetConfiguration() throws Throwable { BSHRequestListener bSHRequestListener = new BSHRequestListener(); Configuration cfg = new SimpleConfiguration(); bSHRequestListener.setConfiguration(cfg); assertEquals(1, bSHRequestListener.whitelist.size(), "bSHRequestListener.whitelist.size()"); assertEquals(0, bSHRequestListener.bshSource.length, "bSHRequestListener.bshSource.length"); assertSame(cfg, bSHRequestListener.cfg, "bSHRequestListener.cfg"); }
@Test public void testSetConfigurationThrowsNullPointerException() throws Throwable { BSHRequestListener bSHRequestListener = new BSHRequestListener(); Configuration cfg = new SubConfiguration(); try { bSHRequestListener.setConfiguration(cfg); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertSame(cfg, bSHRequestListener.cfg, "bSHRequestListener.cfg"); if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"org.jpos.core.Configuration.getAll(String)\" because \"this.cfg\" is null", ex.getMessage(), "ex.getMessage()"); } assertNull(bSHRequestListener.whitelist, "bSHRequestListener.whitelist"); assertNull(bSHRequestListener.bshSource, "bSHRequestListener.bshSource"); } } |
### Question:
BSHLogListener implements org.jpos.util.LogListener, org.jpos.core.Configurable { protected void addScriptInfo(String filename, String code, long lastModified){ Objects.requireNonNull(filename, "The script file name cannot be null"); scripts.put(filename, new ScriptInfo(code, lastModified)); } BSHLogListener(); @Override void setConfiguration(org.jpos.core.Configuration cfg); @Override LogEvent log(LogEvent ev); }### Answer:
@Test public void testAddScriptInfo() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); bSHLogListener.addScriptInfo("testBSHLogListenerFilename", "testBSHLogListenerCode", 100L); assertEquals(1, bSHLogListener.scripts.size(), "bSHLogListener.scripts.size()"); }
@Test public void testAddScriptInfoThrowsNullPointerException() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); try { bSHLogListener.addScriptInfo(null, "testBSHLogListenerCode", 100L); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertEquals("The script file name cannot be null", ex.getMessage()); assertEquals(0, bSHLogListener.scripts.size()); } } |
### Question:
BSHLogListener implements org.jpos.util.LogListener, org.jpos.core.Configurable { protected ScriptInfo getScriptInfo(String filename){ Objects.requireNonNull(filename, "The script file name cannot be null"); return scripts.get(filename); } BSHLogListener(); @Override void setConfiguration(org.jpos.core.Configuration cfg); @Override LogEvent log(LogEvent ev); }### Answer:
@Test public void testGetScriptInfo() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); BSHLogListener.ScriptInfo result = bSHLogListener.getScriptInfo("testBSHLogListenerFilename"); assertNull(result, "result"); assertEquals(0, bSHLogListener.scripts.size(), "bSHLogListener.scripts.size()"); }
@Test public void testGetScriptInfoThrowsNullPointerException() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); try { bSHLogListener.getScriptInfo(null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { assertEquals("The script file name cannot be null", ex.getMessage()); assertEquals(0, bSHLogListener.scripts.size()); } } |
### Question:
Shutdown extends QBeanSupport { public void startService() { getServer().shutdown (); } void startService(); }### Answer:
@Test public void testStartService() throws Throwable { Shutdown shutdown = new Shutdown(); String[] args = new String[2]; args[0] = ""; args[1] = "testString"; shutdown.setServer(server); shutdown.startService(); assertSame(server, shutdown.getServer(), "shutdown.getServer()"); }
@Test public void testStartServiceThrowsNullPointerException() throws Throwable { try { new Shutdown().startService(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"org.jpos.q2.Q2.shutdown()\" because the return value of \"org.jpos.q2.qbean.Shutdown.getServer()\" is null", ex.getMessage(), "ex.getMessage()"); } } } |
### Question:
BSHLogListener implements org.jpos.util.LogListener, org.jpos.core.Configurable { protected String loadCode(File f) throws IOException{ StringBuilder buf = new StringBuilder((int)f.length()); char[] content = new char[(int)f.length()]; int l; Reader r = new BufferedReader(new FileReader(f)); try { while((l=r.read(content))!=-1) buf.append(content,0,l); } finally { r.close(); } return buf.toString(); } BSHLogListener(); @Override void setConfiguration(org.jpos.core.Configuration cfg); @Override LogEvent log(LogEvent ev); }### Answer:
@Test public void testLoadCodeThrowsFileNotFoundException() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); File f = new File("testBSHLogListenerParam1"); try { bSHLogListener.loadCode(f); fail("Expected FileNotFoundException to be thrown"); } catch (FileNotFoundException ex) { assertEquals(FileNotFoundException.class, ex.getClass(), "ex.getClass()"); assertEquals("testBSHLogListenerParam1", f.getName(), "f.getName()"); } }
@Test public void testLoadCodeThrowsNullPointerException() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); try { bSHLogListener.loadCode(null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { } } |
### Question:
BSHLogListener implements org.jpos.util.LogListener, org.jpos.core.Configurable { @Override public LogEvent log(LogEvent ev) { LogEvent ret = ev; boolean processed = false; try{ String[] sources = replace(cfg.getAll("source"), patterns, new String[] {ev.getTag(), ev.getRealm()}); for(int i=0; i<sources.length && ret != null; i++){ try{ Interpreter bsh = new Interpreter(); BSHLogListener.ScriptInfo info = getScriptInfo(sources[i]); NameSpace ns = info!=null ?info.getNameSpace():null; if(ns!=null) bsh.setNameSpace(ns); bsh.set("event", ret); bsh.set("cfg", cfg); File f = new File(sources[i]); if(!cfg.getBoolean("preload-scripts")){ if(f.exists() && f.canRead() && f.isFile()){ processed = true; bsh.eval(new java.io.FileReader(f)); } }else{ if(info == null) scripts.put(sources[i], info=new ScriptInfo()); if(System.currentTimeMillis() > info.getLastCheck() + cfg.getLong("reload")){ info.setLastCheck(System.currentTimeMillis()); if(f.exists() && f.canRead() && f.isFile()){ if(info.getLastModified() != f.lastModified()) { info.setLastModified(f.lastModified()); info.setCode(loadCode(f)); } }else{ info.setCode(null); } } if(info.getCode() != null){ processed = true; bsh.eval(new StringReader(info.getCode())); }else scripts.remove(sources[i]); } ret = (LogEvent)bsh.get("event"); Object saveNS = bsh.get("saveNameSpace"); boolean saveNameSpace = saveNS instanceof Boolean ? (Boolean) saveNS :cfg.getBoolean("save-name-space"); if(saveNameSpace) { if(info!=null) info.setNameSpace(bsh.getNameSpace()); else scripts.put(sources[i], new ScriptInfo(bsh.getNameSpace())); }else if (info!=null) info.setNameSpace(null); }catch(Exception e){ ret.addMessage(e); } } return !processed && cfg.getBoolean("filter-by-default") ? null : ret; }catch(Exception e){ if (ret != null) { ret.addMessage(e); } return ret; } } BSHLogListener(); @Override void setConfiguration(org.jpos.core.Configuration cfg); @Override LogEvent log(LogEvent ev); }### Answer:
@Test public void testLog() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); Configuration cfg = new SimpleConfiguration(new Properties()); bSHLogListener.setConfiguration(cfg); LogEvent ev = new LogEvent("testBSHLogListenerTag"); ev.setSource(new LogChannel()); LogEvent result = bSHLogListener.log(ev); assertSame(ev, result, "result"); assertSame(cfg, bSHLogListener.cfg, "bSHLogListener.cfg"); } |
### Question:
SpaceAdaptor extends QBeanSupport implements SpaceAdaptorMBean { public Set getKeys () { if (sp instanceof LocalSpace) return ((LocalSpace)sp).getKeySet (); return null; } SpaceAdaptor(); synchronized void setSpaceName(String spaceName); String getSpaceName(); Set getKeys(); }### Answer:
@SuppressWarnings("unchecked") @Test public void testGetKeys() throws Throwable { Set result = new SpaceAdaptor().getKeys(); assertNull(result, "result"); } |
### Question:
BSHLogListener implements org.jpos.util.LogListener, org.jpos.core.Configurable { @Override public void setConfiguration(org.jpos.core.Configuration cfg) { this.cfg = cfg; } BSHLogListener(); @Override void setConfiguration(org.jpos.core.Configuration cfg); @Override LogEvent log(LogEvent ev); }### Answer:
@Test public void testSetConfiguration() throws Throwable { BSHLogListener bSHLogListener = new BSHLogListener(); Configuration cfg = new SimpleConfiguration(new Properties()); bSHLogListener.setConfiguration(cfg); assertSame(cfg, bSHLogListener.cfg, "bSHLogListener.cfg"); } |
### Question:
BSHAction implements ActionListener, UIAware { public void actionPerformed (ActionEvent ev) { String bshSource = ev.getActionCommand(); try { Interpreter bsh = new Interpreter (); bsh.source (bshSource); } catch (Exception e) { e.printStackTrace(); } } BSHAction(); void setUI(UI ui, Element e); void actionPerformed(ActionEvent ev); public UI ui; }### Answer:
@Disabled("test fails - needs a real action file") @Test public void testActionPerformed() throws Throwable { new BSHAction().actionPerformed(new ActionEvent("testString", 100, "testBSHActionParam3", 100L, 1000)); assertTrue(true, "Test completed without Exception"); }
@Test public void testActionPerformedThrowsNullPointerException() throws Throwable { try { new BSHAction().actionPerformed(null); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"java.awt.event.ActionEvent.getActionCommand()\" because \"ev\" is null", ex.getMessage(), "ex.getMessage()"); } } } |
### Question:
IFB_AMOUNT extends ISOFieldPackager { public byte[] pack (ISOComponent c) throws ISOException { String s = (String) c.getValue(); String amount = ISOUtil.zeropad(s.substring(1), getLength()-1); byte[] b = new byte[1 + (getLength() >> 1)]; b[0] = (byte) s.charAt(0); interpreter.interpret(amount, b, 1); return b; } IFB_AMOUNT(); IFB_AMOUNT(int len, String description, boolean pad); void setPad(boolean pad); byte[] pack(ISOComponent c); int unpack(ISOComponent c, byte[] b, int offset); int getMaxPackedLength(); }### Answer:
@Test public void testPack() throws Exception { ISOField field = new ISOField(12, "D123"); IFB_AMOUNT packager = new IFB_AMOUNT(6, "Should be D00123", true); TestUtils.assertEquals(new byte[]{68, 0x00, 0x01, 0x23}, packager.pack(field)); }
@Test public void testPackOddDigits() throws Exception { ISOField field = new ISOField(12, "D123"); IFB_AMOUNT packager = new IFB_AMOUNT(5, "Should be D0123", true); TestUtils.assertEquals(new byte[]{68, 0x01, 0x23}, packager.pack(field)); } |
### Question:
IFB_AMOUNT extends ISOFieldPackager { public int unpack (ISOComponent c, byte[] b, int offset) throws ISOException { String d = new String(b, offset, 1) + interpreter.uninterpret(b, offset + 1, getLength() - 1); c.setValue(d); return 1 + (getLength() >> 1); } IFB_AMOUNT(); IFB_AMOUNT(int len, String description, boolean pad); void setPad(boolean pad); byte[] pack(ISOComponent c); int unpack(ISOComponent c, byte[] b, int offset); int getMaxPackedLength(); }### Answer:
@Test public void testUnpack() throws Exception { byte[] raw = new byte[]{68, 0x00, 0x01, 0x23}; IFB_AMOUNT packager = new IFB_AMOUNT(6, "Should be D00123", true); ISOField field = new ISOField(12); packager.unpack(field, raw, 0); assertEquals("D00123", (String) field.getValue()); } |
### Question:
EbcdicBinaryInterpreter implements BinaryInterpreter { public void interpret(byte[] data, byte[] b, int offset) { ISOUtil.asciiToEbcdic(data, b, offset); } void interpret(byte[] data, byte[] b, int offset); byte[] uninterpret(byte[] rawData, int offset, int length); int getPackedLength(int nDataUnits); static final EbcdicBinaryInterpreter INSTANCE; }### Answer:
@Test public void interpret() { byte[] result = new byte[binaryData.length]; interpreter.interpret(binaryData, result, 0); assertThat(result, is(EBCDICDATA)); } |
### Question:
EbcdicBinaryInterpreter implements BinaryInterpreter { public byte[] uninterpret(byte[] rawData, int offset, int length) { return ISOUtil.ebcdicToAsciiBytes(rawData, offset, length); } void interpret(byte[] data, byte[] b, int offset); byte[] uninterpret(byte[] rawData, int offset, int length); int getPackedLength(int nDataUnits); static final EbcdicBinaryInterpreter INSTANCE; }### Answer:
@Test public void uninterpret() { int offset = 0; int length = EBCDICDATA.length; byte[] result = interpreter.uninterpret(EBCDICDATA, offset, length); assertThat(result, is(binaryData)); } |
### Question:
SpaceAdaptor extends QBeanSupport implements SpaceAdaptorMBean { protected void stopService () throws Exception { getServer().getMBeanServer().unregisterMBean (objectName); } SpaceAdaptor(); synchronized void setSpaceName(String spaceName); String getSpaceName(); Set getKeys(); }### Answer:
@Test public void testStopServiceThrowsNullPointerException() throws Throwable { SpaceAdaptor spaceAdaptor = new SpaceAdaptor(); try { spaceAdaptor.stopService(); fail("Expected NullPointerException to be thrown"); } catch (NullPointerException ex) { if (isJavaVersionAtMost(JAVA_14)) { assertNull(ex.getMessage(), "ex.getMessage()"); } else { assertEquals("Cannot invoke \"org.jpos.q2.Q2.getMBeanServer()\" because the return value of \"org.jpos.q2.qbean.SpaceAdaptor.getServer()\" is null", ex.getMessage(), "ex.getMessage()"); } } } |
### Question:
ArchiveWorkItemHandler extends AbstractLogOrThrowWorkItemHandler { public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { String archive = (String) workItem.getParameter("Archive"); List<File> files = (List<File>) workItem.getParameter("Files"); try { RequiredParameterValidator.validate(this.getClass(), workItem); OutputStream outputStream = new FileOutputStream(new File(archive)); ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", outputStream); if (files != null) { for (File file : files) { final TarArchiveEntry entry = new TarArchiveEntry("testdata/test1.xml"); entry.setModTime(0); entry.setSize(file.length()); entry.setUserId(0); entry.setGroupId(0); entry.setMode(0100000); os.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file), os); } } os.closeArchiveEntry(); os.close(); manager.completeWorkItem(workItem.getId(), null); } catch (Exception e) { handleException(e); manager.abortWorkItem(workItem.getId()); } } void executeWorkItem(WorkItem workItem,
WorkItemManager manager); void abortWorkItem(WorkItem workItem,
WorkItemManager manager); }### Answer:
@Test public void testNoFilesSpecified() { TestWorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter("Archive", "testfile.txt"); workItem.setParameter("Files", new ArrayList<File>()); ArchiveWorkItemHandler archiveWorkItemHandler = new ArchiveWorkItemHandler(); archiveWorkItemHandler.setLogThrownException(true); archiveWorkItemHandler.executeWorkItem(workItem, manager); assertEquals(1, manager.getAbortedWorkItems().size()); assertTrue(manager.getAbortedWorkItems().contains(workItem.getId())); }
@Test public void testWithTempFile() throws Exception { TestWorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); workItem.setId(123L); File tempFile = tempFolder.newFile("tempFile1.txt"); FileUtils.writeStringToFile(tempFile, "temp file content", "UTF-8"); File tempFileTwo = tempFolder.newFile("tempFile2.txt"); FileUtils.writeStringToFile(tempFileTwo, "temp file2 content", "UTF-8"); List<java.io.File> filesList = new ArrayList<>(); filesList.add(tempFile); filesList.add(tempFileTwo); workItem.setParameter("Archive", "testfile.txt"); workItem.setParameter("Files", filesList); ArchiveWorkItemHandler archiveWorkItemHandler = new ArchiveWorkItemHandler(); archiveWorkItemHandler.setLogThrownException(true); archiveWorkItemHandler.executeWorkItem(workItem, manager); assertNotNull(manager.getResults()); assertEquals(1, manager.getResults().size()); assertTrue(manager.getResults().containsKey(workItem.getId())); }
@Test public void testNoArchiveSpecified() throws Exception { TestWorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); workItem.setParameter("Files", new ArrayList<File>()); ArchiveWorkItemHandler archiveWorkItemHandler = new ArchiveWorkItemHandler(); archiveWorkItemHandler.setLogThrownException(true); archiveWorkItemHandler.executeWorkItem(workItem, manager); assertEquals(1, manager.getAbortedWorkItems().size()); assertTrue(manager.getAbortedWorkItems().contains(workItem.getId())); } |
### Question:
KafkaWorkItemHandler extends AbstractLogOrThrowWorkItemHandler implements Cacheable { @Override public void close() { if (producer != null) { producer.flush(); producer.close(); } } KafkaWorkItemHandler(Producer producer); KafkaWorkItemHandler(String bootstrapServers,
String clientId,
String keySerializerClass,
String valueSerializerClass,
ClassLoader classLoader); KafkaWorkItemHandler(String bootstrapServers,
String clientId,
String keySerializerClass,
String valueSerializerClass); void executeWorkItem(WorkItem workItem,
WorkItemManager manager); void abortWorkItem(WorkItem workItem,
WorkItemManager manager); @Override void close(); }### Answer:
@Test public void testExceptionHandlingWhenClosed() throws Exception{ buildKafkaWIH(true); mockProducerString.close(); assertExceptionAfterExecuteWorkItem(workItem); } |
### Question:
ExecWorkItemHandler extends AbstractLogOrThrowWorkItemHandler { public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { try { RequiredParameterValidator.validate(this.getClass(), workItem); String command = (String) workItem.getParameter("Command"); List<String> arguments = (List<String>) workItem.getParameter("Arguments"); Map<String, Object> results = new HashMap<>(); CommandLine commandLine = CommandLine.parse(command); if (arguments != null && arguments.size() > 0) { commandLine.addArguments(arguments.toArray(new String[0]), true); } parsedCommandStr = commandLine.toString(); DefaultExecutor executor = new DefaultExecutor(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); executor.setStreamHandler(streamHandler); executor.execute(commandLine); results.put(RESULT, outputStream.toString()); outputStream.close(); manager.completeWorkItem(workItem.getId(), results); } catch (Throwable t) { handleException(t); } } void executeWorkItem(WorkItem workItem,
WorkItemManager manager); void abortWorkItem(WorkItem workItem,
WorkItemManager manager); String getParsedCommandStr(); static final String RESULT; }### Answer:
@Test public void testExecCommandInvalidParam() throws Exception { TestWorkItemManager manager = new TestWorkItemManager(); WorkItemImpl workItem = new WorkItemImpl(); ExecWorkItemHandler handler = new ExecWorkItemHandler(); handler.setLogThrownException(true); handler.executeWorkItem(workItem, manager); assertNotNull(manager.getResults()); assertEquals(0, manager.getResults().size()); } |
### Question:
JPAWorkItemHandler extends AbstractLogOrThrowWorkItemHandler implements Cacheable { public void close() { emf.close(); } JPAWorkItemHandler(String persistenceUnit); JPAWorkItemHandler(String persistenceUnit,
ClassLoader classloader); void executeWorkItem(WorkItem wi,
WorkItemManager wim); void close(); void abortWorkItem(WorkItem wi,
WorkItemManager wim); static final String P_RESULT; static final String P_TYPE; static final String P_ID; static final String P_ENTITY; static final String P_ACTION; static final String P_QUERY; static final String P_QUERY_PARAMS; static final String P_QUERY_RESULTS; static final String CREATE_ACTION; static final String UPDATE_ACTION; static final String GET_ACTION; static final String DELETE_ACTION; static final String QUERY_ACTION; }### Answer:
@Test public void createOnProcessTest() throws Exception { String DESC = "Table"; Product p = new Product(DESC, 10f); startJPAWIHProcess(JPAWorkItemHandler.CREATE_ACTION, p); UserTransaction ut = getUserTransaction(); ut.begin(); EntityManager em = emf.createEntityManager(); TypedQuery<Product> products = em.createQuery("select p from Product p where p.description = :desc", Product.class); products.setParameter("desc", DESC); List<Product> resultList = products.getResultList(); Product result = resultList.iterator().next(); assertEquals(DESC, result.getDescription()); em.remove(result); em.flush(); em.close(); ut.commit(); }
@Test public void removeOnProcessTest() throws Exception { Product p = new Product("A Product", 10f); ut.begin(); EntityManager em = emf.createEntityManager(); em.persist(p); long id = p.getId(); em.close(); ut.commit(); startJPAWIHProcess(JPAWorkItemHandler.DELETE_ACTION, p); ut.begin(); em = emf.createEntityManager(); p = em.find(Product.class, id); assertNull(p); ut.commit(); }
@Test public void updateOnProcessTest() throws Exception { String DESC = "Table"; String NEW_DESC = "Red Table"; Product p = new Product(DESC, 10f); ut.begin(); EntityManager em = emf.createEntityManager(); em.persist(p); long id = p.getId(); em.close(); ut.commit(); p.setDescription(NEW_DESC); startJPAWIHProcess(JPAWorkItemHandler.UPDATE_ACTION, p); ut.begin(); em = emf.createEntityManager(); p = em.find(Product.class, id); assertEquals(p.getDescription(), NEW_DESC); ut.commit(); removeProduct(p); } |
### Question:
DiffInfo { public static DiffInfo fromFile(String path) { try { return new DiffInfo(Files.newBufferedReader(Paths.get(path))); } catch (IOException exc) { throw new RuntimeException("Could not open file: " + path, exc); } } DiffInfo(BufferedReader reader); boolean contains(String path); static DiffInfo fromFile(String path); }### Answer:
@Test void testFromFileWithANotExistingFile() { assertThrows(RuntimeException.class, () -> { DiffInfo.fromFile("notExistingPath"); }); } |
### Question:
DiffMutationFilterFactory implements MutationInterceptorFactory { @Override public MutationInterceptor createInterceptor(InterceptorParameters params) { Optional<String> path = params.getString(fileParameter); return new DiffMutationFilter(DiffInfo.fromFile(path.orElse(defaultPath))); } @Override MutationInterceptor createInterceptor(InterceptorParameters params); @Override Feature provides(); @Override String description(); }### Answer:
@Test void testInterceptorType() { DiffMutationFilterFactory diffMutationFilterFactory = new DiffMutationFilterFactory(); MutationInterceptor diffMutationFilter = diffMutationFilterFactory .createInterceptor(makeFor("file", "LICENSE")); assertEquals(InterceptorType.FILTER, diffMutationFilter.type()); } |
### Question:
TextAttributeConverter implements AttributeConverter<String, String> { @Override public String convertToEntityAttribute(String text) { return text; } @Override String convertToDatabaseColumn(String text); @Override String convertToEntityAttribute(String text); }### Answer:
@Test void testConvertToEntityAttribute() { Assertions.assertEquals("test", textAttributeConverter.convertToEntityAttribute("test")); } |
### Question:
HooksPhaseGetter { public List<HookPhase> getHookPhasesBeforeStop(SyncFlowableStep syncFlowableStep, ProcessContext context) { if (syncFlowableStep instanceof BeforeStepHookPhaseProvider) { return ((BeforeStepHookPhaseProvider) syncFlowableStep).getHookPhasesBeforeStep(context); } return Collections.singletonList(HookPhase.NONE); } List<HookPhase> getHookPhasesBeforeStop(SyncFlowableStep syncFlowableStep, ProcessContext context); List<HookPhase> getHookPhasesAfterStop(SyncFlowableStep syncFlowableStep, ProcessContext context); }### Answer:
@Test void testGetHookPhasesBeforeStop() { List<HookPhase> hookPhases = List.of(HookPhase.BEFORE_STOP); StopAppStep beforeStepHookPhaseProvider = Mockito.mock(StopAppStep.class); Mockito.when(beforeStepHookPhaseProvider.getHookPhasesBeforeStep(context)) .thenReturn(hookPhases); List<HookPhase> hookPhasesBeforeStop = hooksPhaseGetter.getHookPhasesBeforeStop(beforeStepHookPhaseProvider, context); Assertions.assertEquals(1, hookPhasesBeforeStop.size()); Assertions.assertEquals(hookPhases, hookPhasesBeforeStop); }
@Test void testGetHookPhasesBeforeStopNonHooksClass() { SyncFlowableStep syncFlowableStep = Mockito.mock(SyncFlowableStep.class); List<HookPhase> hookPhasesBeforeStop = hooksPhaseGetter.getHookPhasesBeforeStop(syncFlowableStep, context); Assertions.assertEquals(1, hookPhasesBeforeStop.size()); Assertions.assertEquals(HookPhase.NONE, hookPhasesBeforeStop.get(0)); } |
### Question:
HooksPhaseGetter { public List<HookPhase> getHookPhasesAfterStop(SyncFlowableStep syncFlowableStep, ProcessContext context) { if (syncFlowableStep instanceof AfterStepHookPhaseProvider) { return ((AfterStepHookPhaseProvider) syncFlowableStep).getHookPhasesAfterStep(context); } return Collections.singletonList(HookPhase.NONE); } List<HookPhase> getHookPhasesBeforeStop(SyncFlowableStep syncFlowableStep, ProcessContext context); List<HookPhase> getHookPhasesAfterStop(SyncFlowableStep syncFlowableStep, ProcessContext context); }### Answer:
@Test void testGetHookPhasesAfterStop() { List<HookPhase> hookPhases = List.of(HookPhase.AFTER_STOP); StopAppStep afterStepHookPhaseProvider = Mockito.mock(StopAppStep.class); Mockito.when(afterStepHookPhaseProvider.getHookPhasesAfterStep(context)) .thenReturn(hookPhases); List<HookPhase> hookPhasesBeforeStop = hooksPhaseGetter.getHookPhasesAfterStop(afterStepHookPhaseProvider, context); Assertions.assertEquals(1, hookPhasesBeforeStop.size()); Assertions.assertEquals(hookPhases, hookPhasesBeforeStop); }
@Test void testGetHookPhasesAfterStopNonHooksClass() { SyncFlowableStep syncFlowableStep = Mockito.mock(SyncFlowableStep.class); List<HookPhase> hookPhasesAfterStop = hooksPhaseGetter.getHookPhasesAfterStop(syncFlowableStep, context); Assertions.assertEquals(1, hookPhasesAfterStop.size()); Assertions.assertEquals(HookPhase.NONE, hookPhasesAfterStop.get(0)); } |
### Question:
EnvironmentServicesFinder { public CfService findService(String name) { if (StringUtils.isEmpty(name)) { return null; } return CollectionUtils.firstElement(env.findServicesByName(name)); } EnvironmentServicesFinder(); EnvironmentServicesFinder(CfJdbcEnv env); CfJdbcService findJdbcService(String name); CfService findService(String name); }### Answer:
@Test void testFindServiceWithNullOrEmptyServiceName() { Assertions.assertNull(environmentServicesFinder.findService(null)); Assertions.assertNull(environmentServicesFinder.findService("")); }
@Test void testFindService() { CfService expectedService = Mockito.mock(CfService.class); Mockito.when(env.findServicesByName(SERVICE_NAME)) .thenReturn(List.of(expectedService)); CfService service = environmentServicesFinder.findService(SERVICE_NAME); Assertions.assertEquals(expectedService, service); }
@Test void testFindServiceWithMultipleMatches() { CfService expectedService1 = Mockito.mock(CfService.class); CfService expectedService2 = Mockito.mock(CfService.class); Mockito.when(env.findServicesByName(SERVICE_NAME)) .thenReturn(List.of(expectedService1, expectedService2)); CfService service = environmentServicesFinder.findService(SERVICE_NAME); Assertions.assertEquals(expectedService1, service); }
@Test void testFindServiceWithZeroMatches() { Mockito.when(env.findServicesByName(SERVICE_NAME)) .thenReturn(Collections.emptyList()); CfService service = environmentServicesFinder.findService(SERVICE_NAME); Assertions.assertNull(service); } |
### Question:
HooksExecutor { public List<Hook> executeBeforeStepHooks(StepPhase currentStepPhase) { if (!hooksCalculator.isInPreExecuteStepPhase(currentStepPhase)) { return Collections.emptyList(); } return executeHooks(currentStepPhase); } HooksExecutor(HooksCalculator hooksCalculator, Module moduleToDeploy); List<Hook> executeBeforeStepHooks(StepPhase currentStepPhase); List<Hook> executeAfterStepHooks(StepPhase currentStepPhase); }### Answer:
@Test void executeBeforeStepHooksWhenPhaseIsNotBefore() { Module moduleToDeploy = createModule("test-module"); HooksExecutor hooksExecutor = new HooksExecutor(hooksCalculator, moduleToDeploy); List<Hook> hooksForExecution = hooksExecutor.executeBeforeStepHooks(StepPhase.DONE); Assertions.assertTrue(hooksForExecution.isEmpty()); }
@Test void executeBeforeStepHooks() { Module moduleToDeploy = createModule("test-module"); Mockito.when(hooksCalculator.isInPreExecuteStepPhase(StepPhase.EXECUTE)) .thenReturn(true); Mockito.when(processTypeParser.getProcessType(any())) .thenReturn(ProcessType.BLUE_GREEN_DEPLOY); List<Hook> expectedHooksForExecution = List.of(createHook("test-hook", Collections.emptyList())); Mockito.when(hooksCalculator.calculateHooksForExecution(moduleToDeploy, StepPhase.EXECUTE)) .thenReturn(expectedHooksForExecution); HooksExecutor hooksExecutor = new HooksExecutor(hooksCalculator, moduleToDeploy); List<Hook> hooksForExecution = hooksExecutor.executeBeforeStepHooks(StepPhase.EXECUTE); Assertions.assertEquals(expectedHooksForExecution, hooksForExecution); }
@Test void executeBeforeStepHooksWhenModuleToDeployIsNull() { Mockito.when(processTypeParser.getProcessType(any())) .thenReturn(ProcessType.DEPLOY); HooksExecutor hooksExecutor = new HooksExecutor(hooksCalculator, null); Mockito.when(hooksCalculator.isInPreExecuteStepPhase(StepPhase.EXECUTE)) .thenReturn(true); List<Hook> hooksForExecution = hooksExecutor.executeBeforeStepHooks(StepPhase.EXECUTE); Assertions.assertTrue(hooksForExecution.isEmpty()); } |
### Question:
HooksExecutor { public List<Hook> executeAfterStepHooks(StepPhase currentStepPhase) { if (!hooksCalculator.isInPostExecuteStepPhase(currentStepPhase)) { return Collections.emptyList(); } return executeHooks(currentStepPhase); } HooksExecutor(HooksCalculator hooksCalculator, Module moduleToDeploy); List<Hook> executeBeforeStepHooks(StepPhase currentStepPhase); List<Hook> executeAfterStepHooks(StepPhase currentStepPhase); }### Answer:
@Test void executeAfterStepHooksWhenPhaseIsNotAfter() { Module moduleToDeploy = createModule("test-module"); Mockito.when(processTypeParser.getProcessType(any())) .thenReturn(ProcessType.DEPLOY); HooksExecutor hooksExecutor = new HooksExecutor(hooksCalculator, moduleToDeploy); List<Hook> hooksForExecution = hooksExecutor.executeAfterStepHooks(StepPhase.EXECUTE); Assertions.assertTrue(hooksForExecution.isEmpty()); }
@Test void executeAfterStepHooks() { Module moduleToDeploy = createModule("test-module"); Mockito.when(hooksCalculator.isInPostExecuteStepPhase(StepPhase.DONE)) .thenReturn(true); List<Hook> expectedHooksForExecution = List.of(createHook("test-hook", Collections.emptyList())); Mockito.when(processTypeParser.getProcessType(any())) .thenReturn(ProcessType.DEPLOY); Mockito.when(hooksCalculator.calculateHooksForExecution(moduleToDeploy, StepPhase.DONE)) .thenReturn(expectedHooksForExecution); HooksExecutor hooksExecutor = new HooksExecutor(hooksCalculator, moduleToDeploy); List<Hook> hooksForExecution = hooksExecutor.executeAfterStepHooks(StepPhase.DONE); Assertions.assertEquals(expectedHooksForExecution, hooksForExecution); } |
### Question:
ProcessHelper { public Operation.State computeProcessState(String processId) { if (isInAbortedState(processId)) { return State.ABORTED; } if (isInErrorState(processId)) { return State.ERROR; } if (isInReceiveTask(processId)) { return State.ACTION_REQUIRED; } if (isInRunningState(processId)) { return State.RUNNING; } return State.FINISHED; } @Inject ProcessHelper(FlowableFacade flowableFacade, HistoricOperationEventService historicOperationEventService); Operation.State computeProcessState(String processId); List<HistoricOperationEvent> getHistoricOperationEventByProcessId(String processId); }### Answer:
@Test void testIsProcessAtReceiveTask() { Mockito.when(flowableFacade.isProcessInstanceAtReceiveTask(PROCESS_ID)) .thenReturn(true); Assertions.assertEquals(State.ACTION_REQUIRED, processHelper.computeProcessState(PROCESS_ID)); }
@Test void testIsProcessInErrorState() { Mockito.when(flowableFacade.hasDeadLetterJobs(PROCESS_ID)) .thenReturn(true); Assertions.assertEquals(State.ERROR, processHelper.computeProcessState(PROCESS_ID)); }
@Test void testIsProcessAbortedWhenThereIsAbortedProcess() { Mockito.when(historicOperationEventQuery.list()) .thenReturn(List.of(ImmutableHistoricOperationEvent.builder() .type(HistoricOperationEvent.EventType.ABORTED) .processId(PROCESS_ID) .build())); Assertions.assertEquals(State.ABORTED, processHelper.computeProcessState(PROCESS_ID)); }
@Test void testIsProcessAbortedWhenThereIsNotAbortedProcess() { mockHistoricEventsWithTypes(HistoricOperationEvent.EventType.FINISHED); Assertions.assertEquals(State.FINISHED, processHelper.computeProcessState(PROCESS_ID)); } |
### Question:
JdbcUtil { public static void closeQuietly(ResultSet resultSet) { if (resultSet == null) { return; } try { resultSet.close(); } catch (SQLException e) { logSQLException(e); LOGGER.warn(Messages.COULD_NOT_CLOSE_RESULT_SET, e); } catch (Exception e) { LOGGER.warn(Messages.COULD_NOT_CLOSE_RESULT_SET, e); } } private JdbcUtil(); static void closeQuietly(ResultSet resultSet); static void closeQuietly(Statement statement); static void closeQuietly(Connection connection); static void logSQLException(SQLException exception); static void commit(Connection connection); static void rollback(Connection connection); }### Answer:
@Test void closeQuietlyResultSet() throws SQLException { ResultSet resultSet = Mockito.mock(ResultSet.class); JdbcUtil.closeQuietly(resultSet); Mockito.verify(resultSet) .close(); }
@Test void closeQuietlyResultSetWithException() throws SQLException { ResultSet resultSet = Mockito.mock(ResultSet.class); Mockito.doThrow(new SQLException()) .when(resultSet) .close(); JdbcUtil.closeQuietly(resultSet); Mockito.verify(resultSet) .close(); }
@Test void closeQuietlyResultSetWithNull() { ResultSet resultSet = null; Assertions.assertDoesNotThrow(() -> JdbcUtil.closeQuietly(resultSet)); }
@Test void closeQuietlyStatement() throws SQLException { Statement statement = Mockito.mock(Statement.class); JdbcUtil.closeQuietly(statement); Mockito.verify(statement) .close(); }
@Test void closeQuietlyStatementWithException() throws SQLException { Statement statement = Mockito.mock(Statement.class); Mockito.doThrow(new SQLException()) .when(statement) .close(); JdbcUtil.closeQuietly(statement); Mockito.verify(statement) .close(); }
@Test void closeQuietlyStatementWithNull() { Statement statement = null; Assertions.assertDoesNotThrow(() -> JdbcUtil.closeQuietly(statement)); }
@Test void closeQuietlyConnection() throws SQLException { Connection connection = Mockito.mock(Connection.class); JdbcUtil.closeQuietly(connection); Mockito.verify(connection) .close(); }
@Test void closeQuietlyConnectionWithException() throws SQLException { Connection connection = Mockito.mock(Connection.class); Mockito.doThrow(new SQLException()) .when(connection) .close(); JdbcUtil.closeQuietly(connection); Mockito.verify(connection) .close(); }
@Test void closeQuietlyConnectionWithNull() { Connection connection = null; Assertions.assertDoesNotThrow(() -> JdbcUtil.closeQuietly(connection)); } |
### Question:
ApplicationColorDetector { public ApplicationColor detectLiveApplicationColor(DeployedMta deployedMta, String correlationId) { if (deployedMta == null) { return null; } ApplicationColor olderApplicationColor = getOlderApplicationColor(deployedMta); Operation currentOperation = operationService.createQuery() .processId(correlationId) .singleResult(); List<Operation> operations = operationService.createQuery() .mtaId(currentOperation.getMtaId()) .processType(ProcessType.BLUE_GREEN_DEPLOY) .spaceId(currentOperation.getSpaceId()) .inFinalState() .orderByEndTime(OrderDirection.DESCENDING) .limitOnSelect(1) .list(); if (CollectionUtils.isEmpty(operations)) { return olderApplicationColor; } if (operations.get(0) .getState() != Operation.State.ABORTED) { return olderApplicationColor; } String previousProcessId = operations.get(0) .getProcessId(); ApplicationColor latestDeployedColor = getColorFromHistoricProcess(previousProcessId); Phase phase = getPhaseFromHistoricProcess(previousProcessId); if (latestDeployedColor == null) { return olderApplicationColor; } return phase == Phase.UNDEPLOY ? latestDeployedColor : latestDeployedColor.getAlternativeColor(); } ApplicationColor detectLiveApplicationColor(DeployedMta deployedMta, String correlationId); ApplicationColor detectSingularDeployedApplicationColor(DeployedMta deployedMta); }### Answer:
@Test void detectLiveApplicationColorNullDeployedMta() { tester.test(() -> detectLiveApplicationColor(null), new Expectation(null)); }
@Test void detectLiveApplicationColorPhaseNotFound() { Expectation expectation = new Expectation(GREEN); mockOperationService(createFakeOperation(Operation.State.RUNNING, FAKE_PROCESS_ID), createFakeOperation(Operation.State.ABORTED, FAKE_BLUE_GREEN_DEPLOY_HISTORIC_PROCESS_INSTANCE_ID)); mockHistoricVariableInstanceColor(BLUE); tester.test(() -> detectLiveApplicationColor(readResource("deployed-mta-02.json", DeployedMta.class)), expectation); }
@Test void detectLiveApplicationColorMtaColoNotFound() { Expectation expectation = new Expectation(GREEN); mockOperationService(createFakeOperation(Operation.State.RUNNING, FAKE_PROCESS_ID), createFakeOperation(Operation.State.ABORTED, FAKE_BLUE_GREEN_DEPLOY_HISTORIC_PROCESS_INSTANCE_ID)); mockHistoricVariableInstancePhase(); tester.test(() -> detectLiveApplicationColor(readResource("deployed-mta-02.json", DeployedMta.class)), expectation); }
@Test void detectLiveApplicationColorNoOperations() { Expectation expectation = new Expectation(GREEN); mockOperationServiceNoOtherOperations(createFakeOperation(Operation.State.RUNNING, FAKE_PROCESS_ID)); tester.test(() -> detectLiveApplicationColor(readResource("deployed-mta-02.json", DeployedMta.class)), expectation); } |
### Question:
ModuleDeterminer { public Module determineModuleToDeploy() { Module moduleToDeploy = getContext().getVariable(Variables.MODULE_TO_DEPLOY); return moduleToDeploy != null ? moduleToDeploy : determineModule(); } Module determineModuleToDeploy(); abstract MtaMetadataParser getMtaMetadataParser(); abstract ProcessContext getContext(); }### Answer:
@Test void testDetermineModuleToDeployModuleIsSet() { ModuleDeterminer moduleDeterminer = createModuleDeterminer(); context.setVariable(Variables.MODULE_TO_DEPLOY, createModule("test-module")); Module module = moduleDeterminer.determineModuleToDeploy(); Assertions.assertEquals("test-module", module.getName()); }
@Test void testDetermineModuleIfModuleIsNotSetAnywhere() { ModuleDeterminer moduleDeterminer = createModuleDeterminer(); Assertions.assertNull(moduleDeterminer.determineModuleToDeploy()); }
@Test void testDetermineModuleIfModuleIsNotSet() { ModuleDeterminer moduleDeterminer = createModuleDeterminer(); DeploymentDescriptor completeDeploymentDescriptor = createDeploymentDescriptor(); Module moduleToDeploy = createModule("some-module-name"); completeDeploymentDescriptor.setModules(List.of(moduleToDeploy)); context.setVariable(Variables.COMPLETE_DEPLOYMENT_DESCRIPTOR, completeDeploymentDescriptor); context.setVariable(Variables.APP_TO_PROCESS, createApplication("app-to-process", "some-module-name", null)); context.setVariable(Variables.MTA_MAJOR_SCHEMA_VERSION, 3); Module module = moduleDeterminer.determineModuleToDeploy(); Assertions.assertEquals("some-module-name", module.getName()); } |
### Question:
ProcessConflictPreventer { public synchronized void acquireLock(String mtaId, String namespace, String spaceId, String processId) { LOGGER.info(format(Messages.ACQUIRING_LOCK, processId, mtaId)); validateNoConflictingOperationsExist(mtaId, namespace, spaceId); Operation currentOperation = getOperationByProcessId(processId); ImmutableOperation.Builder currentOperationWithAcquiredLock = ImmutableOperation.builder() .from(currentOperation) .mtaId(mtaId) .hasAcquiredLock(true); if (StringUtils.isNotEmpty(namespace)) { currentOperationWithAcquiredLock.namespace(namespace); } operationService.update(currentOperation, currentOperationWithAcquiredLock.build()); LOGGER.info(format(Messages.ACQUIRED_LOCK, processId, StepsUtil.getQualifiedMtaId(mtaId, namespace))); } ProcessConflictPreventer(OperationService operationService); synchronized void acquireLock(String mtaId, String namespace, String spaceId, String processId); void releaseLock(String processInstanceId, Operation.State state); }### Answer:
@Test void testAcquireLock() { SLException exception = assertThrows(SLException.class, this::tryToAcquireLock); assertEquals("Conflicting process \"test-process-id\" found for MTA \"test-mta-id\"", exception.getMessage()); }
@Test void testAcquireLockWithNoConflictingOperations() { assertDoesNotThrow(() -> processConflictPreventerMock.acquireLock(testMtaId, null, testSpaceId, testProcessId)); } |
### Question:
ProcessConflictPreventer { public void releaseLock(String processInstanceId, Operation.State state) { Operation operation = getOperationByProcessId(processInstanceId); LOGGER.info(MessageFormat.format(Messages.PROCESS_0_RELEASING_LOCK_FOR_MTA_1_IN_SPACE_2, operation.getProcessId(), operation.getMtaId(), operation.getSpaceId())); operation = ImmutableOperation.builder() .from(operation) .hasAcquiredLock(false) .state(state) .endedAt(ZonedDateTime.now()) .build(); operationService.update(operation, operation); LOGGER.debug(MessageFormat.format(Messages.PROCESS_0_RELEASED_LOCK, operation.getProcessId())); } ProcessConflictPreventer(OperationService operationService); synchronized void acquireLock(String mtaId, String namespace, String spaceId, String processId); void releaseLock(String processInstanceId, Operation.State state); }### Answer:
@Test void testReleaseLock() { Operation.State abortedState = Operation.State.ABORTED; processConflictPreventerMock.releaseLock(testProcessId, abortedState); ArgumentCaptor<Operation> argumentCaptor = ArgumentCaptor.forClass(Operation.class); verify(operationServiceMock).update(argumentCaptor.capture(), argThat(this::assertOperationAbort)); assertEquals(testProcessId, argumentCaptor.getValue() .getProcessId()); } |
### Question:
OperationTimeAggregator { public ProcessTime computeOverallProcessTime(String correlationId, Map<String, ProcessTime> processTimes) { ProcessTime rootProcessTime = processTimes.get(correlationId); long overallDelayBetweenSteps = processTimes.values() .stream() .mapToLong(ProcessTime::getDelayBetweenSteps) .sum(); return ImmutableProcessTime.copyOf(rootProcessTime) .withDelayBetweenSteps(overallDelayBetweenSteps); } @Inject OperationTimeAggregator(FlowableFacade flowableFacade); Map<String, ProcessTime> collectProcessTimes(String correlationId); ProcessTime computeOverallProcessTime(String correlationId, Map<String, ProcessTime> processTimes); }### Answer:
@Test void testOperationTimeWithNoSubProcesses() { Map<String, ProcessTime> processTimes = new HashMap<>(); processTimes.put(CORRELATION_ID, createProcessTime(100, 200)); ProcessTime overallProcessTime = operationTimeAggregator.computeOverallProcessTime(CORRELATION_ID, processTimes); assertEquals(100, overallProcessTime.getProcessDuration()); assertEquals(200, overallProcessTime.getDelayBetweenSteps()); }
@Test void testOperationTimeWithInvalidInput() { assertThrows(NullPointerException.class, () -> operationTimeAggregator.computeOverallProcessTime(CORRELATION_ID, Collections.emptyMap())); }
@Test void testOperationTimeWithOneSubProcess() { Map<String, ProcessTime> processTimes = new HashMap<>(); processTimes.put(CORRELATION_ID, createProcessTime(100, 200)); processTimes.put("id-1", createProcessTime(50, 100)); ProcessTime overallProcessTime = operationTimeAggregator.computeOverallProcessTime(CORRELATION_ID, processTimes); assertEquals(100, overallProcessTime.getProcessDuration()); assertEquals(300, overallProcessTime.getDelayBetweenSteps()); }
@Test void testOperationTimeWithTwoSubProcesses() { Map<String, ProcessTime> processTimes = new HashMap<>(); processTimes.put(CORRELATION_ID, createProcessTime(100, 200)); processTimes.put("id-1", createProcessTime(50, 100)); processTimes.put("id-2", createProcessTime(70, 300)); ProcessTime overallProcessTime = operationTimeAggregator.computeOverallProcessTime(CORRELATION_ID, processTimes); assertEquals(100, overallProcessTime.getProcessDuration()); assertEquals(600, overallProcessTime.getDelayBetweenSteps()); } |
### Question:
HooksPhaseBuilder { public List<HookPhase> buildHookPhases(List<HookPhase> hookPhases, ProcessContext context) { return hookPhases.stream() .map(hookPhase -> buildPhase(hookPhase, context)) .map(HookPhase::fromString) .collect(Collectors.toList()); } @Inject HooksPhaseBuilder(ProcessTypeParser processTypeParser); List<HookPhase> buildHookPhases(List<HookPhase> hookPhases, ProcessContext context); }### Answer:
@Test void testBuildHookPhaseForDeployProcess() { Mockito.when(processTypeParser.getProcessType(context.getExecution())) .thenReturn(ProcessType.DEPLOY); HooksPhaseBuilder hooksPhaseBuilder = new HooksPhaseBuilder(processTypeParser); List<HookPhase> hookPhases = hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_STOP), context); Assertions.assertEquals(List.of(HookPhase.DEPLOY_APPLICATION_BEFORE_STOP), hookPhases); }
@Test void testBuildHookPhaseForBlueGreenDeployProcessWithSubprocessPhaseBeforeApplicationStop() { Mockito.when(processTypeParser.getProcessType(context.getExecution())) .thenReturn(ProcessType.BLUE_GREEN_DEPLOY); context.setVariable(Variables.SUBPROCESS_PHASE, SubprocessPhase.BEFORE_APPLICATION_STOP); HooksPhaseBuilder hooksPhaseBuilder = new HooksPhaseBuilder(processTypeParser); List<HookPhase> hookPhases = hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_STOP), context); Assertions.assertEquals(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_IDLE), hookPhases); }
@Test void testBuildHookPhaseForBlueGreenDeployProcessWithSubprocessPhaseBeforeApplicationStart() { Mockito.when(processTypeParser.getProcessType(context.getExecution())) .thenReturn(ProcessType.BLUE_GREEN_DEPLOY); context.setVariable(Variables.SUBPROCESS_PHASE, SubprocessPhase.BEFORE_APPLICATION_START); HooksPhaseBuilder hooksPhaseBuilder = new HooksPhaseBuilder(processTypeParser); List<HookPhase> hookPhases = hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_START), context); Assertions.assertEquals(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_START_IDLE), hookPhases); }
@Test void testBuildHookPhaseForBlueGreenProcessWithPhaseUndeploy() { Mockito.when(processTypeParser.getProcessType(context.getExecution())) .thenReturn(ProcessType.BLUE_GREEN_DEPLOY); context.setVariable(Variables.PHASE, Phase.UNDEPLOY); HooksPhaseBuilder hooksPhaseBuilder = new HooksPhaseBuilder(processTypeParser); List<HookPhase> hookPhases = hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.AFTER_STOP), context); Assertions.assertEquals(List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE), hookPhases); }
@Test void testBuildHookPhaseForBlueGreenProcessWithPhaseAfterResume() { Mockito.when(processTypeParser.getProcessType(context.getExecution())) .thenReturn(ProcessType.BLUE_GREEN_DEPLOY); context.setVariable(Variables.PHASE, Phase.AFTER_RESUME); HooksPhaseBuilder hooksPhaseBuilder = new HooksPhaseBuilder(processTypeParser); List<HookPhase> hookPhases = hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_START), context); Assertions.assertEquals(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_START_LIVE), hookPhases); } |
### Question:
ArchiveMerger { public Path createArchiveFromParts(List<FileEntry> archiveParts) { List<FileEntry> sortedArchiveParts = sort(archiveParts); String archiveName = getArchiveName(sortedArchiveParts.get(0)); try (FilePartsMerger filePartsMerger = new FilePartsMerger(archiveName)) { mergeArchiveParts(sortedArchiveParts, filePartsMerger); return filePartsMerger.getMergedFilePath(); } } ArchiveMerger(FileService fileService, StepLogger stepLogger, DelegateExecution execution); Path createArchiveFromParts(List<FileEntry> archiveParts); }### Answer:
@Test void testCreateArchiveFromPartsFileStorageExceptionThrown() throws FileStorageException { Mockito.doThrow(FileStorageException.class) .when(fileService) .consumeFileContent(any(), any(), any()); Assertions.assertThrows(SLException.class, () -> archiveMerger.createArchiveFromParts(createFileEntriesFromFile(FILE_ENTRIES))); }
@Test void testCreateArchiveFromParts() { List<FileEntry> fileEntries = createFileEntriesFromFile(FILE_ENTRIES); Path archiveFromParts = archiveMerger.createArchiveFromParts(fileEntries); Assertions.assertTrue(archiveFromParts.toString() .endsWith(getArchiveName(fileEntries.get(0)))); }
@Test void testWithArchiveNameWithoutParts() throws FileStorageException { List<FileEntry> fileEntryWithoutParts = createFileEntriesFromFile(FILE_ENTRY_WITHOUT_PARTS); archiveMerger.createArchiveFromParts(fileEntryWithoutParts); Mockito.verify(fileService) .consumeFileContent(any(), any(), any()); } |
### Question:
ArchiveMerger { List<FileEntry> sort(List<FileEntry> archiveParts) { return archiveParts.stream() .sorted(Comparator.comparingInt(this::getArchivePartIndex)) .collect(Collectors.toList()); } ArchiveMerger(FileService fileService, StepLogger stepLogger, DelegateExecution execution); Path createArchiveFromParts(List<FileEntry> archiveParts); }### Answer:
@Test void testSortFileEntries() { List<FileEntry> randomSortedFileEntries = createFileEntriesFromFile(RANDOM_SORTED_ENTRIES); List<FileEntry> expectedFileEntries = createFileEntriesFromFile(EXPECTED_FILE_ENTRIES); List<FileEntry> sortedFileEntries = archiveMerger.sort(randomSortedFileEntries); Assertions.assertIterableEquals(getFileEntriesNames(expectedFileEntries), getFileEntriesNames(sortedFileEntries)); }
@Test void testSortFileEntriesWithInvalidNames() { List<FileEntry> invalidFileEntries = createFileEntriesFromFile(FILE_ENTRIES_WITH_INVALID_NAMES); Assertions.assertThrows(SLException.class, () -> archiveMerger.sort(invalidFileEntries)); }
@Test void testSortFileEntriesWithNamesWhichContainPartButDoNotContainIndexes() { List<FileEntry> invalidFileEntries = createFileEntriesFromFile(FILE_ENTRIES_WITHOUT_INDEXES); Assertions.assertThrows(SLException.class, () -> archiveMerger.sort(invalidFileEntries)); } |
### Question:
ApplicationArchiveReader { public String calculateApplicationDigest(ApplicationArchiveContext applicationArchiveContext) { try { iterateApplicationArchive(applicationArchiveContext); return applicationArchiveContext.getApplicationDigestCalculator() .getDigest(); } catch (IOException e) { throw new SLException(e, Messages.ERROR_RETRIEVING_MTA_MODULE_CONTENT, applicationArchiveContext.getModuleFileName()); } } String calculateApplicationDigest(ApplicationArchiveContext applicationArchiveContext); ZipEntry getFirstZipEntry(ApplicationArchiveContext applicationArchiveContext); ZipEntry getNextEntryByName(String name, ApplicationArchiveContext applicationArchiveContext); }### Answer:
@Test void testBadAbsolutePathRead() { String mtar = SAMPLE_MTAR_WITH_JAR_ENTRY_ABSOLUTE_PATH; String fileName = "/web/"; String expectedException = MessageFormat.format(FileUtils.PATH_SHOULD_NOT_BE_ABSOLUTE, "/web/"); long maxFileUploadSize = MAX_UPLOAD_FILE_SIZE; ApplicationArchiveContext applicationArchiveContext = getApplicationArchiveContext(mtar, fileName, maxFileUploadSize); ApplicationArchiveReader reader = getApplicationArchiveReaderForAbsolutePath(); Exception exception = Assertions.assertThrows(Exception.class, () -> reader.calculateApplicationDigest(applicationArchiveContext)); assertEquals(expectedException, exception.getMessage()); } |
### Question:
OperationsHelper { public String getProcessDefinitionKey(Operation operation) { return metadataMapper.getDiagramId(operation.getProcessType()); } @Inject OperationsHelper(OperationService operationService, ProcessTypeToOperationMetadataMapper metadataMapper,
ProcessHelper processHelper); String getProcessDefinitionKey(Operation operation); Operation addErrorType(Operation operation); Operation addState(Operation operation); Operation.State computeState(Operation operation); Operation.State computeProcessState(String processId); List<Operation> findOperations(List<Operation> operations, List<Operation.State> statusList); }### Answer:
@Test void testGetProcessDefinitionKey() { Operation mockedOperation = createMockedOperation(PROCESS_ID, ProcessType.DEPLOY, Operation.State.RUNNING); Mockito.when(metadataMapper.getDiagramId(ProcessType.DEPLOY)) .thenReturn(Constants.DEPLOY_SERVICE_ID); String processDefinitionKey = operationsHelper.getProcessDefinitionKey(mockedOperation); Assertions.assertEquals(Constants.DEPLOY_SERVICE_ID, processDefinitionKey); } |
### Question:
OperationsHelper { public Operation addState(Operation operation) { if (operation.getState() != null) { return operation; } Operation.State state = computeState(operation); if (operation.hasAcquiredLock() && (state.equals(Operation.State.ABORTED) || state.equals(Operation.State.FINISHED))) { operation = ImmutableOperation.builder() .from(operation) .hasAcquiredLock(false) .state(state) .build(); operationService.update(operation, operation); } return ImmutableOperation.copyOf(operation) .withState(state); } @Inject OperationsHelper(OperationService operationService, ProcessTypeToOperationMetadataMapper metadataMapper,
ProcessHelper processHelper); String getProcessDefinitionKey(Operation operation); Operation addErrorType(Operation operation); Operation addState(Operation operation); Operation.State computeState(Operation operation); Operation.State computeProcessState(String processId); List<Operation> findOperations(List<Operation> operations, List<Operation.State> statusList); }### Answer:
@Test void testAddStateWhenOperationHasState() { Operation mockedOperation = createMockedOperation(PROCESS_ID, ProcessType.DEPLOY, Operation.State.RUNNING); Operation operation = operationsHelper.addState(mockedOperation); Assertions.assertEquals(Operation.State.RUNNING, operation.getState()); } |
### Question:
OperationsHelper { public Operation.State computeProcessState(String processId) { return processHelper.computeProcessState(processId); } @Inject OperationsHelper(OperationService operationService, ProcessTypeToOperationMetadataMapper metadataMapper,
ProcessHelper processHelper); String getProcessDefinitionKey(Operation operation); Operation addErrorType(Operation operation); Operation addState(Operation operation); Operation.State computeState(Operation operation); Operation.State computeProcessState(String processId); List<Operation> findOperations(List<Operation> operations, List<Operation.State> statusList); }### Answer:
@Test void testComputeOperationStateWhenProcessIsInNonFinalStateAndProcessIsAborted() { Mockito.when(processHelper.computeProcessState(PROCESS_ID)) .thenReturn(State.ABORTED); Operation.State state = operationsHelper.computeProcessState(PROCESS_ID); Assertions.assertEquals(Operation.State.ABORTED, state); }
@Test void testComputeOperationStateWhenProcessIsInNonFinalStateAndProcessIsAtReceiveTask() { Mockito.when(processHelper.computeProcessState(PROCESS_ID)) .thenReturn(State.ACTION_REQUIRED); Operation.State state = operationsHelper.computeProcessState(PROCESS_ID); Assertions.assertEquals(Operation.State.ACTION_REQUIRED, state); }
@Test void testComputeOperationStateWhenProcessIsInNonFinalStateAndProcessIsInErrorState() { Mockito.when(processHelper.computeProcessState(PROCESS_ID)) .thenReturn(State.ERROR); Operation.State state = operationsHelper.computeProcessState(PROCESS_ID); Assertions.assertEquals(Operation.State.ERROR, state); }
@Test void testComputeOperationStateWhenProcessIsInNonFinalStateAndProcessIsRunning() { Mockito.when(processHelper.computeProcessState(PROCESS_ID)) .thenReturn(State.RUNNING); Operation.State state = operationsHelper.computeProcessState(PROCESS_ID); Assertions.assertEquals(Operation.State.RUNNING, state); }
@Test void testComputeOperationStateWhenProcessIsInFinalStateAndProcessIsAborted() { Mockito.when(processHelper.computeProcessState(PROCESS_ID)) .thenReturn(State.ABORTED); Operation.State state = operationsHelper.computeProcessState(PROCESS_ID); Assertions.assertEquals(Operation.State.ABORTED, state); }
@Test void testComputeOperationStateWhenProcessIsInFinalStateAndProcessIsNotAborted() { Mockito.when(processHelper.computeProcessState(PROCESS_ID)) .thenReturn(State.FINISHED); Operation.State state = operationsHelper.computeProcessState(PROCESS_ID); Assertions.assertEquals(Operation.State.FINISHED, state); } |
### Question:
OperationsHelper { public List<Operation> findOperations(List<Operation> operations, List<Operation.State> statusList) { operations = addState(operations); return filterBasedOnStates(operations, statusList); } @Inject OperationsHelper(OperationService operationService, ProcessTypeToOperationMetadataMapper metadataMapper,
ProcessHelper processHelper); String getProcessDefinitionKey(Operation operation); Operation addErrorType(Operation operation); Operation addState(Operation operation); Operation.State computeState(Operation operation); Operation.State computeProcessState(String processId); List<Operation> findOperations(List<Operation> operations, List<Operation.State> statusList); }### Answer:
@Test void testFindOperationsWithStatusRunning() { List<Operation> operations = List.of(createMockedOperation("12af8e1e-4d96-11ea-b77f-2e728ce88178", ProcessType.DEPLOY, Operation.State.RUNNING), createMockedOperation("13af8e1e-4d96-11ea-b77f-2e728ce88178", ProcessType.DEPLOY, Operation.State.ABORTED)); List<Operation.State> statusList = List.of(Operation.State.RUNNING); List<Operation> foundOperations = operationsHelper.findOperations(operations, statusList); Assertions.assertEquals(1, foundOperations.size()); Assertions.assertEquals("12af8e1e-4d96-11ea-b77f-2e728ce88178", operations.get(0) .getProcessId()); }
@Test void testFundOperationsWithoutStatus() { List<Operation> operations = List.of(createMockedOperation("12af8e1e-4d96-11ea-b77f-2e728ce88178", ProcessType.DEPLOY, Operation.State.RUNNING), createMockedOperation("13af8e1e-4d96-11ea-b77f-2e728ce88178", ProcessType.DEPLOY, Operation.State.ABORTED)); List<Operation> foundOperations = operationsHelper.findOperations(operations, Collections.emptyList()); Assertions.assertEquals(2, foundOperations.size()); } |
### Question:
ApplicationStager { public boolean isApplicationStagedCorrectly(CloudApplication app) { List<CloudBuild> buildsForApplication = client.getBuildsForApplication(app.getMetadata() .getGuid()); if (containsNullMetadata(buildsForApplication)) { return false; } CloudBuild build = getLastBuild(buildsForApplication); if (build == null) { logger.debug(Messages.NO_BUILD_FOUND_FOR_APPLICATION, app.getName()); return false; } if (isBuildStagedCorrectly(build)) { return true; } logMessages(app, build); return false; } ApplicationStager(ProcessContext context); StagingState getStagingState(); boolean isApplicationStagedCorrectly(CloudApplication app); void bindDropletToApplication(UUID appGuid); StepPhase stageApp(CloudApplication app); }### Answer:
@Test void testIsApplicationStagedCorrectlyMetadataIsNull() { CloudApplication app = createApplication(); Mockito.when(client.getBuildsForApplication(any(UUID.class))) .thenReturn(List.of(Mockito.mock(CloudBuild.class))); Assertions.assertFalse(applicationStager.isApplicationStagedCorrectly(app)); }
@Test void testIsApplicationStagedCorrectlyNoLastBuild() { CloudApplication app = createApplication(); Mockito.when(client.getBuildsForApplication(any(UUID.class))) .thenReturn(Collections.emptyList()); Assertions.assertFalse(applicationStager.isApplicationStagedCorrectly(app)); } |
### Question:
ApplicationStager { public StepPhase stageApp(CloudApplication app) { CloudPackage cloudPackage = context.getVariable(Variables.CLOUD_PACKAGE); if (cloudPackage == null) { return StepPhase.DONE; } logger.info(Messages.STAGING_APP, app.getName()); return createBuild(cloudPackage.getGuid()); } ApplicationStager(ProcessContext context); StagingState getStagingState(); boolean isApplicationStagedCorrectly(CloudApplication app); void bindDropletToApplication(UUID appGuid); StepPhase stageApp(CloudApplication app); }### Answer:
@Test void testStageAppIfThereIsNoCloudPacakge() { context.setVariable(Variables.CLOUD_PACKAGE, null); assertEquals(StepPhase.DONE, applicationStager.stageApp(null)); } |
### Question:
ApplicationStager { public StagingState getStagingState() { UUID buildGuid = context.getVariable(Variables.BUILD_GUID); if (buildGuid == null) { return ImmutableStagingState.builder() .state(PackageState.STAGED) .build(); } CloudBuild build = getBuild(buildGuid); return getStagingState(build); } ApplicationStager(ProcessContext context); StagingState getStagingState(); boolean isApplicationStagedCorrectly(CloudApplication app); void bindDropletToApplication(UUID appGuid); StepPhase stageApp(CloudApplication app); }### Answer:
@Test void testIfBuildGuidDoesNotExist() { StagingState stagingState = applicationStager.getStagingState(); assertEquals(PackageState.STAGED, stagingState.getState()); assertNull(stagingState.getError()); } |
### Question:
JarSignatureOperations { public List<X509Certificate> readCertificates(String certificatesFilename) { try (InputStream certificatesInputStream = getClass().getResourceAsStream(certificatesFilename)) { CertificateFactory certificateFactory = CertificateFactory.getInstance(Constants.CERTIFICATE_TYPE_X_509); return (List<X509Certificate>) certificateFactory.generateCertificates(certificatesInputStream); } catch (CertificateException | IOException e) { throw new SLException(e, e.getMessage()); } } void checkCertificates(URL url, List<X509Certificate> certificates, String certificateCN); List<X509Certificate> readCertificates(String certificatesFilename); }### Answer:
@Test void testGetCertificatesCheckWhetherSymantecExists() { List<X509Certificate> providedCertificates = mtaCertificateChecker.readCertificates(Constants.SYMANTEC_CERTIFICATE_FILE); Assertions.assertEquals(1, providedCertificates.size()); Assertions.assertEquals(SYMANTEC_SUBJECT_DN, providedCertificates.get(0) .getSubjectDN() .toString()); Assertions.assertEquals(SYMANTEC_ISSUER_DN, providedCertificates.get(0) .getIssuerDN() .toString()); }
@Test void testGetCertificatesWithNullInputStream() { SLException exception = Assertions.assertThrows(SLException.class, () -> mtaCertificateChecker.readCertificates("non-existing-certificate.crt")); Assertions.assertEquals("Missing input stream", exception.getMessage()); } |
### Question:
ProcessTypeToOperationMetadataMapper { public String getDiagramId(ProcessType processType) { return getOperationMetadata(processType).getDiagramId(); } OperationMetadata getOperationMetadata(ProcessType processType); String getDiagramId(ProcessType processType); }### Answer:
@Test void testGetDiagramDeployProcessType() { Assertions.assertEquals(Constants.DEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.DEPLOY)); }
@Test void testGetDiagramBlueGreenDeployProcessType() { Assertions.assertEquals(Constants.BLUE_GREEN_DEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.BLUE_GREEN_DEPLOY)); }
@Test void testGetDiagramUndeployProcessType() { Assertions.assertEquals(Constants.UNDEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.UNDEPLOY)); }
@Test void testGetDiagramCtsDeployProcessType() { Assertions.assertEquals(Constants.CTS_DEPLOY_SERVICE_ID, processTypeToOperationMetadataMapper.getDiagramId(ProcessType.CTS_DEPLOY)); } |
### Question:
VersionRuleParameterConverter implements ParameterConverter { @Override public Object convert(Object value) { String versionRule = String.valueOf(value); validate(versionRule); return versionRule; } @Override Object convert(Object value); }### Answer:
@Test void testConvertWithInvalidValueType() { assertThrows(SLException.class, () -> new VersionRuleParameterConverter().convert(false)); }
@Test void testConvertWithInvalidValue() { assertThrows(SLException.class, () -> new VersionRuleParameterConverter().convert("foo")); }
@Test void testConvert() { String versionRule = (String) new VersionRuleParameterConverter().convert("ALL"); assertEquals("ALL", versionRule); } |
### Question:
StartTimeoutParameterConverter extends IntegerParameterConverter { @Override public Integer convert(Object value) { int startTimeout = super.convert(value); if (startTimeout < 0) { throw new SLException(Messages.ERROR_PARAMETER_1_MUST_NOT_BE_NEGATIVE, startTimeout, Variables.START_TIMEOUT.getName()); } return startTimeout; } @Override Integer convert(Object value); }### Answer:
@Test void testConvertWithInvalidValueType() { assertThrows(SLException.class, () -> new StartTimeoutParameterConverter().convert(false)); }
@Test void testConvertWithInvalidValue() { assertThrows(SLException.class, () -> new StartTimeoutParameterConverter().convert(-1000)); }
@Test void testConvert() { int startTimeout = (int) new StartTimeoutParameterConverter().convert("1000"); assertEquals(1000, startTimeout); } |
### Question:
RestartAppStep extends TimeoutAsyncFlowableStepWithHooks implements BeforeStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesBeforeStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Collections.singletonList(HookPhase.BEFORE_START), context); } @Override StepPhase executePollingStep(ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testGetHookPhasesBeforeStep() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_START), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_START_LIVE)); List<HookPhase> expectedHooks = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_START_LIVE); List<HookPhase> hookPhasesBeforeStep = step.getHookPhasesBeforeStep(context); assertEquals(expectedHooks, hookPhasesBeforeStep); } |
### Question:
UpdateServiceMetadataStep extends ServiceStep { private MethodExecution<String> updateServiceMetadata(CloudControllerClient controllerClient, CloudServiceInstanceExtended service) { getStepLogger().debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0, service.getName(), service.getResourceName()); updateServiceMetadata(service, controllerClient); getStepLogger().debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0_DONE, service.getName()); return new MethodExecution<>(null, MethodExecution.ExecutionState.FINISHED); } }### Answer:
@Test void testUpdateServiceMetadata() { CloudServiceInstanceExtended serviceToProcess = buildServiceToProcess(); prepareServiceToProcess(serviceToProcess); prepareClient(serviceToProcess); step.execute(execution); verify(client).updateServiceInstanceMetadata(serviceToProcess.getMetadata() .getGuid(), serviceToProcess.getV3Metadata()); } |
### Question:
UpdateServiceMetadataExecution implements AsyncExecution { @Override public AsyncExecutionState execute(ProcessContext context) { CloudServiceInstanceExtended serviceInstance = context.getVariable(Variables.SERVICE_TO_PROCESS); context.getStepLogger() .debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0, serviceInstance.getName()); updateMetadata(context.getControllerClient(), serviceInstance); context.getStepLogger() .debug(Messages.UPDATING_METADATA_OF_SERVICE_INSTANCE_0_DONE, serviceInstance.getName()); return AsyncExecutionState.FINISHED; } @Override AsyncExecutionState execute(ProcessContext context); @Override String getPollingErrorMessage(ProcessContext context); }### Answer:
@Test void testExecute() { Metadata v3Metadata = Metadata.builder() .annotation("a", "b") .annotation("c", "d") .build(); CloudServiceInstanceExtended serviceInstanceToCreate = ImmutableCloudServiceInstanceExtended.builder() .name(SERVICE_INSTANCE_NAME) .plan(SERVICE_INSTANCE_PLAN) .label(SERVICE_INSTANCE_LABEL) .v3Metadata(v3Metadata) .build(); Mockito.when(procesContext.getVariable(Variables.SERVICE_TO_PROCESS)) .thenReturn(serviceInstanceToCreate); CloudMetadata metadata = ImmutableCloudMetadata.builder() .guid(UUID.randomUUID()) .createdAt(new Date()) .updatedAt(new Date()) .build(); CloudServiceInstance serviceInstance = ImmutableCloudServiceInstance.builder() .name(SERVICE_INSTANCE_NAME) .plan(SERVICE_INSTANCE_PLAN) .label(SERVICE_INSTANCE_LABEL) .metadata(metadata) .build(); Mockito.when(controllerClient.getServiceInstance(serviceInstance.getName())) .thenReturn(serviceInstance); AsyncExecution asyncExecution = new UpdateServiceMetadataExecution(); asyncExecution.execute(procesContext); Mockito.verify(controllerClient) .updateServiceInstanceMetadata(metadata.getGuid(), v3Metadata); } |
### Question:
ProcessStepHelper { protected void postExecuteStep(ProcessContext context, StepPhase state) { logDebug(MessageFormat.format(Messages.STEP_FINISHED, context.getExecution() .getCurrentFlowElement() .getName())); getProcessLogsPersister().persistLogs(context.getVariable(Variables.CORRELATION_ID), context.getVariable(Variables.TASK_ID)); context.setVariable(Variables.STEP_EXECUTION, state.toString()); } void failStepIfProcessIsAborted(ProcessContext context); static boolean isProcessAborted(List<HistoricOperationEvent> historicOperationEvents); abstract ProgressMessageService getProgressMessageService(); abstract ProcessLogsPersister getProcessLogsPersister(); abstract StepLogger getStepLogger(); abstract ProcessEngineConfiguration getProcessEngineConfiguration(); abstract ProcessHelper getProcessHelper(); }### Answer:
@Test void testPostExecutionStep() { Mockito.when(context.getVariable(Variables.TASK_ID)) .thenReturn(TASK_GUID); FlowElement flowElement = Mockito.mock(SubProcess.class); Mockito.when(execution.getCurrentFlowElement()) .thenReturn(flowElement); processStepHelper.postExecuteStep(context, StepPhase.DONE); Mockito.verify(processLogsPersister) .persistLogs(CORRELATION_GUID, TASK_GUID); Mockito.verify(context) .setVariable(Variables.STEP_EXECUTION, StepPhase.DONE.toString()); } |
### Question:
ProcessStepHelper { protected void logExceptionAndStoreProgressMessage(ProcessContext context, Throwable t) { logException(context, t); storeExceptionInProgressMessageService(context, t); } void failStepIfProcessIsAborted(ProcessContext context); static boolean isProcessAborted(List<HistoricOperationEvent> historicOperationEvents); abstract ProgressMessageService getProgressMessageService(); abstract ProcessLogsPersister getProcessLogsPersister(); abstract StepLogger getStepLogger(); abstract ProcessEngineConfiguration getProcessEngineConfiguration(); abstract ProcessHelper getProcessHelper(); }### Answer:
@Test void testLogExceptionAndStoreExceptionContentError() { prepareProgressMessagesService(); processStepHelper.logExceptionAndStoreProgressMessage(context, new ContentException("content exception")); Mockito.verify(context) .setVariable(Variables.ERROR_TYPE, ErrorType.CONTENT_ERROR); Mockito.verify(progressMessageService) .add(any()); }
@Test void testLogExceptionAndStoreExceptionUnknownError() { prepareProgressMessagesService(); processStepHelper.logExceptionAndStoreProgressMessage(context, new RuntimeException("runtime exception")); Mockito.verify(context) .setVariable(Variables.ERROR_TYPE, ErrorType.UNKNOWN_ERROR); Mockito.verify(progressMessageService) .add(any()); } |
### Question:
ProcessStepHelper { public void failStepIfProcessIsAborted(ProcessContext context) { String correlationId = context.getVariable(Variables.CORRELATION_ID); List<HistoricOperationEvent> historicOperationEvents = getProcessHelper().getHistoricOperationEventByProcessId(correlationId); if (isProcessAborted(historicOperationEvents)) { throw new SLException(Messages.PROCESS_WAS_ABORTED); } } void failStepIfProcessIsAborted(ProcessContext context); static boolean isProcessAborted(List<HistoricOperationEvent> historicOperationEvents); abstract ProgressMessageService getProgressMessageService(); abstract ProcessLogsPersister getProcessLogsPersister(); abstract StepLogger getStepLogger(); abstract ProcessEngineConfiguration getProcessEngineConfiguration(); abstract ProcessHelper getProcessHelper(); }### Answer:
@Test void testFailStepPhaseAbortIsInvoked() { prepareHistoricOperationsEventGetter(HistoricOperationEvent.EventType.STARTED, HistoricOperationEvent.EventType.FINISHED, HistoricOperationEvent.EventType.ABORT_EXECUTED); Exception exception = Assertions.assertThrows(SLException.class, () -> processStepHelper.failStepIfProcessIsAborted(context)); Assertions.assertEquals(Messages.PROCESS_WAS_ABORTED, exception.getMessage()); }
@Test void testFailedStepPhaseAbortIsNotInvoked() { prepareHistoricOperationsEventGetter(HistoricOperationEvent.EventType.STARTED, HistoricOperationEvent.EventType.FINISHED); Assertions.assertDoesNotThrow(() -> processStepHelper.failStepIfProcessIsAborted(context)); } |
### Question:
ProcessGitSourceStep extends SyncFlowableStep { protected String getGitUri(ProcessContext context) { String gitUriParam = StepsUtil.getGitRepoUri(context); try { return new URL(gitUriParam).toString(); } catch (MalformedURLException e) { throw new ContentException(e, Messages.GIT_URI_IS_NOT_SPECIFIED); } } static final String META_INF_PATH; }### Answer:
@Test void getGitUriTest() throws SLException { String gitUri = "https: context.setVariable(Variables.GIT_URI, gitUri); assertEquals(gitUri, step.getGitUri(context)); } |
### Question:
ProcessGitSourceStep extends SyncFlowableStep { protected String extractRepoName(String gitUri, String processId) { if (!gitUri.endsWith(PATH_SEPARATOR + org.eclipse.jgit.lib.Constants.DOT_GIT)) { return gitUri.substring(gitUri.lastIndexOf(PATH_SEPARATOR) + 1) + processId; } String repoLocation = gitUri.substring(0, gitUri.lastIndexOf(PATH_SEPARATOR + org.eclipse.jgit.lib.Constants.DOT_GIT)); return repoLocation.substring(repoLocation.lastIndexOf(PATH_SEPARATOR) + 1) + processId; } static final String META_INF_PATH; }### Answer:
@Test void testExtractRepoName() { String somerepoName = step.extractRepoName("https: assertEquals("somerepo" + PROCESS_INSTANCE_ID, somerepoName); String otherrepoName = step.extractRepoName("https: assertEquals("otherrepo" + PROCESS_INSTANCE_ID, otherrepoName); } |
### Question:
TextAttributeConverter implements AttributeConverter<String, String> { @Override public String convertToDatabaseColumn(String text) { if (text != null) { return StringUtils.abbreviate(text, MAX_STRING_LENGTH); } return ""; } @Override String convertToDatabaseColumn(String text); @Override String convertToEntityAttribute(String text); }### Answer:
@Test void testConvertToDatabaseColumnWhenInputIsNotNull() { Assertions.assertEquals("test", textAttributeConverter.convertToDatabaseColumn("test")); }
@Test void testConvertToDatabaseColumnWhenInputIsNull() { Assertions.assertEquals("", textAttributeConverter.convertToDatabaseColumn(null)); }
@Test void testConvertToDatabaseColumnWhenInputIsLongerThan4000chars() { String expectedString = getLongStringInput().substring(0, 3997) .concat("..."); Assertions.assertEquals(expectedString, textAttributeConverter.convertToDatabaseColumn(getLongStringInput())); } |
### Question:
StageAppStep extends TimeoutAsyncFlowableStep { @Override protected String getStepErrorMessage(ProcessContext context) { return MessageFormat.format(Messages.ERROR_STAGING_APP_0, context.getVariable(Variables.APP_TO_PROCESS) .getName()); } @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testGetErrorMessage() { String applicationName = "another-app"; mockApplication(applicationName); Assertions.assertEquals(MessageFormat.format(Messages.ERROR_STAGING_APP_0, applicationName), step.getStepErrorMessage(context)); } |
### Question:
StageAppStep extends TimeoutAsyncFlowableStep { @Override protected List<AsyncExecution> getAsyncStepExecutions(ProcessContext context) { return Collections.singletonList(new PollStageAppStatusExecution(recentLogsRetriever, new ApplicationStager(context))); } @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testAsyncExecutionStatus() { List<AsyncExecution> asyncStepExecutions = step.getAsyncStepExecutions(context); Assertions.assertEquals(1, asyncStepExecutions.size()); Assertions.assertTrue(asyncStepExecutions.get(0) instanceof PollStageAppStatusExecution); } |
### Question:
StageAppStep extends TimeoutAsyncFlowableStep { @Override public Integer getTimeout(ProcessContext context) { return context.getVariable(Variables.START_TIMEOUT); } @Override Integer getTimeout(ProcessContext context); }### Answer:
@Test void testGetTimeoutDefaultValue() { Assertions.assertEquals(Variables.START_TIMEOUT.getDefaultValue(), step.getTimeout(context)); }
@Test void testGetTimeoutCustomValue() { int timeout = 10; context.setVariable(Variables.START_TIMEOUT, timeout); Assertions.assertEquals(timeout, step.getTimeout(context)); } |
### Question:
DeleteIdleRoutesStep extends SyncFlowableStep { @Override protected String getStepErrorMessage(ProcessContext context) { return Messages.ERROR_DELETING_IDLE_ROUTES; } }### Answer:
@Test void testErrorMessage() { Assertions.assertEquals(Messages.ERROR_DELETING_IDLE_ROUTES, step.getStepErrorMessage(context)); } |
### Question:
PollExecuteAppStatusExecution implements AsyncExecution { @Override public AsyncExecutionState execute(ProcessContext context) { List<ApplicationStateAction> actions = context.getVariable(Variables.APP_STATE_ACTIONS_TO_EXECUTE); if (!actions.contains(ApplicationStateAction.EXECUTE)) { return AsyncExecutionState.FINISHED; } CloudApplication app = getNextApp(context); CloudControllerClient client = context.getControllerClient(); ApplicationAttributes appAttributes = ApplicationAttributes.fromApplication(app); AppExecutionDetailedStatus status = getAppExecutionStatus(context, client, appAttributes, app); ProcessLoggerProvider processLoggerProvider = context.getStepLogger() .getProcessLoggerProvider(); StepsUtil.saveAppLogs(context, client, recentLogsRetriever, app, LOGGER, processLoggerProvider); return checkAppExecutionStatus(context, client, app, appAttributes, status); } PollExecuteAppStatusExecution(RecentLogsRetriever recentLogsRetriever); @Override AsyncExecutionState execute(ProcessContext context); String getPollingErrorMessage(ProcessContext context); }### Answer:
@Test void testStepWithoutExecuteAction() { context.setVariable(Variables.APP_STATE_ACTIONS_TO_EXECUTE, Collections.emptyList()); AsyncExecutionState resultState = step.execute(context); assertEquals(AsyncExecutionState.FINISHED, resultState); } |
### Question:
DeleteApplicationRoutesStep extends UndeployAppStep implements BeforeStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesBeforeStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Arrays.asList(HookPhase.BEFORE_UNMAP_ROUTES, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES), context); } @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); }### Answer:
@Test void testGetHookPhaseBefore() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_UNMAP_ROUTES, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_UNMAP_ROUTES_LIVE, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES)); List<HookPhase> expectedPhases = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_UNMAP_ROUTES_LIVE, HookPhase.APPLICATION_BEFORE_UNMAP_ROUTES); List<HookPhase> hookPhasesBeforeStep = ((BeforeStepHookPhaseProvider) step).getHookPhasesBeforeStep(context); assertEquals(expectedPhases, hookPhasesBeforeStep); } |
### Question:
StepsUtil { public static String determineCurrentUser(VariableScope scope) { String user = VariableHandling.get(scope, Variables.USER); if (user == null) { throw new SLException(Messages.CANT_DETERMINE_CURRENT_USER); } return user; } protected StepsUtil(); static String determineCurrentUser(VariableScope scope); static CloudHandlerFactory getHandlerFactory(VariableScope scope); static String getQualifiedMtaId(String mtaId, String namespace); static CloudServiceBroker getServiceBrokersToCreateForModule(VariableScope scope, String moduleName); static List<String> getCreatedOrUpdatedServiceBrokerNames(ProcessContext context); static String getLoggerPrefix(Logger logger); static void incrementVariable(VariableScope scope, String name); static void setExecutedHooksForModule(VariableScope scope, String moduleName, Map<String, List<String>> moduleHooks); static Map<String, List<String>> getExecutedHooksForModule(VariableScope scope, String moduleName); static Integer getInteger(VariableScope scope, String name); static Integer getInteger(VariableScope scope, String name, Integer defaultValue); static T getObject(VariableScope scope, String name); @SuppressWarnings("unchecked") static T getObject(VariableScope scope, String name, T defaultValue); static T getFromJsonBinary(VariableScope scope, String name, Class<T> classOfT); static T getFromJsonBinary(VariableScope scope, String name, TypeReference<T> type); static T getFromJsonBinary(VariableScope scope, String name, TypeReference<T> type, T defaultValue); static void setAsJsonBinary(VariableScope scope, String name, Object value); static final String DEPLOY_ID_PREFIX; }### Answer:
@Test void testDetermineCurrentUserWithSetUser() { VariableHandling.set(execution, Variables.USER, EXAMPLE_USER); String determinedUser = StepsUtil.determineCurrentUser(execution); assertEquals(EXAMPLE_USER, determinedUser); }
@Test void testDetermineCurrentUserError() { Assertions.assertThrows(SLException.class, () -> StepsUtil.determineCurrentUser(execution)); } |
### Question:
PrepareToUndeployStep extends SyncFlowableStep { @Override protected String getStepErrorMessage(ProcessContext context) { return Messages.ERROR_DETECTING_COMPONENTS_TO_UNDEPLOY; } }### Answer:
@Test void testErrorMessage() { Assertions.assertEquals(Messages.ERROR_DETECTING_COMPONENTS_TO_UNDEPLOY, step.getStepErrorMessage(context)); } |
### Question:
JdbcUtil { public static void rollback(Connection connection) throws SQLException { if (connection == null) { return; } if (!connection.getAutoCommit()) { connection.rollback(); } } private JdbcUtil(); static void closeQuietly(ResultSet resultSet); static void closeQuietly(Statement statement); static void closeQuietly(Connection connection); static void logSQLException(SQLException exception); static void commit(Connection connection); static void rollback(Connection connection); }### Answer:
@Test void rollback() throws SQLException { Connection connection = Mockito.mock(Connection.class); Mockito.when(connection.getAutoCommit()) .thenReturn(false); JdbcUtil.rollback(connection); Mockito.verify(connection) .rollback(); }
@Test void rollbackWithNull() throws SQLException { JdbcUtil.rollback(null); }
@Test void rollbackWithAutoCommit() throws SQLException { Connection connection = Mockito.mock(Connection.class); Mockito.when(connection.getAutoCommit()) .thenReturn(true); JdbcUtil.rollback(connection); Mockito.verify(connection, Mockito.never()) .rollback(); } |
### Question:
CollectSystemParametersStep extends SyncFlowableStep { private String getDefaultDomain(CloudControllerClient client, ProcessContext context) { try { return client.getDefaultDomain() .getName(); } catch (CloudOperationException e) { if (e.getStatusCode() == HttpStatus.NOT_FOUND) { context.setVariable(Variables.MISSING_DEFAULT_DOMAIN, true); return DEFAULT_DOMAIN_PLACEHOLDER; } throw e; } } }### Answer:
@Test void testDefaultDomainNotFoundException() { prepareDescriptor("system-parameters/mtad.yaml"); prepareClient(); when(client.getDefaultDomain()).thenThrow(new CloudOperationException(HttpStatus.NOT_FOUND)); step.execute(execution); assertTrue(context.getVariable(Variables.MISSING_DEFAULT_DOMAIN)); DeploymentDescriptor descriptor = context.getVariable(Variables.DEPLOYMENT_DESCRIPTOR_WITH_SYSTEM_PARAMETERS); assertEquals(DEFAULT_DOMAIN_PLACEHOLDER, descriptor.getParameters() .get(SupportedParameters.DEFAULT_DOMAIN)); }
@Test void testDefaultDomainException() { when(client.getDefaultDomain()).thenThrow(new CloudOperationException(HttpStatus.GATEWAY_TIMEOUT)); assertThrows(SLException.class, () -> step.execute(execution)); } |
### Question:
StopAppStep extends SyncFlowableStepWithHooks implements BeforeStepHookPhaseProvider, AfterStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesBeforeStep(ProcessContext context) { List<HookPhase> hookPhases = getHookPhases(HookPhase.APPLICATION_BEFORE_STOP_IDLE, HookPhase.APPLICATION_BEFORE_STOP_LIVE, context); hookPhases.add(HookPhase.BEFORE_STOP); return hooksPhaseBuilder.buildHookPhases(hookPhases, context); } @Override StepPhase executeStepInternal(ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override List<HookPhase> getHookPhasesAfterStep(ProcessContext context); }### Answer:
@Test void testGetHooksBeforeStep() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.APPLICATION_BEFORE_STOP_LIVE, HookPhase.BEFORE_STOP), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_LIVE)); List<HookPhase> expectedPhases = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_LIVE); List<HookPhase> hookPhasesBeforeStep = step.getHookPhasesBeforeStep(context); assertEquals(expectedPhases, hookPhasesBeforeStep); }
@Test void testGetHooksBeforeStepWithBlueGreenProcess() { Mockito.when(processTypeParser.getProcessType(context.getExecution())) .thenReturn(ProcessType.BLUE_GREEN_DEPLOY); Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.APPLICATION_BEFORE_STOP_IDLE, HookPhase.BEFORE_STOP), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_IDLE)); List<HookPhase> expectedPhases = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_IDLE); List<HookPhase> hookPhasesBeforeStep = step.getHookPhasesBeforeStep(context); assertEquals(expectedPhases, hookPhasesBeforeStep); } |
### Question:
StopAppStep extends SyncFlowableStepWithHooks implements BeforeStepHookPhaseProvider, AfterStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesAfterStep(ProcessContext context) { List<HookPhase> hookPhases = getHookPhases(HookPhase.APPLICATION_AFTER_STOP_IDLE, HookPhase.APPLICATION_AFTER_STOP_LIVE, context); hookPhases.add(HookPhase.AFTER_STOP); return hooksPhaseBuilder.buildHookPhases(hookPhases, context); } @Override StepPhase executeStepInternal(ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override List<HookPhase> getHookPhasesAfterStep(ProcessContext context); }### Answer:
@Test void testGetHooksAfterStep() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.APPLICATION_AFTER_STOP_LIVE, HookPhase.AFTER_STOP), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_LIVE)); List<HookPhase> expectedPhases = List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_LIVE); List<HookPhase> hookPhasesBeforeStep = step.getHookPhasesAfterStep(context); assertEquals(expectedPhases, hookPhasesBeforeStep); }
@Test void testGetHooksAfterStepWithBlueGreenProcess() { Mockito.when(processTypeParser.getProcessType(context.getExecution())) .thenReturn(ProcessType.BLUE_GREEN_DEPLOY); Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.APPLICATION_AFTER_STOP_IDLE, HookPhase.AFTER_STOP), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_IDLE)); List<HookPhase> expectedPhases = List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_IDLE); List<HookPhase> hookPhasesBeforeStep = step.getHookPhasesAfterStep(context); assertEquals(expectedPhases, hookPhasesBeforeStep); } |
### Question:
PollStageAppStatusExecution implements AsyncExecution { @Override public String getPollingErrorMessage(ProcessContext context) { CloudApplication application = context.getVariable(Variables.APP_TO_PROCESS); return MessageFormat.format(Messages.ERROR_STAGING_APP_0, application.getName()); } PollStageAppStatusExecution(RecentLogsRetriever recentLogsRetriever, ApplicationStager applicationStager); @Override AsyncExecutionState execute(ProcessContext context); @Override String getPollingErrorMessage(ProcessContext context); }### Answer:
@Test void testPollingErrorMessage() { context.setVariable(Variables.APP_TO_PROCESS, createCloudApplication("anatz")); String pollingErrorMessage = step.getPollingErrorMessage(context); Assertions.assertEquals("Error staging application \"anatz\"", pollingErrorMessage); } |
### Question:
DeleteApplicationStep extends UndeployAppStep { private void deleteApplication(CloudControllerClient client, String applicationName) { getStepLogger().info(Messages.DELETING_APP, applicationName); client.deleteApplication(applicationName); getStepLogger().debug(Messages.APP_DELETED, applicationName); } }### Answer:
@Test void testApplicationNotFoundExceptionThrown() { Mockito.doThrow(new CloudOperationException(HttpStatus.NOT_FOUND)) .when(client) .deleteApplication(anyString()); context.setVariable(Variables.APP_TO_PROCESS, createCloudApplication("test-app")); step.execute(execution); assertStepFinishedSuccessfully(); }
@Test void testBadGatewayExceptionThrown() { Mockito.doThrow(new CloudOperationException(HttpStatus.BAD_GATEWAY)) .when(client) .deleteApplication(anyString()); context.setVariable(Variables.APP_TO_PROCESS, createCloudApplication("test-app")); Assertions.assertThrows(SLException.class, () -> step.execute(execution)); } |
### Question:
StopApplicationUndeploymentStep extends UndeployAppStep implements BeforeStepHookPhaseProvider, AfterStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesBeforeStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Arrays.asList(HookPhase.BEFORE_STOP, HookPhase.APPLICATION_BEFORE_STOP_LIVE), context); } @Override StepPhase undeployApplication(CloudControllerClient client, CloudApplication cloudApplicationToUndeploy,
ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override List<HookPhase> getHookPhasesAfterStep(ProcessContext context); }### Answer:
@Test void testGetHookPhaseBefore() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.BEFORE_STOP, HookPhase.APPLICATION_BEFORE_STOP_LIVE), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_LIVE)); List<HookPhase> expectedHooks = List.of(HookPhase.BLUE_GREEN_APPLICATION_BEFORE_STOP_LIVE, HookPhase.APPLICATION_BEFORE_STOP_LIVE); List<HookPhase> hookPhasesBeforeStep = ((StopApplicationUndeploymentStep) step).getHookPhasesBeforeStep(context); assertEquals(expectedHooks, hookPhasesBeforeStep); } |
### Question:
StopApplicationUndeploymentStep extends UndeployAppStep implements BeforeStepHookPhaseProvider, AfterStepHookPhaseProvider { @Override public List<HookPhase> getHookPhasesAfterStep(ProcessContext context) { return hooksPhaseBuilder.buildHookPhases(Arrays.asList(HookPhase.AFTER_STOP, HookPhase.APPLICATION_AFTER_STOP_LIVE), context); } @Override StepPhase undeployApplication(CloudControllerClient client, CloudApplication cloudApplicationToUndeploy,
ProcessContext context); @Override List<HookPhase> getHookPhasesBeforeStep(ProcessContext context); @Override List<HookPhase> getHookPhasesAfterStep(ProcessContext context); }### Answer:
@Test void testGetHookPhaseAfter() { Mockito.when(hooksPhaseBuilder.buildHookPhases(List.of(HookPhase.AFTER_STOP, HookPhase.APPLICATION_AFTER_STOP_LIVE), context)) .thenReturn(List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_LIVE)); List<HookPhase> expectedHooks = List.of(HookPhase.BLUE_GREEN_APPLICATION_AFTER_STOP_LIVE, HookPhase.APPLICATION_AFTER_STOP_LIVE); List<HookPhase> hookPhasesBeforeStep = ((StopApplicationUndeploymentStep) step).getHookPhasesAfterStep(context); assertEquals(expectedHooks, hookPhasesBeforeStep); } |
### Question:
RetryProcessAdditionalAction implements AdditionalProcessAction { @Override public void executeAdditionalProcessAction(String processInstanceId) { List<String> failedActivityIds = findFailedActivityIds(processInstanceId); for (String failedActivityId : failedActivityIds) { progressMessageService.createQuery() .processId(processInstanceId) .taskId(failedActivityId) .type(ProgressMessageType.ERROR) .delete(); } } @Inject RetryProcessAdditionalAction(FlowableFacade flowableFacade, ProgressMessageService progressMessageService); @Override void executeAdditionalProcessAction(String processInstanceId); @Override Action getApplicableAction(); }### Answer:
@Test void testExecuteAdditionalAction() { retryProcessAdditionalAction.executeAdditionalProcessAction(PROCESS_GUID); Mockito.verify(progressMessageQuery, times(2)) .delete(); } |
### Question:
FlowableFacade { public void shutdownJobExecutor() { LOGGER.info(Messages.SHUTTING_DOWN_FLOWABLE_JOB_EXECUTOR); AsyncExecutor asyncExecutor = processEngine.getProcessEngineConfiguration() .getAsyncExecutor(); asyncExecutor.shutdown(); } @Inject FlowableFacade(ProcessEngine processEngine); ProcessInstance startProcess(String processDefinitionKey, Map<String, Object> variables); String getProcessInstanceId(String executionId); String getCurrentTaskId(String executionId); ProcessInstance getProcessInstance(String processId); boolean hasDeadLetterJobs(String processId); List<String> getHistoricSubProcessIds(String correlationId); HistoricProcessInstance getHistoricProcessById(String processInstanceId); HistoricVariableInstance getHistoricVariableInstance(String processInstanceId, String variableName); List<String> getActiveHistoricSubProcessIds(String correlationId); void executeJob(String processInstanceId); void trigger(String executionId, Map<String, Object> variables); void deleteProcessInstance(String processInstanceId, String deleteReason); boolean isProcessInstanceAtReceiveTask(String processInstanceId); List<Execution> findExecutionsAtReceiveTask(String processInstanceId); List<Execution> getActiveProcessExecutions(String processInstanceId); void suspendProcessInstance(String processInstanceId); void shutdownJobExecutor(); boolean isJobExecutorActive(); ProcessEngine getProcessEngine(); List<ProcessInstance> findAllRunningProcessInstanceStartedBefore(Date startedBefore); }### Answer:
@Test void testAsyncExecutorMethodsAreCalled() { flowableFacade.shutdownJobExecutor(); Mockito.verify(mockedAsyncExecutor, Mockito.times(1)) .shutdown(); } |
### Question:
SetRetryPhaseAdditionalProcessAction implements AdditionalProcessAction { @Override public void executeAdditionalProcessAction(String processInstanceId) { flowableFacade.getActiveProcessExecutions(processInstanceId) .stream() .map(this::toExecutionEntityImpl) .filter(executionEntityImpl -> executionEntityImpl.getDeadLetterJobCount() > 0) .map(ExecutionEntityImpl::getProcessInstanceId) .forEach(this::setRetryPhaseForProcess); } @Inject SetRetryPhaseAdditionalProcessAction(FlowableFacade flowableFacade); @Override void executeAdditionalProcessAction(String processInstanceId); @Override Action getApplicableAction(); }### Answer:
@Test void testExecuteAdditionalProcessAction() { setRetryPhaseAdditionalProcessAction.executeAdditionalProcessAction(PROCESS_GUID); Mockito.verify(runtimeService) .setVariable(EXECUTION_WITH_DEADLETTER_JOBS_PROCESS_ID, Variables.STEP_PHASE.getName(), StepPhase.RETRY.name()); Mockito.verify(runtimeService, never()) .setVariable(EXECUTION_WITHOUT_DEADLETTER_JOBS_PROCESS_ID, Variables.STEP_PHASE.getName(), StepPhase.RETRY.name()); } |
### Question:
ServiceUpdater extends CloudServiceOperator { public MethodExecution<String> updateServicePlan(CloudControllerClient client, String serviceName, String servicePlan) { return new CustomControllerClientErrorHandler().handleErrorsOrReturnResult(() -> attemptToUpdateServicePlan(client, serviceName, servicePlan)); } @Inject ServiceUpdater(WebClientFactory webClientFactory); MethodExecution<String> updateServicePlanQuietly(CloudControllerClient client, String serviceName, String servicePlan); MethodExecution<String> updateServicePlan(CloudControllerClient client, String serviceName, String servicePlan); MethodExecution<String> updateServiceTagsQuietly(CloudControllerClient client, String serviceName, List<String> serviceTags); MethodExecution<String> updateServiceTags(CloudControllerClient client, String serviceName, List<String> serviceTags); MethodExecution<String> updateServiceParametersQuietly(CloudControllerClient client, String serviceName,
Map<String, Object> parameters); MethodExecution<String> updateServiceParameters(CloudControllerClient client, String serviceName,
Map<String, Object> parameters); }### Answer:
@Test void testUpdateServicePlan1() { CloudControllerClient client = getMockedClient(); Mockito.when(client.getServiceInstance(EXISTING_SERVICE_INSTANCE_NAME)) .thenReturn(EXISTING_SERVICE_INSTANCE); serviceUpdater.updateServicePlan(client, EXISTING_SERVICE_INSTANCE_NAME, "v3.0-small"); validatePlanUpdate("8e886beb-85cb-4455-9474-b6dfda36ffeb"); }
@Test void testUpdateServicePlan2() { CloudControllerClient client = getMockedClient(); Mockito.when(client.getServiceInstance(EXISTING_SERVICE_INSTANCE_NAME)) .thenReturn(EXISTING_SERVICE_INSTANCE); try { serviceUpdater.updateServicePlan(client, EXISTING_SERVICE_INSTANCE_NAME, "v3.0-large"); } catch (CloudOperationException e) { assertEquals("404 Not Found: Could not create service instance \"foo\". Service plan \"v3.0-large\" from service offering \"mongodb\" was not found.", e.getMessage()); } }
@Test void testUpdateServicePlan3() { CloudControllerClient client = getMockedClient(); Mockito.when(client.getServiceInstance(EXISTING_SERVICE_INSTANCE_NAME)) .thenThrow(new CloudOperationException(HttpStatus.NOT_FOUND, HttpStatus.NOT_FOUND.getReasonPhrase(), "Service \"foo\" was not found!")); try { serviceUpdater.updateServicePlan(client, EXISTING_SERVICE_INSTANCE_NAME, "v3.0-small"); } catch (CloudOperationException e) { assertEquals("404 Not Found: Service \"foo\" was not found!", e.getMessage()); } } |
### Question:
RecentLogsRetriever { public List<ApplicationLog> getRecentLogs(CloudControllerClient client, String appName, LogsOffset offset) { List<ApplicationLog> appLogs = client.getRecentLogs(appName); if (offset == null) { return appLogs; } return appLogs.stream() .filter(appLog -> isLogNew(appLog, offset)) .collect(Collectors.toList()); } List<ApplicationLog> getRecentLogsSafely(CloudControllerClient client, String appName, LogsOffset offset); List<ApplicationLog> getRecentLogs(CloudControllerClient client, String appName, LogsOffset offset); }### Answer:
@Test void testGetRecentLogsWithError() { Mockito.when(client.getRecentLogs(APP_NAME)) .thenThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Something fails")); tester.test(() -> recentLogsRetriever.getRecentLogs(client, APP_NAME, null), new Expectation(Expectation.Type.EXCEPTION, "500 Something fails")); }
@Test void testGetRecentLogsWithNoPriorOffset() { Mockito.when(client.getRecentLogs(APP_NAME)) .thenReturn(List.of(createAppLog(1, ""))); assertEquals(List.of(createAppLog(1, "")), recentLogsRetriever.getRecentLogs(client, APP_NAME, null)); }
@Test void testGetRecentLogsWithOffsetReturnsNoLogs() { LogsOffset offset = createLogsOffset(1, ""); Mockito.when(client.getRecentLogs(APP_NAME)) .thenReturn(List.of(createAppLog(0, ""))); assertTrue(recentLogsRetriever.getRecentLogs(client, APP_NAME, offset) .isEmpty()); }
@Test void testGetRecentLogsWithOffsetSameMessageReturnsNoLogs() { LogsOffset offset = createLogsOffset(1, "msg"); Mockito.when(client.getRecentLogs(APP_NAME)) .thenReturn(List.of(createAppLog(1, "msg"))); assertTrue(recentLogsRetriever.getRecentLogs(client, APP_NAME, offset) .isEmpty()); }
@Test void testGetRecentLogsWithOffsetReturnsFilteredLogs() { LogsOffset offset = createLogsOffset(1, ""); Mockito.when(client.getRecentLogs(APP_NAME)) .thenReturn(List.of(createAppLog(1, ""), createAppLog(2, ""))); assertEquals(List.of(createAppLog(2, "")), recentLogsRetriever.getRecentLogs(client, APP_NAME, offset)); }
@Test void testGetRecentLogsWithOffsetSameTimestampReturnsFilteredLogs() { LogsOffset offset = createLogsOffset(1, "msg"); Mockito.when(client.getRecentLogs(APP_NAME)) .thenReturn(List.of(createAppLog(1, "msg"), createAppLog(1, "msg1"))); assertEquals(List.of(createAppLog(1, "msg1")), recentLogsRetriever.getRecentLogs(client, APP_NAME, offset)); }
@Test void testGetRecentLogsWithOffsetSameMessageReturnsFilteredLogs() { LogsOffset offset = createLogsOffset(1, "msg1"); Mockito.when(client.getRecentLogs(APP_NAME)) .thenReturn(List.of(createAppLog(1, "msg"), createAppLog(1, "msg1"))); assertEquals(List.of(createAppLog(1, "msg")), recentLogsRetriever.getRecentLogs(client, APP_NAME, offset)); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.