method2testcases
stringlengths
118
3.08k
### Question: IdGenerator { public static long newLinearId(AtomicLong longValue) { long candiateId = longValue.incrementAndGet(); if (candiateId > IdGenerator.MAX) { longValue.set(1L); candiateId = longValue.longValue(); } return candiateId; } static long newRandomId(@Nullable Set<Long> existingIds); static long newLinearId(AtomicLong longValue); static final long MIN; static final long MAX; }### Answer: @Test public void testNewLinearId() { AtomicLong id = new AtomicLong(0); assertThat(IdGenerator.newLinearId(id)).isEqualTo(1); assertThat(IdGenerator.newLinearId(id)).isEqualTo(2); id.set(IdGenerator.MAX - 1L); assertThat(IdGenerator.newLinearId(id)).isEqualTo(IdGenerator.MAX); assertThat(IdGenerator.newLinearId(id)).isEqualTo(1L); }
### Question: CollectionHelper { @SafeVarargs @Nullable public static <T> List<T> toList(@Nullable T... arguments) { if (arguments != null) { if (arguments.length == 1) { return Collections.singletonList(arguments[0]); } if (arguments.length > 1) { return Arrays.asList(arguments); } } return null; } @SafeVarargs @Nullable static List<T> toList(@Nullable T... arguments); @SuppressWarnings("unchecked") @Nullable static List<Object> toList(@Nullable Collection<T> collection); @Nullable static Set<Long> toSet(@Nullable Collection<Long> collection); }### Answer: @Test public void testToListTArray() { assertThat(CollectionHelper.toList()).isNull(); assertThat(CollectionHelper.toList(1)).isInstanceOf(List.class) .containsExactly(1); assertThat(CollectionHelper.toList(1, 2, 3)).isInstanceOf(List.class) .containsExactly(1, 2, 3); } @Test public void testToListCollectionOfT() { assertThat(CollectionHelper.toList((List<String>) null)).isNull(); assertThat(CollectionHelper.toList(Arrays.asList(1))).isInstanceOf(List.class) .containsExactly(1); assertThat(CollectionHelper.toList(Arrays.asList(1, 2, 3))) .isInstanceOf(List.class).containsExactly(1, 2, 3); Set<Long> set = new HashSet<>(); set.add(11L); set.add(22L); assertThat(CollectionHelper.toList(set)).isInstanceOf(List.class) .containsOnly(11L, 22L); }
### Question: CollectionHelper { @Nullable public static Set<Long> toSet(@Nullable Collection<Long> collection) { if (collection != null) { if (collection instanceof Set) { return (Set<Long>) collection; } return new HashSet<>(collection); } return null; } @SafeVarargs @Nullable static List<T> toList(@Nullable T... arguments); @SuppressWarnings("unchecked") @Nullable static List<Object> toList(@Nullable Collection<T> collection); @Nullable static Set<Long> toSet(@Nullable Collection<Long> collection); }### Answer: @Test public void testToSet() { assertThat(CollectionHelper.toSet((Set<Long>) null)).isNull(); Set<Long> set = new HashSet<>(); set.add(33L); set.add(44L); assertThat(CollectionHelper.toSet(set)).isInstanceOf(Set.class).containsOnly(33L, 44L); assertThat(CollectionHelper.toSet(Arrays.asList(1L))).isInstanceOf(Set.class) .containsExactly(1L); assertThat(CollectionHelper.toSet(Arrays.asList(1L, 2L, 3L))) .isInstanceOf(Set.class).containsExactly(1L, 2L, 3L); }
### Question: RegisteredMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); generator.writeNumber(this.registrationId); } RegisteredMessage(long requestId, long registrationId); RegisteredMessage(RegisterMessage registerMessage, long registrationId); static RegisteredMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getRegistrationId(); @Override String toString(); }### Answer: @Test public void serializeTest() { RegisteredMessage registeredMessage = new RegisteredMessage(11, 127172L); assertThat(registeredMessage.getCode()).isEqualTo(65); assertThat(registeredMessage.getRequestId()).isEqualTo(11); assertThat(registeredMessage.getRegistrationId()).isEqualTo(127172L); String json = serializeToJson(registeredMessage); assertThat(json).isEqualTo("[65,11,127172]"); }
### Question: RegisteredMessage extends WampMessage { public static RegisteredMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); jp.nextToken(); long registration = jp.getLongValue(); return new RegisteredMessage(request, registration); } RegisteredMessage(long requestId, long registrationId); RegisteredMessage(RegisterMessage registerMessage, long registrationId); static RegisteredMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getRegistrationId(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[65, 25349185, 2103333224]"; RegisteredMessage registeredMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(registeredMessage.getCode()).isEqualTo(65); assertThat(registeredMessage.getRequestId()).isEqualTo(25349185L); assertThat(registeredMessage.getRegistrationId()).isEqualTo(2103333224L); }
### Question: UnsubscribedMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); if (this.subscriptionId != null || this.reason != null) { generator.writeStartObject(); if (this.reason != null) { generator.writeStringField("reason", this.reason); } if (this.subscriptionId != null) { generator.writeNumberField("subscription", this.subscriptionId); } generator.writeEndObject(); } } UnsubscribedMessage(long requestId); UnsubscribedMessage(long requestId, @Nullable Long subscriptionId, @Nullable String reason); UnsubscribedMessage(UnsubscribeMessage unsubscribeMessage); static UnsubscribedMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); @Nullable Long getSubscriptionId(); @Nullable String getReason(); @Override String toString(); }### Answer: @Test public void serializeTest() { UnsubscribedMessage unsubscribedMessage = new UnsubscribedMessage(1); assertThat(unsubscribedMessage.getCode()).isEqualTo(35); assertThat(unsubscribedMessage.getRequestId()).isEqualTo(1); assertThat(unsubscribedMessage.getSubscriptionId()).isNull(); assertThat(unsubscribedMessage.getReason()).isNull(); String json = serializeToJson(unsubscribedMessage); assertThat(json).isEqualTo("[35,1]"); unsubscribedMessage = new UnsubscribedMessage(2, 1208L, "removed"); assertThat(unsubscribedMessage.getCode()).isEqualTo(35); assertThat(unsubscribedMessage.getRequestId()).isEqualTo(2); assertThat(unsubscribedMessage.getSubscriptionId()).isEqualTo(1208L); assertThat(unsubscribedMessage.getReason()).isEqualTo("removed"); json = serializeToJson(unsubscribedMessage); assertThat(json) .isEqualTo("[35,2,{\"reason\":\"removed\",\"subscription\":1208}]"); }
### Question: UnsubscribedMessage extends WampMessage { public static UnsubscribedMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); Long subscriptionId = null; String reason = null; JsonToken token = jp.nextToken(); if (token == JsonToken.START_OBJECT) { Map<String, Object> details = ParserUtil.readObject(jp); reason = (String) details.get("reason"); Object subscriptionObj = details.get("subscription"); if (subscriptionObj != null) { subscriptionId = ((Number) subscriptionObj).longValue(); } } return new UnsubscribedMessage(request, subscriptionId, reason); } UnsubscribedMessage(long requestId); UnsubscribedMessage(long requestId, @Nullable Long subscriptionId, @Nullable String reason); UnsubscribedMessage(UnsubscribeMessage unsubscribeMessage); static UnsubscribedMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); @Nullable Long getSubscriptionId(); @Nullable String getReason(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[35, 85346237]"; UnsubscribedMessage unsubscribedMessage = WampMessage .deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(unsubscribedMessage.getCode()).isEqualTo(35); assertThat(unsubscribedMessage.getRequestId()).isEqualTo(85346237L); assertThat(unsubscribedMessage.getSubscriptionId()).isNull(); assertThat(unsubscribedMessage.getReason()).isNull(); json = "[35, 0, {\"subscription\":1213,\"reason\":\"the reason\"}]"; unsubscribedMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(unsubscribedMessage.getCode()).isEqualTo(35); assertThat(unsubscribedMessage.getRequestId()).isEqualTo(0); assertThat(unsubscribedMessage.getSubscriptionId()).isEqualTo(1213L); assertThat(unsubscribedMessage.getReason()).isEqualTo("the reason"); }
### Question: PublishedMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); generator.writeNumber(this.publicationId); } PublishedMessage(long requestId, long publicationId); PublishedMessage(PublishMessage publishMessage, long publicationId); static PublishedMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getPublicationId(); @Override String toString(); }### Answer: @Test public void serializeTest() { PublishedMessage publishedMessage = new PublishedMessage(44, 121); assertThat(publishedMessage.getCode()).isEqualTo(17); assertThat(publishedMessage.getRequestId()).isEqualTo(44); assertThat(publishedMessage.getPublicationId()).isEqualTo(121); String json = serializeToJson(publishedMessage); assertThat(json).isEqualTo("[17,44,121]"); }
### Question: PublishedMessage extends WampMessage { public static PublishedMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); jp.nextToken(); long subscription = jp.getLongValue(); return new PublishedMessage(request, subscription); } PublishedMessage(long requestId, long publicationId); PublishedMessage(PublishMessage publishMessage, long publicationId); static PublishedMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getPublicationId(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[17, 239714735, 4429313566]"; PublishedMessage publishedMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(publishedMessage.getCode()).isEqualTo(17); assertThat(publishedMessage.getRequestId()).isEqualTo(239714735L); assertThat(publishedMessage.getPublicationId()).isEqualTo(4429313566L); }
### Question: RegisterMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); generator.writeStartObject(); if (this.discloseCaller) { generator.writeBooleanField("disclose_caller", this.discloseCaller); } generator.writeEndObject(); generator.writeString(this.procedure); } RegisterMessage(long requestId, String procedure); RegisterMessage(long requestId, String procedure, boolean discloseCaller); static RegisterMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); String getProcedure(); boolean isDiscloseCaller(); @Override String toString(); static final int CODE; }### Answer: @Test public void serializeTest() { RegisterMessage registerMessage = new RegisterMessage(11, "bean.method"); assertThat(registerMessage.getCode()).isEqualTo(64); assertThat(registerMessage.getRequestId()).isEqualTo(11); assertThat(registerMessage.getProcedure()).isEqualTo("bean.method"); assertThat(registerMessage.isDiscloseCaller()).isFalse(); String json = serializeToJson(registerMessage); assertThat(json).isEqualTo("[64,11,{},\"bean.method\"]"); registerMessage = new RegisterMessage(927639114088448L, "com.maypp.add2", true); assertThat(registerMessage.getCode()).isEqualTo(64); assertThat(registerMessage.getRequestId()).isEqualTo(927639114088448L); assertThat(registerMessage.getProcedure()).isEqualTo("com.maypp.add2"); assertThat(registerMessage.isDiscloseCaller()).isTrue(); json = serializeToJson(registerMessage); assertThat(json).isEqualTo( "[64,927639114088448,{\"disclose_caller\":true},\"com.maypp.add2\"]"); }
### Question: RegisterMessage extends WampMessage { public static RegisterMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); boolean discloseCaller = false; jp.nextToken(); Map<String, Object> options = ParserUtil.readObject(jp); if (options != null) { discloseCaller = (boolean) options.getOrDefault("disclose_caller", false); } jp.nextToken(); String procedure = jp.getValueAsString(); return new RegisterMessage(request, procedure, discloseCaller); } RegisterMessage(long requestId, String procedure); RegisterMessage(long requestId, String procedure, boolean discloseCaller); static RegisterMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); String getProcedure(); boolean isDiscloseCaller(); @Override String toString(); static final int CODE; }### Answer: @Test public void deserializeTest() throws IOException { String json = "[64, 25349185, {}, \"com.myapp.myprocedure\"]"; RegisterMessage registerMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(registerMessage.getCode()).isEqualTo(64); assertThat(registerMessage.getRequestId()).isEqualTo(25349185L); assertThat(registerMessage.getProcedure()).isEqualTo("com.myapp.myprocedure"); assertThat(registerMessage.isDiscloseCaller()).isFalse(); json = "[64, 927639114088448, {\"disclose_caller\":true},\"com.maypp.add2\"]"; registerMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(registerMessage.getCode()).isEqualTo(64); assertThat(registerMessage.getRequestId()).isEqualTo(927639114088448L); assertThat(registerMessage.getProcedure()).isEqualTo("com.maypp.add2"); assertThat(registerMessage.isDiscloseCaller()).isTrue(); }
### Question: UnsubscribeMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); generator.writeNumber(this.subscriptionId); } UnsubscribeMessage(long requestId, long subscriptionId); static UnsubscribeMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getSubscriptionId(); @Override String toString(); }### Answer: @Test public void serializeTest() { UnsubscribeMessage unsubscribeMessage = new UnsubscribeMessage(1, 2); assertThat(unsubscribeMessage.getCode()).isEqualTo(34); assertThat(unsubscribeMessage.getRequestId()).isEqualTo(1); assertThat(unsubscribeMessage.getSubscriptionId()).isEqualTo(2); String json = serializeToJson(unsubscribeMessage); assertThat(json).isEqualTo("[34,1,2]"); }
### Question: UnsubscribeMessage extends WampMessage { public static UnsubscribeMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); jp.nextToken(); long subscription = jp.getLongValue(); return new UnsubscribeMessage(request, subscription); } UnsubscribeMessage(long requestId, long subscriptionId); static UnsubscribeMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getSubscriptionId(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[34, 85346237, 5512315355]"; UnsubscribeMessage unsubscribeMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(unsubscribeMessage.getCode()).isEqualTo(34); assertThat(unsubscribeMessage.getRequestId()).isEqualTo(85346237L); assertThat(unsubscribeMessage.getSubscriptionId()).isEqualTo(5512315355L); }
### Question: UnregisteredMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); if (this.registrationId != null || this.reason != null) { generator.writeStartObject(); if (this.reason != null) { generator.writeStringField("reason", this.reason); } if (this.registrationId != null) { generator.writeNumberField("registration", this.registrationId); } generator.writeEndObject(); } } UnregisteredMessage(long requestId); UnregisteredMessage(long requestId, @Nullable Long registrationId, @Nullable String reason); UnregisteredMessage(UnregisterMessage unregisterMessage); static UnregisteredMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); @Nullable Long getRegistrationId(); @Nullable String getReason(); @Override String toString(); }### Answer: @Test public void serializeTest() { UnregisteredMessage unregisteredMessage = new UnregisteredMessage(13); assertThat(unregisteredMessage.getCode()).isEqualTo(67); assertThat(unregisteredMessage.getRequestId()).isEqualTo(13); assertThat(unregisteredMessage.getRegistrationId()).isNull(); assertThat(unregisteredMessage.getReason()).isNull(); String json = serializeToJson(unregisteredMessage); assertThat(json).isEqualTo("[67,13]"); unregisteredMessage = new UnregisteredMessage(13, 333L, "a reason"); assertThat(unregisteredMessage.getCode()).isEqualTo(67); assertThat(unregisteredMessage.getRequestId()).isEqualTo(13); assertThat(unregisteredMessage.getRegistrationId()).isEqualTo(333); assertThat(unregisteredMessage.getReason()).isEqualTo("a reason"); json = serializeToJson(unregisteredMessage); assertThat(json) .isEqualTo("[67,13,{\"reason\":\"a reason\",\"registration\":333}]"); }
### Question: UnregisteredMessage extends WampMessage { public static UnregisteredMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); Long registrationId = null; String reason = null; JsonToken token = jp.nextToken(); if (token == JsonToken.START_OBJECT) { Map<String, Object> details = ParserUtil.readObject(jp); reason = (String) details.get("reason"); Object registrationObj = details.get("registration"); if (registrationObj != null) { registrationId = ((Number) registrationObj).longValue(); } } return new UnregisteredMessage(request, registrationId, reason); } UnregisteredMessage(long requestId); UnregisteredMessage(long requestId, @Nullable Long registrationId, @Nullable String reason); UnregisteredMessage(UnregisterMessage unregisterMessage); static UnregisteredMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); @Nullable Long getRegistrationId(); @Nullable String getReason(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[67, 788923562]"; UnregisteredMessage unregisteredMessage = WampMessage .deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(unregisteredMessage.getCode()).isEqualTo(67); assertThat(unregisteredMessage.getRequestId()).isEqualTo(788923562L); assertThat(unregisteredMessage.getRegistrationId()).isNull(); assertThat(unregisteredMessage.getReason()).isNull(); json = "[67, 0, {\"registration\":334,\"reason\":\"another reason\"}]"; unregisteredMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(unregisteredMessage.getCode()).isEqualTo(67); assertThat(unregisteredMessage.getRequestId()).isEqualTo(0); assertThat(unregisteredMessage.getRegistrationId()).isEqualTo(334); assertThat(unregisteredMessage.getReason()).isEqualTo("another reason"); }
### Question: UnregisterMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); generator.writeNumber(this.registrationId); } UnregisterMessage(long requestId, long registrationId); static UnregisterMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getRegistrationId(); @Override String toString(); }### Answer: @Test public void serializeTest() { UnregisterMessage unregisterMessage = new UnregisterMessage(14, 23); assertThat(unregisterMessage.getCode()).isEqualTo(66); assertThat(unregisterMessage.getRequestId()).isEqualTo(14); assertThat(unregisterMessage.getRegistrationId()).isEqualTo(23); String json = serializeToJson(unregisterMessage); assertThat(json).isEqualTo("[66,14,23]"); }
### Question: UnregisterMessage extends WampMessage { public static UnregisterMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); jp.nextToken(); long registration = jp.getLongValue(); return new UnregisterMessage(request, registration); } UnregisterMessage(long requestId, long registrationId); static UnregisterMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getRegistrationId(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[66, 788923562, 2103333224]"; UnregisterMessage unregisterMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(unregisterMessage.getCode()).isEqualTo(66); assertThat(unregisterMessage.getRequestId()).isEqualTo(788923562L); assertThat(unregisterMessage.getRegistrationId()).isEqualTo(2103333224L); }
### Question: GoodbyeMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeStartObject(); if (this.message != null) { generator.writeStringField("message", this.message); } generator.writeEndObject(); generator.writeString(this.reason); } GoodbyeMessage(WampError reason, @Nullable String message); GoodbyeMessage(WampError reason); private GoodbyeMessage(String reason, @Nullable String message); static GoodbyeMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); String getReason(); @Nullable String getMessage(); @Override String toString(); }### Answer: @Test public void serializeTest() { GoodbyeMessage goodbyeMessage = new GoodbyeMessage(WampError.GOODBYE_AND_OUT, "theMessage"); assertThat(goodbyeMessage.getCode()).isEqualTo(6); assertThat(goodbyeMessage.getMessage()).isEqualTo("theMessage"); assertThat(goodbyeMessage.getReason()) .isEqualTo(WampError.GOODBYE_AND_OUT.getExternalValue()); String json = serializeToJson(goodbyeMessage); assertThat(json).isEqualTo( "[6,{\"message\":\"theMessage\"},\"wamp.error.goodbye_and_out\"]"); goodbyeMessage = new GoodbyeMessage(WampError.NO_SUCH_PROCEDURE); json = serializeToJson(goodbyeMessage); assertThat(json).isEqualTo("[6,{},\"wamp.error.no_such_procedure\"]"); }
### Question: GoodbyeMessage extends WampMessage { public static GoodbyeMessage deserialize(JsonParser jp) throws IOException { String msg = null; jp.nextToken(); Map<String, Object> details = ParserUtil.readObject(jp); if (details != null) { msg = (String) details.get("message"); } jp.nextToken(); return new GoodbyeMessage(jp.getValueAsString(), msg); } GoodbyeMessage(WampError reason, @Nullable String message); GoodbyeMessage(WampError reason); private GoodbyeMessage(String reason, @Nullable String message); static GoodbyeMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); String getReason(); @Nullable String getMessage(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[6, {\"message\": \"The host is shutting down now.\"},\"wamp.error.system_shutdown\"]"; GoodbyeMessage goodbyeMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(goodbyeMessage.getCode()).isEqualTo(6); assertThat(goodbyeMessage.getMessage()) .isEqualTo("The host is shutting down now."); assertThat(goodbyeMessage.getReason()).isEqualTo("wamp.error.system_shutdown"); json = "[6,{},\"wamp.error.no_such_procedure\"]"; goodbyeMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(goodbyeMessage.getCode()).isEqualTo(6); assertThat(goodbyeMessage.getMessage()).isNull(); assertThat(goodbyeMessage.getReason()).isEqualTo("wamp.error.no_such_procedure"); }
### Question: HelloMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeString(this.realm); generator.writeStartObject(); generator.writeObjectFieldStart("roles"); for (WampRole wampRole : this.roles) { generator.writeObjectFieldStart(wampRole.getRole()); if (wampRole.hasFeatures()) { generator.writeObjectFieldStart("features"); for (String feature : wampRole.getFeatures()) { generator.writeBooleanField(feature, true); } generator.writeEndObject(); } generator.writeEndObject(); } generator.writeEndObject(); generator.writeEndObject(); } HelloMessage(@Nullable String realm, List<WampRole> roles); @SuppressWarnings("unchecked") static HelloMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); @Nullable String getRealm(); List<WampRole> getRoles(); @Override String toString(); }### Answer: @Test public void serializeTest() { List<WampRole> roles = createRoles(); HelloMessage helloMessage = new HelloMessage("aRealm", roles); assertThat(helloMessage.getCode()).isEqualTo(1); assertThat(helloMessage.getRealm()).isEqualTo("aRealm"); assertThat(helloMessage.getRoles()).isEqualTo(roles); String json = serializeToJson(helloMessage); assertThat(json).isEqualTo( "[1,\"aRealm\",{\"roles\":{\"publisher\":{\"features\":{\"publisher_exclusion\":true}},\"subscriber\":{\"features\":{\"subscriber_blackwhite_listing\":true}}}}]"); }
### Question: SubscribedMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeNumber(this.requestId); generator.writeNumber(this.subscriptionId); } SubscribedMessage(long requestId, long subscriptionId); SubscribedMessage(SubscribeMessage subscribeMessage, long subscriptionId); static SubscribedMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getSubscriptionId(); @Override String toString(); }### Answer: @Test public void serializeTest() { SubscribedMessage subscribedMessage = new SubscribedMessage(1, 2); assertThat(subscribedMessage.getCode()).isEqualTo(33); assertThat(subscribedMessage.getRequestId()).isEqualTo(1); assertThat(subscribedMessage.getSubscriptionId()).isEqualTo(2); String json = serializeToJson(subscribedMessage); assertThat(json).isEqualTo("[33,1,2]"); }
### Question: SubscribedMessage extends WampMessage { public static SubscribedMessage deserialize(JsonParser jp) throws IOException { jp.nextToken(); long request = jp.getLongValue(); jp.nextToken(); long subscription = jp.getLongValue(); return new SubscribedMessage(request, subscription); } SubscribedMessage(long requestId, long subscriptionId); SubscribedMessage(SubscribeMessage subscribeMessage, long subscriptionId); static SubscribedMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); long getRequestId(); long getSubscriptionId(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[33, 713845233, 5512315355]"; SubscribedMessage subscribedMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(subscribedMessage.getCode()).isEqualTo(33); assertThat(subscribedMessage.getRequestId()).isEqualTo(713845233L); assertThat(subscribedMessage.getSubscriptionId()).isEqualTo(5512315355L); }
### Question: ParserUtil { @Nullable public static List<Object> readArray(JsonParser jp) throws IOException { if (jp.currentToken() != JsonToken.START_ARRAY) { return null; } List<Object> result = new ArrayList<>(); JsonToken token = jp.nextToken(); while (token != JsonToken.END_ARRAY) { if (token == JsonToken.START_ARRAY) { result.add(readArray(jp)); } else if (token == JsonToken.START_OBJECT) { result.add(readObject(jp)); } else { result.add(getValue(jp)); } token = jp.nextToken(); } return result; } @Nullable static List<Object> readArray(JsonParser jp); @Nullable static Map<String, Object> readObject(JsonParser jp); }### Answer: @SuppressWarnings("resource") @Test public void testReadArray() throws JsonParseException, IOException { ObjectMapper om = new ObjectMapper(); JsonParser jp = om.getFactory().createParser("\"test\""); jp.nextToken(); assertThat(ParserUtil.readArray(jp)).isNull(); jp = om.getFactory().createParser("[1,2,3]"); jp.nextToken(); assertThat(ParserUtil.readArray(jp)).containsExactly(1, 2, 3); jp = om.getFactory().createParser("[[\"k\",\"l\",\"m\"],[\"a\",\"b\",\"c\"]]"); jp.nextToken(); assertThat(ParserUtil.readArray(jp)).containsExactly(Arrays.asList("k", "l", "m"), Arrays.asList("a", "b", "c")); }
### Question: AbortMessage extends WampMessage { @Override public void serialize(JsonGenerator generator) throws IOException { generator.writeNumber(getCode()); generator.writeStartObject(); if (this.message != null) { generator.writeStringField("message", this.message); } generator.writeEndObject(); generator.writeString(this.reason); } AbortMessage(WampError reason, @Nullable String message); AbortMessage(WampError reason); private AbortMessage(String reason, @Nullable String message); static AbortMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); @Nullable String getMessage(); @Nullable String getReason(); @Override String toString(); }### Answer: @Test public void serializeTest() { AbortMessage abortMessage = new AbortMessage(WampError.NO_SUCH_REGISTRATION, "No such registration"); assertThat(abortMessage.getCode()).isEqualTo(3); assertThat(abortMessage.getMessage()).isEqualTo("No such registration"); assertThat(abortMessage.getReason()).isEqualTo("wamp.error.no_such_registration"); String json = serializeToJson(abortMessage); assertThat(json).isEqualTo( "[3,{\"message\":\"No such registration\"},\"wamp.error.no_such_registration\"]"); abortMessage = new AbortMessage(WampError.NO_SUCH_REGISTRATION); assertThat(abortMessage.getCode()).isEqualTo(3); assertThat(abortMessage.getMessage()).isNull(); assertThat(abortMessage.getReason()).isEqualTo("wamp.error.no_such_registration"); json = serializeToJson(abortMessage); assertThat(json).isEqualTo("[3,{},\"wamp.error.no_such_registration\"]"); }
### Question: AbortMessage extends WampMessage { public static AbortMessage deserialize(JsonParser jp) throws IOException { String msg = null; jp.nextToken(); Map<String, Object> details = ParserUtil.readObject(jp); if (details != null) { msg = (String) details.get("message"); } jp.nextToken(); return new AbortMessage(jp.getValueAsString(), msg); } AbortMessage(WampError reason, @Nullable String message); AbortMessage(WampError reason); private AbortMessage(String reason, @Nullable String message); static AbortMessage deserialize(JsonParser jp); @Override void serialize(JsonGenerator generator); @Nullable String getMessage(); @Nullable String getReason(); @Override String toString(); }### Answer: @Test public void deserializeTest() throws IOException { String json = "[3, {\"message\": \"The realm does not exist.\"}, \"wamp.error.no_such_realm\"]"; AbortMessage abortMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(abortMessage.getCode()).isEqualTo(3); assertThat(abortMessage.getMessage()).isEqualTo("The realm does not exist."); assertThat(abortMessage.getReason()).isEqualTo("wamp.error.no_such_realm"); json = "[3, {}, \"wamp.error.no_such_realm\"]"; abortMessage = WampMessage.deserialize(getJsonFactory(), json.getBytes(StandardCharsets.UTF_8)); assertThat(abortMessage.getCode()).isEqualTo(3); assertThat(abortMessage.getMessage()).isNull(); assertThat(abortMessage.getReason()).isEqualTo("wamp.error.no_such_realm"); }
### Question: WampSessionIdMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(WampSessionId.class); } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, Message<?> message); }### Answer: @Test public void supportsParameterTest() { assertThat(this.resolver.supportsParameter(this.wampSessionIdParameter)).isTrue(); assertThat(this.resolver.supportsParameter(this.stringParameter)).isFalse(); }
### Question: WampSessionIdMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { return message.getHeaders().get(WampMessageHeader.WAMP_SESSION_ID.name()); } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, Message<?> message); }### Answer: @Test public void resolveArgumentTest() throws Exception { CallMessage callMessage = new CallMessage(1, "call"); callMessage.setHeader(WampMessageHeader.WAMP_SESSION_ID, 23L); assertThat( this.resolver.resolveArgument(this.wampSessionIdParameter, callMessage)) .isEqualTo(23L); }
### Question: PrincipalMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { Class<?> paramType = parameter.getParameterType(); return Principal.class.isAssignableFrom(paramType); } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, Message<?> message); }### Answer: @Test public void supportsParameterTest() { assertThat(this.resolver.supportsParameter(this.principalParameter)).isTrue(); assertThat(this.resolver.supportsParameter(this.stringParameter)).isFalse(); }
### Question: PrincipalMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { Principal user = ((WampMessage) message).getPrincipal(); if (user == null) { throw new MessageHandlingException(message, "No \"PRINCIPAL\" header in message"); } return user; } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, Message<?> message); }### Answer: @Test public void resolveArgumentTest() throws Exception { CallMessage callMessage = new CallMessage(1, "call"); TestPrincipal testPrincipal = new TestPrincipal("testPrincipal"); callMessage.setHeader(WampMessageHeader.PRINCIPAL, testPrincipal); assertThat(this.resolver.resolveArgument(this.principalParameter, callMessage)) .isEqualTo(testPrincipal); } @Test(expected = MessageHandlingException.class) public void missingPrincipalTest() throws Exception { CallMessage callMessage = new CallMessage(1, "call"); TestPrincipal testPrincipal = new TestPrincipal("testPrincipal"); assertThat(this.resolver.resolveArgument(this.principalParameter, callMessage)) .isEqualTo(testPrincipal); }
### Question: WampMessageMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { return WampMessage.class.isAssignableFrom(parameter.getParameterType()); } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, Message<?> message); }### Answer: @Test public void supportsParameterTest() { assertThat(this.resolver.supportsParameter(this.messageParameter)).isTrue(); assertThat(this.resolver.supportsParameter(this.stringParameter)).isFalse(); }
### Question: WampMessageMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception { return message; } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, Message<?> message); }### Answer: @Test public void resolveArgumentTest() throws Exception { CallMessage callMessage = new CallMessage(1, "call"); assertThat(this.resolver.resolveArgument(this.messageParameter, callMessage)) .isEqualTo(callMessage); }
### Question: Features { public List<Feature> enabledDealerFeatures() { List<Feature> dealerFeatures = new ArrayList<>(); if (isEnabled(Feature.DEALER_CALLER_IDENTIFICATION)) { dealerFeatures.add(Feature.DEALER_CALLER_IDENTIFICATION); } return dealerFeatures; } void disable(Feature feature); boolean isEnabled(Feature feature); boolean isDisabled(Feature feature); List<Feature> enabledDealerFeatures(); List<Feature> enabledBrokerFeatures(); }### Answer: @Test public void testEnabledDealerFeatures() { Features feat = new Features(); assertThat(feat.enabledDealerFeatures()) .containsExactly(Feature.DEALER_CALLER_IDENTIFICATION); feat.disable(Feature.DEALER_CALLER_IDENTIFICATION); assertThat(feat.enabledDealerFeatures()).isEmpty(); }
### Question: DuplicateChangeSetException extends LiquibaseException { public DuplicateChangeSetException(String message) { super(message); } DuplicateChangeSetException(String message); }### Answer: @Test public void duplicateChangeSetException() throws Exception { DuplicateChangeSetException duplicateChangeSetException = new DuplicateChangeSetException("MESSAGE HERE"); assertEquals("MESSAGE HERE", duplicateChangeSetException.getMessage()); }
### Question: AlreadyRanChangeSetFilter extends RanChangeSetFilter { public boolean accepts(ChangeSet changeSet) { return getRanChangeSet(changeSet) != null; } AlreadyRanChangeSetFilter(List<RanChangeSet> ranChangeSets); boolean accepts(ChangeSet changeSet); }### Answer: @Test public void accepts_noneRun() { AlreadyRanChangeSetFilter filter = new AlreadyRanChangeSetFilter(new ArrayList<RanChangeSet>()); assertFalse(filter.accepts(new ChangeSet("1", "testAuthor", false, false, "path/changelog",null, null))); } @Test public void accepts() { ArrayList<RanChangeSet> ranChanges = new ArrayList<RanChangeSet>(); ranChanges.add(new RanChangeSet("path/changelog", "1", "testAuthor", CheckSum.parse("12345"), new Date(), null, null)); ranChanges.add(new RanChangeSet("path/changelog", "2", "testAuthor", CheckSum.parse("12345"), new Date(), null, null)); AlreadyRanChangeSetFilter filter = new AlreadyRanChangeSetFilter(ranChanges); assertTrue(filter.accepts(new ChangeSet("1", "testAuthor", false, false, "path/changelog", null, null))); assertTrue(filter.accepts(new ChangeSet("1", "testAuthor", true, false, "path/changelog", null, null))); assertTrue(filter.accepts(new ChangeSet("1", "testAuthor", false, true, "path/changelog", null, null))); assertFalse(filter.accepts(new ChangeSet("3", "testAuthor", false, false, "path/changelog", null, null))); assertFalse(filter.accepts(new ChangeSet("1", "otherAuthor", false, false, "path/changelog", null, null))); assertFalse(filter.accepts(new ChangeSet("1", "testAuthor", false, false, "other/changelog", null, null))); }
### Question: AfterTagChangeSetFilter implements ChangeSetFilter { public boolean accepts(ChangeSet changeSet) { return changeLogsAfterTag.contains(changeLogToString(changeSet.getId(), changeSet.getAuthor(), changeSet.getFilePath())); } AfterTagChangeSetFilter(String tag, List<RanChangeSet> ranChangeSets); boolean accepts(ChangeSet changeSet); }### Answer: @Test public void accepts() throws Exception { ArrayList<RanChangeSet> ranChanges = new ArrayList<RanChangeSet>(); ranChanges.add(new RanChangeSet("path/changelog", "1", "testAuthor", CheckSum.parse("12345"), new Date(), null, null)); ranChanges.add(new RanChangeSet("path/changelog", "2", "testAuthor", CheckSum.parse("12345"), new Date(), "tag1", null)); ranChanges.add(new RanChangeSet("path/changelog", "3", "testAuthor", CheckSum.parse("12345"), new Date(), null, null)); AfterTagChangeSetFilter filter = new AfterTagChangeSetFilter("tag1", ranChanges); assertFalse(filter.accepts(new ChangeSet("1", "testAuthor", false, false, "path/changelog", null, null))); assertFalse(filter.accepts(new ChangeSet("2", "testAuthor", false, false, "path/changelog", null, null))); assertTrue(filter.accepts(new ChangeSet("3", "testAuthor", false, false, "path/changelog", null, null))); }
### Question: CountChangeSetFilter implements ChangeSetFilter { public boolean accepts(ChangeSet changeSet) { changeSetsSeen++; return changeSetsSeen <= changeSetsToAllow; } CountChangeSetFilter(int changeSetsToAllow); boolean accepts(ChangeSet changeSet); }### Answer: @Test public void acceptsZeroCorrectly() { CountChangeSetFilter filter = new CountChangeSetFilter(0); assertFalse(filter.accepts(new ChangeSet("a1","b1",false, false, "c1", null, null))); assertFalse(filter.accepts(new ChangeSet("a2","b2",false, false, "c2", null, null))); } @Test public void acceptsOneCorrectly() { CountChangeSetFilter filter = new CountChangeSetFilter(1); assertTrue(filter.accepts(new ChangeSet("a1","b1",false, false, "c1", null, null))); assertFalse(filter.accepts(new ChangeSet("a2","b2",false, false, "c2", null, null))); } @Test public void acceptsTwoCorrectly() { CountChangeSetFilter filter = new CountChangeSetFilter(2); assertTrue(filter.accepts(new ChangeSet("a1","b1",false, false, "c1", null, null))); assertTrue(filter.accepts(new ChangeSet("a2","b2",false, false, "c2", null, null))); assertFalse(filter.accepts(new ChangeSet("a3","b3",false, false, "c3", null, null))); }
### Question: DbmsChangeSetFilter implements ChangeSetFilter { public boolean accepts(ChangeSet changeSet) { List<SqlVisitor> visitorsToRemove = new ArrayList<SqlVisitor>(); for (SqlVisitor visitor : changeSet.getSqlVisitors()) { if (databaseString != null && visitor.getApplicableDbms() != null && visitor.getApplicableDbms().size() > 0) { boolean shouldRemove = true; if (visitor.getApplicableDbms().contains(databaseString)) { shouldRemove = false; } if (shouldRemove) { visitorsToRemove.add(visitor); } } } changeSet.getSqlVisitors().removeAll(visitorsToRemove); if (databaseString == null) { return true; } if (changeSet.getDbmsSet() == null) { return true; } for (String dbms : changeSet.getDbmsSet()) { if (databaseString.equals(dbms)) { return true; } } return false; } DbmsChangeSetFilter(Database database); boolean accepts(ChangeSet changeSet); }### Answer: @Test public void singleDbms() { DbmsChangeSetFilter filter = new DbmsChangeSetFilter(new MySQLDatabase()); assertTrue(filter.accepts(new ChangeSet(null, null, false, false, null,null, "mysql"))); assertTrue(filter.accepts(new ChangeSet(null, null, false, false, null,null, "mysql, oracle"))); assertFalse(filter.accepts(new ChangeSet(null, null, false, false, null,null, "oracle"))); assertTrue(filter.accepts(new ChangeSet(null, null, false, false, null, null, null))); }
### Question: ChangeLogParameters { public Object getValue(String key) { ChangeLogParameter parameter = findParameter(key); return parameter != null ? parameter.getValue() : null; } ChangeLogParameters(); ChangeLogParameters(Database currentDatabase); void addContext(String context); void setContexts(Collection<String> contexts); void set(String paramter, Object value); void set(String key, String value, String contexts, String databases); Object getValue(String key); boolean hasValue(String key); String expandExpressions(String string); }### Answer: @Test public void getParameterValue_systemProperty() { ChangeLogParameters changeLogParameters = new ChangeLogParameters(); assertEquals(System.getProperty("user.name"), changeLogParameters.getValue("user.name")); }
### Question: RollbackVisitor implements ChangeSetVisitor { public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) throws LiquibaseException { LogFactory.getLogger().info("Rolling Back Changeset:" + changeSet); changeSet.rollback(this.database); this.database.removeRanStatus(changeSet); this.database.commit(); } RollbackVisitor(Database database); Direction getDirection(); void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database); }### Answer: @Test public void visit() throws Exception { Database database = createMock(Database.class); ChangeSet changeSet = createMock(ChangeSet.class); changeSet.rollback(database); expectLastCall(); database.removeRanStatus(changeSet); expectLastCall(); database.commit(); expectLastCall(); replay(changeSet); replay(database); RollbackVisitor visitor = new RollbackVisitor(database); visitor.visit(changeSet, new DatabaseChangeLog(), database); verify(database); verify(changeSet); }
### Question: UpdateVisitor implements ChangeSetVisitor { public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) throws LiquibaseException { ChangeSet.RunStatus runStatus = this.database.getRunStatus(changeSet); log.debug("Running Changeset:" + changeSet); ChangeSet.ExecType execType = changeSet.execute(databaseChangeLog, this.database); if (!runStatus.equals(ChangeSet.RunStatus.NOT_RAN)) { execType = ChangeSet.ExecType.RERAN; } this.database.markChangeSetExecStatus(changeSet, execType); this.database.commit(); } UpdateVisitor(Database database); Direction getDirection(); void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database); }### Answer: @Test public void visit_unrun() throws Exception { Database database = createMock(Database.class); ChangeSet changeSet = createMock(ChangeSet.class); expect(changeSet.execute(new DatabaseChangeLog("test.xml"), database)).andReturn(ChangeSet.ExecType.EXECUTED); expect(database.getRunStatus(changeSet)).andReturn(ChangeSet.RunStatus.NOT_RAN); database.markChangeSetExecStatus(changeSet, ChangeSet.ExecType.EXECUTED); expectLastCall(); database.commit(); expectLastCall(); replay(changeSet); replay(database); UpdateVisitor visitor = new UpdateVisitor(database); visitor.visit(changeSet, new DatabaseChangeLog("test.xml"), database); verify(database); verify(changeSet); }
### Question: AddColumnGeneratorDefaultClauseBeforeNotNull extends AddColumnGenerator { @Override public ValidationErrors validate(AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = super.validate(statement, database, sqlGeneratorChain); if (database instanceof DerbyDatabase && statement.isAutoIncrement()) { validationErrors.addError("Cannot add an identity column to a database"); } return validationErrors; } @Override int getPriority(); @Override boolean supports(AddColumnStatement statement, Database database); @Override ValidationErrors validate(AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); @Override Sql[] generateSql(AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); }### Answer: @Test public void validate_noAutoIncrementWithDerby() { ValidationErrors validationErrors = generatorUnderTest.validate(new AddColumnStatement(null, "table_name", "column_name", "int", null, new AutoIncrementConstraint("column_name")), new DerbyDatabase(), new MockSqlGeneratorChain()); assertTrue(validationErrors.getErrorMessages().contains("Cannot add an identity column to a database")); }
### Question: InsertOrUpdateGeneratorMSSQL extends InsertOrUpdateGenerator { protected String getRecordCheck(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause) { StringBuffer recordCheck = new StringBuffer(); recordCheck.append("DECLARE @reccount integer\n"); recordCheck.append("SELECT @reccount = count(*) FROM "); recordCheck.append(database.escapeTableName(insertOrUpdateStatement.getSchemaName(),insertOrUpdateStatement.getTableName())); recordCheck.append(" WHERE "); recordCheck.append(whereClause); recordCheck.append("\n"); recordCheck.append("IF @reccount = 0\n"); return recordCheck.toString(); } boolean supports(InsertOrUpdateStatement statement, Database database); @Override Sql[] generateSql(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain); }### Answer: @Test public void getRecordCheck(){ InsertOrUpdateGeneratorMSSQL generator = new InsertOrUpdateGeneratorMSSQL(); MSSQLDatabase database = new MSSQLDatabase(); InsertOrUpdateStatement statement = new InsertOrUpdateStatement("myschema","mytable","pk_col1"); statement.addColumnValue("pk_col1","value1"); statement.addColumnValue("col2","value2"); String where = "1 = 1"; Class c = InsertOrUpdateGenerator.class.getClass(); String recordCheck = (String)invokePrivateMethod(generator,"getRecordCheck", new Object[] {statement,database,where}); Integer lineNumber = 0; String[] lines = recordCheck.split("\n"); assertEquals("DECLARE @reccount integer", lines[lineNumber]); lineNumber++; assertEquals("SELECT @reccount = count(*) FROM [myschema].[mytable] WHERE " + where, lines[lineNumber]); lineNumber++; assertEquals("IF @reccount = 0", lines[lineNumber]); }
### Question: InsertOrUpdateGeneratorMSSQL extends InsertOrUpdateGenerator { protected String getElse(Database database) { return "ELSE\n"; } boolean supports(InsertOrUpdateStatement statement, Database database); @Override Sql[] generateSql(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain); }### Answer: @Test public void getElse(){ InsertOrUpdateGeneratorMSSQL generator = new InsertOrUpdateGeneratorMSSQL(); MSSQLDatabase database = new MSSQLDatabase(); InsertOrUpdateStatement statement = new InsertOrUpdateStatement("myschema","mytable","pk_col1"); statement.addColumnValue("pk_col1","value1"); statement.addColumnValue("col2","value2"); String where = "1 = 1"; Class c = InsertOrUpdateGenerator.class.getClass(); String insertStatement = (String)invokePrivateMethod(generator,"getElse", new Object[] {database}); Integer lineNumber = 0; String[] lines = insertStatement.split("\n"); assertEquals("ELSE", lines[lineNumber]); }
### Question: AutoIncrementConstraint implements ColumnConstraint { public String getColumnName() { return columnName; } AutoIncrementConstraint(); AutoIncrementConstraint(String columnName); AutoIncrementConstraint( String columnName, BigInteger startWith, BigInteger incrementBy); String getColumnName(); AutoIncrementConstraint setColumnName(String columnName); BigInteger getStartWith(); AutoIncrementConstraint setStartWith(BigInteger startWith); BigInteger getIncrementBy(); AutoIncrementConstraint setIncrementBy(BigInteger incrementBy); }### Answer: @Test public void ctor() { AutoIncrementConstraint constraint = new AutoIncrementConstraint("COL_NAME"); assertEquals("COL_NAME", constraint.getColumnName()); }
### Question: GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } @Override int getPriority(); @Override boolean supports(GetViewDefinitionStatement statement, Database database); @Override Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); }### Answer: @Test public void testGenerateSqlForDefaultSchema() { GetViewDefinitionGeneratorSybase generator = new GetViewDefinitionGeneratorSybase(); GetViewDefinitionStatement statement = new GetViewDefinitionStatement(null, "view_name"); Sql[] sql = generator.generateSql(statement, new SybaseDatabase(), null); assertEquals(1, sql.length); assertEquals("select text from syscomments where id = object_id('dbo.view_name') order by colid", sql[0].toSql()); } @Test public void testGenerateSqlForNamedSchema() { GetViewDefinitionGeneratorSybase generator = new GetViewDefinitionGeneratorSybase(); GetViewDefinitionStatement statement = new GetViewDefinitionStatement("owner", "view_name"); Sql[] sql = generator.generateSql(statement, new SybaseDatabase(), null); assertEquals(1, sql.length); assertEquals("select text from syscomments where id = object_id('owner.view_name') order by colid", sql[0].toSql()); }
### Question: SqlGeneratorFactory { public static SqlGeneratorFactory getInstance() { if (instance == null) { instance = new SqlGeneratorFactory(); } return instance; } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); }### Answer: @Test public void getInstance() { assertNotNull(SqlGeneratorFactory.getInstance()); assertTrue(SqlGeneratorFactory.getInstance() == SqlGeneratorFactory.getInstance()); }
### Question: SqlGeneratorFactory { public void register(SqlGenerator generator) { generators.add(generator); } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); }### Answer: @Test public void register() { SqlGeneratorFactory.getInstance().getGenerators().clear(); assertEquals(0, SqlGeneratorFactory.getInstance().getGenerators().size()); SqlGeneratorFactory.getInstance().register(new MockSqlGenerator(1, "A1")); assertEquals(1, SqlGeneratorFactory.getInstance().getGenerators().size()); }
### Question: SqlGeneratorFactory { public static void reset() { instance = new SqlGeneratorFactory(); } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); }### Answer: @Test public void reset() { SqlGeneratorFactory instance1 = SqlGeneratorFactory.getInstance(); SqlGeneratorFactory.reset(); assertFalse(instance1 == SqlGeneratorFactory.getInstance()); }
### Question: SqlGeneratorFactory { protected Collection<SqlGenerator> getGenerators() { return generators; } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); }### Answer: @Test public void getGenerators() { SortedSet<SqlGenerator> allGenerators = SqlGeneratorFactory.getInstance().getGenerators(new AddAutoIncrementStatement(null, "person", "name", "varchar(255)", null, null), new H2Database()); assertNotNull(allGenerators); assertEquals(1, allGenerators.size()); }
### Question: PreconditionFactory { public static PreconditionFactory getInstance() { if (instance == null) { instance = new PreconditionFactory(); } return instance; } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); }### Answer: @Test public void getInstance() { assertNotNull(PreconditionFactory.getInstance()); assertTrue(PreconditionFactory.getInstance() == PreconditionFactory.getInstance()); }
### Question: PreconditionFactory { public void register(Class<? extends Precondition> clazz) { try { preconditions.put(clazz.newInstance().getName(), clazz); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); }### Answer: @Test public void register() { PreconditionFactory.getInstance().getPreconditions().clear(); assertEquals(0, PreconditionFactory.getInstance().getPreconditions().size()); PreconditionFactory.getInstance().register(MockPrecondition.class); assertEquals(1, PreconditionFactory.getInstance().getPreconditions().size()); }
### Question: PreconditionFactory { public static void reset() { instance = new PreconditionFactory(); } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); }### Answer: @Test public void reset() { PreconditionFactory instance1 = PreconditionFactory.getInstance(); PreconditionFactory.reset(); assertFalse(instance1 == PreconditionFactory.getInstance()); }
### Question: Main { protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "info"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } } Main(); static void main(String args[]); boolean isWindows(); }### Answer: @Test public void applyDefaults() { Main cli = new Main(); cli.promptForNonLocalDatabase = Boolean.TRUE; cli.applyDefaults(); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); cli.promptForNonLocalDatabase = Boolean.FALSE; cli.applyDefaults(); assertEquals(Boolean.FALSE, cli.promptForNonLocalDatabase); cli.promptForNonLocalDatabase = null; cli.applyDefaults(); assertEquals(Boolean.FALSE, cli.promptForNonLocalDatabase); }
### Question: StreamUtil { public static String getStreamContents(InputStream ins) throws IOException { InputStreamReader reader = new InputStreamReader(ins); return getReaderContents(reader); } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); final static String lineSeparator; }### Answer: @Test public void testGetStreamContents() throws IOException { byte[] contents = "TEST2".getBytes(); ByteArrayInputStream stream = new ByteArrayInputStream(contents); String result = StreamUtil.getStreamContents(stream); assertEquals("TEST2", result); }
### Question: Main { protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println("Errors:"); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); printHelp(stream); } Main(); static void main(String args[]); boolean isWindows(); }### Answer: @Test public void printHelp() throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Main cli = new Main(); cli.printHelp(new PrintStream(stream)); BufferedReader reader = new BufferedReader(new StringReader(new String(stream.toByteArray()))); String line; while ((line = reader.readLine()) != null) { if (line.length() > 80) { fail("'" + line + "' is longer than 80 chars"); } } }
### Question: Main { protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if (i + 1 < args.length) { nextArg = args[i + 1]; } if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } Main(); static void main(String args[]); boolean isWindows(); }### Answer: @Test public void fixArgs() { Main liquibase = new Main(); String[] fixedArgs = liquibase.fixupArgs(new String[] {"--defaultsFile","liquibase.properties", "migrate"}); assertEquals("--defaultsFile=liquibase.properties migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); fixedArgs = liquibase.fixupArgs(new String[] {"--defaultsFile=liquibase.properties", "migrate"}); assertEquals("--defaultsFile=liquibase.properties migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); fixedArgs = liquibase.fixupArgs(new String[] {"--driver=DRIVER", "--username=USERNAME", "--password=PASSWORD", "--url=URL", "--changeLogFile=FILE", "--classpath=CLASSPATH;CLASSPATH2", "--contexts=CONTEXT1,CONTEXT2", "--promptForNonLocalDatabase=true", "migrate" }); assertEquals("--driver=DRIVER --username=USERNAME --password=PASSWORD --url=URL --changeLogFile=FILE --classpath=CLASSPATH;CLASSPATH2 --contexts=CONTEXT1,CONTEXT2 --promptForNonLocalDatabase=true migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); }
### Question: ColumnConfig { public void setValue(String value) { this.value = value; } ColumnConfig(Column columnStructure); ColumnConfig(ColumnConfig column); ColumnConfig(); String getName(); ColumnConfig setName(String name); String getType(); ColumnConfig setType(String type); String getValue(); void setValue(String value); Number getValueNumeric(); ColumnConfig setValueNumeric(String valueNumeric); ColumnConfig setValueNumeric(Number valueNumeric); Boolean getValueBoolean(); ColumnConfig setValueBoolean(Boolean valueBoolean); DatabaseFunction getValueComputed(); ColumnConfig setValueComputed(DatabaseFunction valueComputed); Date getValueDate(); ColumnConfig setValueDate(Date valueDate); ColumnConfig setValueDate(String valueDate); Object getValueObject(); String getDefaultValue(); ColumnConfig setDefaultValue(String defaultValue); Number getDefaultValueNumeric(); ColumnConfig setDefaultValueNumeric(Number defaultValueNumeric); ColumnConfig setDefaultValueNumeric(String defaultValueNumeric); Date getDefaultValueDate(); ColumnConfig setDefaultValueDate(String defaultValueDate); ColumnConfig setDefaultValueDate(Date defaultValueDate); Boolean getDefaultValueBoolean(); ColumnConfig setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); ColumnConfig setDefaultValueComputed(DatabaseFunction defaultValueComputed); Object getDefaultValueObject(); ConstraintsConfig getConstraints(); ColumnConfig setConstraints(ConstraintsConfig constraints); Boolean isAutoIncrement(); ColumnConfig setAutoIncrement(Boolean autoIncrement); BigInteger getStartWith(); ColumnConfig setStartWith(BigInteger startWith); BigInteger getIncrementBy(); ColumnConfig setIncrementBy(BigInteger incrementBy); boolean isPrimaryKey(); boolean isNullable(); boolean hasDefaultValue(); String getRemarks(); ColumnConfig setRemarks(String remarks); }### Answer: @Test public void setValue() throws Exception { ColumnConfig column = new ColumnConfig(); column.setValue(null); assertNull(column.getValue()); column.setValue("abc"); assertEquals("abc", column.getValue()); column.setValue(null); assertEquals("passed null should override the value", null, column.getValue()); column.setValue(""); assertEquals("passed empty strings should override the value", "", column.getValue()); }
### Question: DropPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key dropped from "+getTableName(); } DropPrimaryKeyChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { DropPrimaryKeyChange change = new DropPrimaryKeyChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setConstraintName("PK_NAME"); assertEquals("Primary key dropped from TABLE_NAME", change.getConfirmationMessage()); }
### Question: DropDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value dropped from "+getTableName()+"."+getColumnName(); } DropDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { DropDefaultValueChange change = new DropDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Default value dropped from TABLE_NAME.COL_HERE", change.getConfirmationMessage()); }
### Question: AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void addColumn(ColumnConfig column) { columns.add(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Test public void addColumn() throws Exception { AddColumnChange change = new AddColumnChange(); assertEquals(0, change.getColumns().size()); change.addColumn(new ColumnConfig().setName("a")); assertEquals(1, change.getColumns().size()); change.addColumn(new ColumnConfig().setName("b")); assertEquals(2, change.getColumns().size()); }
### Question: StreamUtil { public static String getReaderContents(Reader reader) throws IOException { try { StringBuffer result = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = reader.read(buffer)) > -1) { result.append(buffer, 0, read); } return result.toString(); } finally { try { reader.close(); } catch (IOException ioe) { } } } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); final static String lineSeparator; }### Answer: @Test public void testGetReaderContents() throws IOException { String contents = "TEST"; StringReader reader = new StringReader(contents); String result = StreamUtil.getReaderContents(reader); assertEquals(contents, result); }
### Question: AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void removeColumn(ColumnConfig column) { columns.remove(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Test public void removeColumn() throws Exception { ColumnConfig columnA = new ColumnConfig().setName("a"); ColumnConfig columnB = new ColumnConfig().setName("b"); AddColumnChange change = new AddColumnChange(); assertEquals(0, change.getColumns().size()); change.removeColumn(columnA); assertEquals(0, change.getColumns().size()); change.addColumn(columnA); assertEquals(1, change.getColumns().size()); change.removeColumn(columnB); assertEquals(1, change.getColumns().size()); change.removeColumn(columnA); assertEquals(0, change.getColumns().size()); }
### Question: AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { List<String> names = new ArrayList<String>(columns.size()); for (ColumnConfig col : columns) { names.add(col.getName() + "(" + col.getType() + ")"); } return "Columns " + StringUtils.join(names, ",") + " added to " + tableName; } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AddColumnChange refactoring = new AddColumnChange(); refactoring.setTableName("TAB"); ColumnConfig column = new ColumnConfig(); column.setName("NEWCOL"); column.setType("TYP"); refactoring.addColumn(column); assertEquals("Columns NEWCOL(TYP) added to TAB", refactoring.getConfirmationMessage()); }
### Question: CreateProcedureChange extends AbstractChange { public String getConfirmationMessage() { return "Stored procedure created"; } CreateProcedureChange(); String getProcedureBody(); void setProcedureBody(String procedureBody); String getComments(); void setComments(String comments); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { CreateProcedureChange refactoring = new CreateProcedureChange(); assertEquals("Stored procedure created", refactoring.getConfirmationMessage()); }
### Question: RenameTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + oldTableName + " renamed to " + newTableName; } RenameTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldTableName(); void setOldTableName(String oldTableName); String getNewTableName(); void setNewTableName(String newTableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { refactoring.setOldTableName("OLD_NAME"); refactoring.setNewTableName("NEW_NAME"); assertEquals("Table OLD_NAME renamed to NEW_NAME", refactoring.getConfirmationMessage()); }
### Question: RawSQLChange extends AbstractSQLChange { public String getConfirmationMessage() { return "Custom SQL executed"; } RawSQLChange(); RawSQLChange(String sql); String getComments(); void setComments(String comments); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Custom SQL executed", refactoring.getConfirmationMessage()); }
### Question: DropIndexChange extends AbstractChange { public String getConfirmationMessage() { return "Index " + getIndexName() + " dropped from table " + getTableName(); } DropIndexChange(); String getSchemaName(); void setSchemaName(String schemaName); String getIndexName(); void setIndexName(String indexName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { DropIndexChange refactoring = new DropIndexChange(); refactoring.setIndexName("IDX_NAME"); refactoring.setTableName("TABLE_NAME"); assertEquals("Index IDX_NAME dropped from table TABLE_NAME", refactoring.getConfirmationMessage()); }
### Question: TagDatabaseChange extends AbstractChange { public String getConfirmationMessage() { return "Tag '"+tag+"' applied to database"; } TagDatabaseChange(); String getTag(); void setTag(String tag); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { refactoring.setTag("TAG_NAME"); assertEquals("Tag 'TAG_NAME' applied to database", refactoring.getConfirmationMessage()); }
### Question: AddForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key contraint added to " + getBaseTableName() + " (" + getBaseColumnNames() + ")"; } AddForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getBaseColumnNames(); void setBaseColumnNames(String baseColumnNames); String getReferencedTableSchemaName(); void setReferencedTableSchemaName(String referencedTableSchemaName); String getReferencedTableName(); void setReferencedTableName(String referencedTableName); String getReferencedColumnNames(); void setReferencedColumnNames(String referencedColumnNames); String getConstraintName(); void setConstraintName(String constraintName); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); void setDeleteCascade(Boolean deleteCascade); void setOnUpdate(String rule); String getOnUpdate(); void setOnDelete(String onDelete); String getOnDelete(); Boolean getReferencesUniqueColumn(); void setReferencesUniqueColumn(Boolean referencesUniqueColumn); void setOnDelete(ForeignKeyConstraintType rule); void setOnUpdate(ForeignKeyConstraintType rule); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AddForeignKeyConstraintChange change = new AddForeignKeyConstraintChange(); change.setConstraintName("FK_NAME"); change.setBaseTableSchemaName("SCHEMA_NAME"); change.setBaseTableName("TABLE_NAME"); change.setBaseColumnNames("COL_NAME"); assertEquals("Foreign key contraint added to TABLE_NAME (COL_NAME)", change.getConfirmationMessage()); }
### Question: RenameColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName; } RenameColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getOldColumnName(); void setOldColumnName(String oldColumnName); String getNewColumnName(); void setNewColumnName(String newColumnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Column TABLE_NAME.oldColName renamed to newColName", refactoring.getConfirmationMessage()); }
### Question: AlterSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " altered"; } AlterSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AlterSequenceChange refactoring = new AlterSequenceChange(); refactoring.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME altered", refactoring.getConfirmationMessage()); }
### Question: MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } static String computeMD5(String input); static String computeMD5(InputStream stream); }### Answer: @Test public void testComputeMD5() throws Exception { String hash = MD5Util.computeMD5(TEST_STRING); assertEquals(TEST_STRING_MD5_HASH, hash); String hash2 = MD5Util.computeMD5(TEST_STRING2); assertEquals(TEST_STRING2_MD5_HASH, hash2); String hash3 = MD5Util.computeMD5(TEST_STRING3); assertEquals(TEST_STRING3_MD5_HASH, hash3); } @Test public void testComputeMD5InputStream() { ByteArrayInputStream bais = new ByteArrayInputStream(TEST_STRING.getBytes()); String hexString = MD5Util.computeMD5(bais); assertEquals(TEST_STRING_MD5_HASH, hexString); }
### Question: DropForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key " + getConstraintName() + " dropped"; } DropForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange(); change.setBaseTableSchemaName("SCHEMA_NAME"); change.setBaseTableName("TABLE_NAME"); change.setConstraintName("FK_NAME"); assertEquals("Foreign key FK_NAME dropped", change.getConfirmationMessage()); }
### Question: DropTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + getTableName() + " dropped"; } DropTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); Boolean isCascadeConstraints(); void setCascadeConstraints(Boolean cascadeConstraints); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Table TAB_NAME dropped", change.getConfirmationMessage()); }
### Question: LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); }### Answer: @Test public void getStatements() throws Exception { MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); SqlStatement[] statements = change.generateStatements(database); assertNotNull(statements); assertEquals(InsertOrUpdateStatement.class,statements[0].getClass()); } @Test public void generateSql(){ MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); SqlStatement[] statements = change.generateStatements(database); assertNotNull(statements); assertEquals(InsertOrUpdateStatement.class,statements[0].getClass()); }
### Question: LoadUpdateDataChange extends LoadDataChange { public void setPrimaryKey(String primaryKey) throws LiquibaseException { if (primaryKey == null) { throw new LiquibaseException("primaryKey cannot be null."); } this.primaryKey = primaryKey; } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); }### Answer: @Test public void primaryKeyNullThrowsException() { LoadUpdateDataChange change = new LoadUpdateDataChange(); try { change.setPrimaryKey(null); fail("setPrimaryKey did not throw InvalidArgumentException as expected."); } catch(LiquibaseException e) { } }
### Question: AddUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } AddUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); Boolean getDisabled(); void setDisabled(Boolean disabled); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AddUniqueConstraintChange change = new AddUniqueConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Unique constraint added to TABLE_NAME(COL_HERE)", change.getConfirmationMessage()); }
### Question: AddNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint has been added to " + getTableName() + "." + getColumnName(); } AddNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getDefaultNullValue(); void setDefaultNullValue(String defaultNullValue); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AddNotNullConstraintChange change = new AddNotNullConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Null constraint has been added to TABLE_NAME.COL_HERE", change.getConfirmationMessage()); }
### Question: RenameViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + oldViewName + " renamed to " + newViewName; } RenameViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldViewName(); void setOldViewName(String oldViewName); String getNewViewName(); void setNewViewName(String newViewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { refactoring.setOldViewName("OLD_NAME"); refactoring.setNewViewName("NEW_NAME"); assertEquals("View OLD_NAME renamed to NEW_NAME", refactoring.getConfirmationMessage()); }
### Question: LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { public String getConfirmationMessage() { return "Data loaded from "+getFile()+" into "+getTableName(); } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { LoadDataChange refactoring = new LoadDataChange(); refactoring.setTableName("TABLE_NAME"); refactoring.setFile("FILE_NAME"); assertEquals("Data loaded from FILE_NAME into TABLE_NAME", refactoring.getConfirmationMessage()); }
### Question: LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { @Override public CheckSum generateCheckSum() { InputStream stream = null; try { stream = getResourceAccessor().getResourceAsStream(getFile()); if (stream == null) { throw new RuntimeException(getFile() + " could not be found"); } return CheckSum.compute(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { ; } } } } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); }### Answer: @Override @Test public void generateCheckSum() throws Exception { LoadDataChange refactoring = new LoadDataChange(); refactoring.setSchemaName("SCHEMA_NAME"); refactoring.setTableName("TABLE_NAME"); refactoring.setFile("liquibase/change/core/sample.data1.csv"); refactoring.setResourceAccessor(new ClassLoaderResourceAccessor()); String md5sum1 = refactoring.generateCheckSum().toString(); refactoring.setFile("liquibase/change/core/sample.data2.csv"); String md5sum2 = refactoring.generateCheckSum().toString(); assertTrue(!md5sum1.equals(md5sum2)); assertEquals(md5sum2, refactoring.generateCheckSum().toString()); }
### Question: CreateViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + getViewName() + " created"; } CreateViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); String getSelectQuery(); void setSelectQuery(String selectQuery); Boolean getReplaceIfExists(); void setReplaceIfExists(Boolean replaceIfExists); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { CreateViewChange change = new CreateViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME created", change.getConfirmationMessage()); }
### Question: DropUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint "+getConstraintName()+" dropped from "+getTableName(); } DropUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); String getUniqueColumns(); void setUniqueColumns(String uniqueColumns); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Unique constraint UQ_CONSTRAINT dropped from TAB_NAME", change.getConfirmationMessage()); }
### Question: CreateTableChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Table " + tableName + " created"; } CreateTableChange(); SqlStatement[] generateStatements(Database database); List<ColumnConfig> getColumns(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getTablespace(); void setTablespace(String tablespace); void addColumn(ColumnConfig column); String getRemarks(); void setRemarks(String remarks); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { change.setTableName("TAB_NAME"); assertEquals("Table TAB_NAME created", change.getConfirmationMessage()); }
### Question: InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public SqlStatement[] generateStatements(Database database) { InsertStatement statement = new InsertStatement(getSchemaName() == null?database.getDefaultSchemaName():getSchemaName(), getTableName()); for (ColumnConfig column : columns) { if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) { continue; } statement.addColumnValue(column.getName(), column.getValueObject()); } return new SqlStatement[]{ statement }; } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void generateStatement() throws Exception { SqlStatement[] sqlStatements = refactoring.generateStatements(new MockDatabase()); assertEquals(1, sqlStatements.length); assertTrue(sqlStatements[0] instanceof InsertStatement); assertEquals("123", ((InsertStatement) sqlStatements[0]).getColumnValue("id").toString()); assertEquals("Andrew", ((InsertStatement) sqlStatements[0]).getColumnValue("name").toString()); assertEquals("21", ((InsertStatement) sqlStatements[0]).getColumnValue("age").toString()); assertEquals("1.78", ((InsertStatement) sqlStatements[0]).getColumnValue("height").toString()); }
### Question: InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "New row inserted into " + getTableName(); } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("New row inserted into TABLE_NAME", refactoring.getConfirmationMessage()); }
### Question: DropViewChange extends AbstractChange { public String getConfirmationMessage() { return "View "+getViewName()+" dropped"; } DropViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { DropViewChange change = new DropViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME dropped", change.getConfirmationMessage()); }
### Question: DropColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column " + getTableName() + "." + getColumnName() + " dropped"; } DropColumnChange(); String getColumnName(); void setColumnName(String columnName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { DropColumnChange change = new DropColumnChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Column TABLE_NAME.COL_HERE dropped", change.getConfirmationMessage()); }
### Question: DropNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint dropped from " + getTableName() + "." + getColumnName(); } DropNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { DropNotNullConstraintChange change = new DropNotNullConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Null constraint dropped from TABLE_NAME.COL_HERE", change.getConfirmationMessage()); }
### Question: AddDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value added to " + getTableName() + "." + getColumnName(); } AddDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); String getDefaultValue(); void setDefaultValue(String defaultValue); String getDefaultValueNumeric(); void setDefaultValueNumeric(String defaultValueNumeric); String getDefaultValueDate(); void setDefaultValueDate(String defaultValueDate); Boolean getDefaultValueBoolean(); void setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); void setDefaultValueComputed(DatabaseFunction defaultValueComputed); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); assertEquals("Default value added to TABLE_NAME.COLUMN_NAME", change.getConfirmationMessage()); }
### Question: RegexMatcher { public boolean allMatchedInSequentialOrder() { return allMatched; } RegexMatcher(String text,String [] regexToMatch); boolean allMatchedInSequentialOrder(); }### Answer: @Test public void testMatchingInSequentialOrder() { matcher=new RegexMatcher(text,new String[]{"Pulp","Reservoir","Kill"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Pulp","ion"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Pu.p","^Ki.+ll$"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"pulP","kiLL"}); assertTrue("Case insensitive",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Reservoir","Pulp","Dogs"}); assertFalse("Not in order",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Memento"}); assertFalse("Not found",matcher.allMatchedInSequentialOrder()); }
### Question: DropSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " dropped"; } DropSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Sequence SEQ_NAME dropped", change.getConfirmationMessage()); }
### Question: SQLFileChange extends AbstractSQLChange { public String getConfirmationMessage() { return "SQL in file " + path + " executed"; } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { change.setPath(fileName); assertEquals("SQL in file " + fileName + " executed", change.getConfirmationMessage()); }
### Question: CreateIndexChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } CreateIndexChange(); String getIndexName(); void setIndexName(String indexName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); void setUnique(Boolean isUnique); Boolean isUnique(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { CreateIndexChange refactoring = new CreateIndexChange(); refactoring.setIndexName("IDX_TEST"); assertEquals("Index IDX_TEST created", refactoring.getConfirmationMessage()); }
### Question: AddAutoIncrementChange extends AbstractChange { public String getConfirmationMessage() { return "Auto-increment added to " + getTableName() + "." + getColumnName(); } AddAutoIncrementChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); BigInteger getStartWith(); void setStartWith(BigInteger startWith); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AddAutoIncrementChange change = new AddAutoIncrementChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setColumnDataType("DATATYPE(255)"); assertEquals("Auto-increment added to TABLE_NAME.COLUMN_NAME", change.getConfirmationMessage()); }
### Question: AddPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key added to " + getTableName() + " (" + getColumnNames() + ")"; } AddPrimaryKeyChange(); String getTableName(); void setTableName(String tableName); String getSchemaName(); void setSchemaName(String schemaName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { AddPrimaryKeyChange change = new AddPrimaryKeyChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Primary key added to TABLE_NAME (COL_HERE)", change.getConfirmationMessage()); }
### Question: CreateSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " created"; } CreateSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getStartValue(); void setStartValue(BigInteger startValue); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); Boolean getCycle(); void setCycle(Boolean cycle); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); }### Answer: @Override @Test public void getConfirmationMessage() throws Exception { CreateSequenceChange change = new CreateSequenceChange(); change.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME created", change.getConfirmationMessage()); }
### Question: AbstractChange implements Change { public boolean supports(Database database) { for (SqlStatement statement : generateStatements(database)) { if (!SqlGeneratorFactory.getInstance().supports(statement, database)) { return false; } } return true; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); }### Answer: @Test public void isSupported() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } for (Database database : TestContext.getInstance().getAllDatabases()) { assertEquals("Unexpected availablity on "+database.getTypeName(), !changeIsUnsupported(database), change.supports(database)); } }
### Question: AbstractChange implements Change { public ValidationErrors validate(Database database) { ValidationErrors changeValidationErrors = new ValidationErrors(); for (SqlStatement statement : generateStatements(database)) { boolean supported = SqlGeneratorFactory.getInstance().supports(statement, database); if (!supported) { if (statement.skipOnUnsupported()) { LogFactory.getLogger().info(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()+" but will continue"); } else { changeValidationErrors.addError(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()); } } else { changeValidationErrors.addAll(SqlGeneratorFactory.getInstance().validate(statement, database)); } } return changeValidationErrors; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); }### Answer: @Test public void validate() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } for (Database database : TestContext.getInstance().getAllDatabases()) { if (change.supports(database)) { ValidationErrors validationErrors = change.validate(database); assertTrue("no errors found for "+database.getClass().getName(), validationErrors.hasErrors()); } } }
### Question: LiquibaseEntityResolver implements EntityResolver2 { public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException { InputSource resolved=null; if(systemId!=null && systemId.toLowerCase().endsWith(".xsd")) { resolved=tryResolveLiquibaseSchema(systemId, publicId); } if(resolved==null && resourceAccessor!=null && basePath!=null && systemId!=null) { resolved=tryResolveFromResourceAccessor(systemId); } return resolved; } LiquibaseEntityResolver(); void useResoureAccessor(ResourceAccessor resourceAccessor,String basePath); InputSource resolveEntity(String name, String publicId, String baseURI, String systemId); InputSource getExternalSubset(String name, String baseURI); InputSource resolveEntity(String publicId, String systemId); }### Answer: @Test public void resolveSchemas() throws Exception { LiquibaseEntityResolver liquibaseSchemaResolver = new LiquibaseEntityResolver(); assertNotNull(liquibaseSchemaResolver.resolveEntity(null, null, null, "http: assertNull(liquibaseSchemaResolver.resolveEntity(null,null,null, "http: }