Skip to content

Commit

Permalink
Merge pull request #48 from AutomateThePlanet/smpInternal
Browse files Browse the repository at this point in the history
Smp internal release 31/10/2024
  • Loading branch information
n1xan authored Oct 31, 2024
2 parents f70deed + 5e3be3c commit d15cba5
Show file tree
Hide file tree
Showing 11 changed files with 177 additions and 56 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,15 @@

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EntitiesAsserter {
public static <TEntity> Boolean areEqual(TEntity expectedObject, TEntity realObject, DateTimeDeltaType deltaType, int deltaQuantity, String... propertiesNotToCompare) {
List<Exception> failedAssertions = assertAreEqualsInternal(expectedObject, realObject, deltaType, deltaQuantity, propertiesNotToCompare);
if (failedAssertions.size() > 1) {
return false;
}
return true;
return failedAssertions.size() <= 1;
}
public static <TEntity> Boolean areEqual(TEntity expectedObject, TEntity realObject, String... propertiesNotToCompare) {
return areEqual(expectedObject, realObject, DateTimeDeltaType.MILLISECONDS, 300, propertiesNotToCompare);
Expand Down Expand Up @@ -69,13 +67,20 @@ private static <TEntity> List<Exception> assertAreEqualsInternal(TEntity expecte

try {
if (currentRealProperty.getReturnType() == LocalDateTime.class) {
assert currentExpectedProperty != null;
LocalDateTimeAssert.areEqual(
(LocalDateTime)currentExpectedProperty.invoke(expectedObject),
(LocalDateTime)currentRealProperty.invoke(realObject),
deltaType, deltaQuantity, exceptionMessage);
} else if (currentRealProperty.getReturnType() == OffsetDateTime.class) {
assert currentExpectedProperty != null;
LocalDateTimeAssert.areEqual(
((OffsetDateTime)currentExpectedProperty.invoke(expectedObject)).toLocalDateTime(),
((OffsetDateTime)currentRealProperty.invoke(realObject)).toLocalDateTime(),
deltaType, deltaQuantity, exceptionMessage);
} else {
Assertions.assertEquals(
currentExpectedProperty.invoke(expectedObject),
currentExpectedProperty != null ? currentExpectedProperty.invoke(expectedObject) : null,
currentRealProperty.invoke(realObject),
exceptionMessage);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ else if (actualDate == null){
}

}
public static void areEqual(LocalDateTime expectedDate, LocalDateTime actualDate, Duration expectedDelta, String exceptionMessage) throws Exception {

public static void areEqual(LocalDateTime expectedDate, LocalDateTime actualDate, Duration expectedDelta, String exceptionMessage) {
if (expectedDate == null && actualDate == null){
return;
}
Expand All @@ -54,7 +55,7 @@ else if (actualDate == null){
{
var message = exceptionMessage+"\nExpected Date: "+expectedDate+", Actual Date: "+actualDate+
" \nExpected Delta: "+expectedDelta+", Actual Delta: "+actualDelta;
throw new Exception(message);
throw new RuntimeException(message);
}
}
private static Duration getTimeSpanDeltaByType(DateTimeDeltaType type, int count) throws UnsupportedOperationException {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ public WebElement getWrappedElement() {
try {
wrappedElement.isDisplayed(); // checking if getting property throws exception
return wrappedElement;
} catch (StaleElementReferenceException | NoSuchElementException | NullPointerException ex) {
} catch (StaleElementReferenceException | NoSuchElementException | NullPointerException | ScriptTimeoutException ex ) {
return findElement();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.openqa.selenium.Platform;

import java.util.HashMap;
import java.util.Objects;

public class BrowserConfiguration {
@Setter @Getter private Browser browser;
Expand Down Expand Up @@ -72,25 +73,18 @@ public BrowserConfiguration(DeviceName deviceName, Lifecycle browserBehavior, St

@Override
public boolean equals(Object obj) {
if (!(obj instanceof BrowserConfiguration))
return false;
BrowserConfiguration that = (BrowserConfiguration)obj;
if (!((this.getBrowser() == null) ? (that.getBrowser() == null) : this.getBrowser().equals(that.getBrowser())))
return false;
if (this.deviceName != that.deviceName)
return false;
if (!(this.getLifecycle() == null ? that.getLifecycle() == null : this.getLifecycle().equals(that.getLifecycle())))
return false;
if (this.getHeight() != that.getHeight())
return false;
if (this.getWidth() != that.getWidth())
return false;
if (this.getVersion() != that.getVersion())
return false;
if (!(this.getPlatform() == null ? that.getPlatform() == null : this.getPlatform().equals(that.getPlatform())))
return false;
if (!(this.getDriverOptions() == null ? that.getDriverOptions() == null : this.getDriverOptions().equals(that.getDriverOptions())))
return false;
return true;
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;

BrowserConfiguration that = (BrowserConfiguration) obj;

if (!Objects.equals(this.getBrowser(), that.getBrowser())) return false;
if (!Objects.equals(this.deviceName, that.deviceName)) return false;
if (!Objects.equals(this.getLifecycle(), that.getLifecycle())) return false;
if (this.getHeight() != that.getHeight()) return false;
if (this.getWidth() != that.getWidth()) return false;
if (this.getVersion() != that.getVersion()) return false;
if (!Objects.equals(this.getPlatform(), that.getPlatform())) return false;
return Objects.equals(this.getDriverOptions(), that.getDriverOptions());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,6 @@ private boolean shouldRestartBrowser() {
return true;
} else if (!previousConfiguration.equals(currentConfiguration)) {
return true;
} else if (currentConfiguration.getLifecycle() == Lifecycle.REUSE_IF_STARTED) {
return false;
} else if (currentConfiguration.getLifecycle() == Lifecycle.RESTART_EVERY_TIME) {
return true;
} else {
return false;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package solutions.bellatrix.web.infrastructure;

import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class EmptyObjectTypeAdapterFactory implements TypeAdapterFactory {
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

return new TypeAdapter<T>() {
@Override
public void write(JsonWriter out, T value) throws IOException {
delegate.write(out, value);
}

@Override
public T read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.BEGIN_ARRAY) {
JsonArray arr = new JsonParser().parse(in).getAsJsonArray();
if (arr.size() == 0) {
if (isCollectionType(type.getType())) {
return delegate.fromJsonTree(arr);
} else {
return delegate.fromJsonTree(new JsonObject());
}
}
return delegate.fromJsonTree(arr);
}
return delegate.read(in);
}
};
}

private boolean isCollectionType(Type type) {
if (type instanceof Class<?>) {
return Collection.class.isAssignableFrom((Class<?>)type);
} else if (type instanceof ParameterizedType) {
return isCollectionType(((ParameterizedType)type).getRawType());
}
return false;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package solutions.bellatrix.web.infrastructure;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LocalDateTimeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

@Override
public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(src).replace("+00:00", ""));
}

@Override
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return LocalDateTime.parse(json.getAsString().replace("+00:00", ""), formatter);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package solutions.bellatrix.web.infrastructure;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class OffsetDateTimeTypeAdapter implements JsonSerializer<OffsetDateTime>, JsonDeserializer<OffsetDateTime> {
private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
private final DateTimeFormatter localDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

@Override
public JsonElement serialize(OffsetDateTime src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(formatter.format(src));
}

@Override
public OffsetDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
OffsetDateTime result;
try {
result = OffsetDateTime.parse(json.getAsString(), formatter);
}
catch(Exception ex) {
result = LocalDateTime.parse(json.getAsString(), localDateTimeFormatter).atOffset(ZoneOffset.UTC);
}

return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@

package solutions.bellatrix.web.infrastructure;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.*;
import lombok.SneakyThrows;
import net.lightbody.bmp.BrowserMobProxyServer;
import net.lightbody.bmp.core.har.HarEntry;
Expand All @@ -37,6 +34,8 @@
import java.lang.reflect.Type;
import java.net.ServerSocket;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
Expand All @@ -55,6 +54,8 @@ public class ProxyServer {
HttpStatus.SC_PARTIAL_CONTENT,
HttpStatus.SC_MULTI_STATUS);

private static Gson gson;

@SneakyThrows
public static int init() {
Log.info("Starting Proxy Service...");
Expand All @@ -64,6 +65,11 @@ public static int init() {
PROXY_SERVER.get().enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT, CaptureType.REQUEST_HEADERS);
PORT.set(port);
Log.info("Proxy Service Started at Port %s".formatted(port));
gson = new GsonBuilder()
.registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
.registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeTypeAdapter())
.registerTypeAdapterFactory(new EmptyObjectTypeAdapterFactory())
.create();
return port;
}

Expand Down Expand Up @@ -164,7 +170,7 @@ public static void waitForResponse(WebDriver driver, String requestPartialUrl, H
catch (TimeoutException exception){
String allUrlsString = getSimilarRequestsString(requestPartialUrl, allHarEntries);

throw new AssertionFailedError(String.format("The expected response with request URL '%s' with method %s is not loaded! \r\nSimilar requests: %s", requestPartialUrl, httpMethod, allUrlsString));
throw new RuntimeException(String.format("The expected response with request URL '%s' with method %s is not loaded! \r\nSimilar requests: %s", requestPartialUrl, httpMethod, allUrlsString));
}
}

Expand Down Expand Up @@ -220,7 +226,7 @@ public static <T> T getLastRequest(Class<T> requestModelClass) {
return getCapturedEntries().stream()
.map(HarEntry::getRequest)
.filter(request -> request.getPostData() != null)
.map(request -> new Gson().fromJson(request.getPostData().getText(), requestModelClass))
.map(request -> gson.fromJson(request.getPostData().getText(), requestModelClass))
.reduce((first, second) -> second)
.orElse(null);
}
Expand All @@ -229,7 +235,7 @@ public static <T> T getLastResponse(Class<T> responseModelClass) {
return getCapturedEntries().stream()
.map(HarEntry::getResponse)
.filter(response -> response.getContent() != null)
.map(response -> new Gson().fromJson(getDataObject(response.getContent().getText()), responseModelClass))
.map(response -> gson.fromJson(getDataObject(response.getContent().getText()), responseModelClass))
.reduce((first, second) -> second)
.orElse(null);
}
Expand All @@ -238,13 +244,13 @@ public static <T> T getRequestByIndex(int index, Class<T> requestModelClass) {
var entries = getCapturedEntries();
var harEntry = entries.get(index);
String json = harEntry.getRequest().getPostData().getText();
return new Gson().fromJson(json, requestModelClass);
return gson.fromJson(json, requestModelClass);
}

public static <T> T getResponseByIndex(int index, Class<T> responseModelClass) {
var harEntry = getCapturedEntries().get(index);
String json = harEntry.getResponse().getContent().getText();
return new Gson().fromJson(getDataObject(json), responseModelClass);
return gson.fromJson(getDataObject(json), responseModelClass);
}

public static <T> T getRequestByUrl(String url, String httpMethod, Class<T> requestModelClass) {
Expand All @@ -258,7 +264,7 @@ public static <T> T getRequestByUrl(String url, String httpMethod, Class<T> requ
}
String json = harEntry.getRequest().getPostData().getText();
try {
return new Gson().fromJson(json, requestModelClass);
return gson.fromJson(json, requestModelClass);
}
catch (Exception e) {
throw new RuntimeException("Error occurred while converting json to model. Json was: %s".formatted(json), e);
Expand All @@ -276,7 +282,7 @@ public static <T> T getRequestByUrl(String url, String httpMethod, Type modelTyp
}
String json = harEntry.getRequest().getPostData().getText();
try {
return new Gson().fromJson(json, modelType);
return gson.fromJson(json, modelType);
}
catch (Exception e) {
throw new RuntimeException("Error occurred while converting json to model. Json was: %s".formatted(json), e);
Expand All @@ -295,7 +301,7 @@ public static <T> T getResponseByUrl(String url, String httpMethod, Class<T> res
}
String json = harEntry.getResponse().getContent().getText();
try {
return new Gson().fromJson(getDataObject(json), responseModelClass);
return gson.fromJson(getDataObject(json), responseModelClass);
}
catch (Exception ex){
throw new AssertionFailedError("Cannot get JSON body from the string: " + json + ". Error was: " + ex.getMessage());
Expand All @@ -313,7 +319,12 @@ public static <T> T getResponseByUrl(String url, String httpMethod, Type respons
return null;
}
String json = harEntry.getResponse().getContent().getText();
return new Gson().fromJson(getDataObject(json), responseModelType);
try {
return gson.fromJson(getDataObject(json), responseModelType);
}
catch (Exception ex) {
throw new RuntimeException("Failed to Serialize Json to Object: \n Entity Type: %s\n Json was: %s".formatted(responseModelType.getTypeName(), json));
}
}

public static void blockRequestByUrl(String url, HttpMethod httpMethod) {
Expand Down
Loading

0 comments on commit d15cba5

Please sign in to comment.