Skip to content

Commit

Permalink
Update e2e tests to make them compatible with v2compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
pabloFuente committed Jul 2, 2024
1 parent d9bc9b3 commit 0c49be1
Show file tree
Hide file tree
Showing 6 changed files with 1,182 additions and 1,170 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public Map<String, Long> getAverageRgbFromVideo(WebElement videoElement) {
public Map<String, Long> getAverageColorFromPixels(WebElement videoElement, List<Point> pixelPercentagePositions) {
String script = "var callback = arguments[arguments.length - 1];"
+ "var points = arguments[arguments.length - 2];" + "points = JSON.parse(points);"
+ "var video = document.getElementById('local-video-undefined');"
+ "var video = document.getElementById('" + videoElement.getAttribute("id") + "');"
+ "var canvas = document.createElement('canvas');" + "canvas.height = video.videoHeight;"
+ "canvas.width = video.videoWidth;" + "var context = canvas.getContext('2d');"
+ "context.drawImage(video, 0, 0, canvas.width, canvas.height);"
Expand Down Expand Up @@ -175,6 +175,9 @@ public boolean assertMediaTracks(Iterable<WebElement> videoElements, boolean aud
boolean success = true;
for (WebElement video : videoElements) {
if (!waitUntilSrcObjectDefined(video, "", 5000)) {
if (!audioTransmission && !videoTransmission) {
return true;
}
System.err.println("srcObject of HTMLVideoElement was not defined!");
return false;
}
Expand All @@ -194,6 +197,9 @@ public boolean assertMediaTracks(Iterable<WebElement> videoElements, boolean aud
boolean success = true;
for (WebElement video : videoElements) {
if (!waitUntilSrcObjectDefined(video, "", 5000)) {
if (!audioTransmission && !videoTransmission) {
return true;
}
System.err.println("srcObject of HTMLVideoElement was not defined!");
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.net.Socket;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Version;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublisher;
import java.net.http.HttpResponse;
Expand Down Expand Up @@ -99,7 +100,7 @@ public void checkServerTrusted(final X509Certificate[] a_certificates, final Str
throw new RuntimeException(e);
}

this.client = HttpClient.newBuilder().sslContext(sslContext).build();
this.client = HttpClient.newBuilder().version(Version.HTTP_1_1).sslContext(sslContext).build();
}

public int getAndReturnStatus(String path, String credentials) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,9 +79,7 @@ protected void waitUntilReady() {
}

// Media server variables
final protected static String KURENTO_IMAGE = "kurento/kurento-media-server";
final protected static String MEDIASOUP_IMAGE = "openvidu/mediasoup-controller";
protected static String MEDIA_SERVER_IMAGE = KURENTO_IMAGE + ":6.18.0";
final String PLAYGROUND_SCRIPT = "/opt/openvidu-deployment/playground/dev.sh ";

final protected String DEFAULT_JSON_SESSION = "{'id':'STR','object':'session','sessionId':'STR','createdAt':0,'mediaMode':'STR','recordingMode':'STR','defaultRecordingProperties':{'hasVideo':true,'frameRate':25,'hasAudio':true,'shmSize':536870912,'name':'','outputMode':'COMPOSED','resolution':'1280x720','recordingLayout':'BEST_FIT'},'customSessionId':'STR','connections':{'numberOfElements':0,'content':[]},'recording':false,'broadcasting':false,'forcedVideoCodec':'STR','allowTranscoding':false}";
final protected String DEFAULT_JSON_PENDING_CONNECTION = "{'id':'STR','object':'connection','type':'WEBRTC','status':'pending','connectionId':'STR','sessionId':'STR','createdAt':0,'activeAt':null,'location':null,'ip':null,'platform':null,'token':'STR','serverData':'STR','record':true,'role':'STR','kurentoOptions':null,'rtspUri':null,'adaptativeBitrate':null,'onlyPlayWithSubscribers':null,'networkCache':null,'clientData':null,'publishers':null,'subscribers':null, 'customIceServers':[]}";
Expand All @@ -90,8 +88,8 @@ protected void waitUntilReady() {
final protected String DEFAULT_JSON_TOKEN = "{'id':'STR','token':'STR','connectionId':'STR','createdAt':0,'session':'STR','role':'STR','data':'STR','kurentoOptions':{}}";

protected static String OPENVIDU_SECRET = "MY_SECRET";
protected static String OPENVIDU_URL = "https://localhost:4443/";
protected static String APP_URL = "https://localhost:4200/";
protected static String OPENVIDU_URL = "http://localhost:4443/";
protected static String APP_URL = "http://localhost:4200/";
protected static String EXTERNAL_CUSTOM_LAYOUT_URL = "http://localhost:4114";
protected static String OPENVIDU_PRO_LICENSE = "not_valid";
protected static String OPENVIDU_PRO_LICENSE_API = "not_valid";
Expand Down Expand Up @@ -287,12 +285,6 @@ protected static void loadEnvironmentVariables() {
}
log.info("Using secret {} to connect to openvidu-server", OPENVIDU_SECRET);

String mediaServerImage = System.getProperty("MEDIA_SERVER_IMAGE");
if (mediaServerImage != null) {
MEDIA_SERVER_IMAGE = mediaServerImage;
}
log.info("Using media server {} for e2e tests", MEDIA_SERVER_IMAGE);

String chromeVersion = System.getProperty("CHROME_VERSION");
if (chromeVersion != null && !chromeVersion.isBlank()) {
CHROME_VERSION = chromeVersion;
Expand Down Expand Up @@ -607,7 +599,7 @@ protected void deleteAllRecordings(OpenVidu client) {
} catch (OpenViduJavaClientException | OpenViduHttpException e) {
log.error("Error listing recordings: {}", e.getMessage());
}
removeAllRecordingContiners();
// removeAllRecordingContiners();
try {
FileUtils.cleanDirectory(new File("/opt/openvidu/recordings"));
} catch (IOException e) {
Expand All @@ -631,27 +623,7 @@ protected String getBase64Screenshot(BrowserUser user) throws Exception {
}

protected void startMediaServer(boolean waitUntilKurentoClientReconnection) {
String command = null;
if (MEDIA_SERVER_IMAGE.startsWith(KURENTO_IMAGE)) {
log.info("Starting kurento");
command = "docker run -e KMS_UID=$(id -u) --network=host --detach=true"
+ " --volume=/opt/openvidu/recordings:/opt/openvidu/recordings " + MEDIA_SERVER_IMAGE;
} else if (MEDIA_SERVER_IMAGE.startsWith(MEDIASOUP_IMAGE)) {
log.info("Starting mediaSoup");
command = "docker inspect bridge --format '{{with index .IPAM.Config 0}}{{or .Gateway .Subnet}}{{end}}' | sed -r 's|\\.0/[[:digit:]]+$|.1|'";
String dockerGatewayIp = commandLine.executeCommand(command, false, 5);
log.info("Discovered docker gateway IP is {}", dockerGatewayIp);
command = "LOG_DATE=$(printf '%(%Y-%m-%d-%H-%M-%S)T'); docker run --network=host --restart=always --env=KMS_MIN_PORT=40000 --env=KMS_MAX_PORT=65535"
+ " --env=OPENVIDU_PRO_LICENSE=" + OPENVIDU_PRO_LICENSE + " --env=OPENVIDU_PRO_LICENSE_API="
+ OPENVIDU_PRO_LICENSE_API + " --env=WEBRTC_LISTENIPS_0_ANNOUNCEDIP=" + dockerGatewayIp
+ " --env=WEBRTC_LISTENIPS_0_IP=" + dockerGatewayIp
+ " --volume=/opt/openvidu/recordings:/opt/openvidu/recordings " + MEDIA_SERVER_IMAGE
+ " >& /opt/openvidu/mediasoup-controller-${LOG_DATE}.log &";
} else {
log.error("Unrecognized MEDIA_SERVER_IMAGE: {}", MEDIA_SERVER_IMAGE);
System.exit(1);
}
commandLine.executeCommand(command, true, 60);
commandLine.executeCommand(PLAYGROUND_SCRIPT + "start-service master-node-1 openvidu", true, 60);
if (waitUntilKurentoClientReconnection) {
try {
Thread.sleep(5000);
Expand All @@ -662,19 +634,7 @@ protected void startMediaServer(boolean waitUntilKurentoClientReconnection) {
}

protected void stopMediaServer(boolean waitUntilNodeCrashedEvent) {
final String dockerRemoveCmd = "docker ps -a | awk '{ print $1,$2 }' | grep GREP_PARAMETER | awk '{ print $1 }' | xargs -I {} docker rm -f {}";
String grep = null;
if (MEDIA_SERVER_IMAGE.startsWith(KURENTO_IMAGE)) {
log.info("Stopping kurento");
grep = KURENTO_IMAGE;
} else if (MEDIA_SERVER_IMAGE.startsWith(MEDIASOUP_IMAGE)) {
log.info("Stopping mediasoup");
grep = MEDIASOUP_IMAGE;
} else {
log.error("Unrecognized MEDIA_SERVER_IMAGE: {}", MEDIA_SERVER_IMAGE);
System.exit(1);
}
commandLine.executeCommand(dockerRemoveCmd.replaceFirst("GREP_PARAMETER", grep), 60);
commandLine.executeCommand(PLAYGROUND_SCRIPT + "stop-service master-node-1 openvidu", true, 60);
if (waitUntilNodeCrashedEvent) {
try {
Thread.sleep(4000);
Expand Down Expand Up @@ -709,14 +669,7 @@ protected String mergeJson(String json, String newProperties, String[] removePro
}

protected String getIndividualRecordingExtension() throws Exception {
if (MEDIA_SERVER_IMAGE.contains(KURENTO_IMAGE)) {
return "webm";
}
if (MEDIA_SERVER_IMAGE.contains(MEDIASOUP_IMAGE)) {
return "mkv";
} else {
throw new Exception("Unknown media server");
}
return "webm";
}

protected void waitUntilFileExistsAndIsBiggerThan(String absolutePath, int kbs, int maxSecondsWait)
Expand Down Expand Up @@ -795,7 +748,9 @@ public static String getRandom(Set<String> set) {
}

protected JsonObject restartOpenViduServer(Map<String, Object> newConfig) {
return this.restartOpenViduServer(newConfig, false, HttpURLConnection.HTTP_OK);
return new JsonObject();
// return this.restartOpenViduServer(newConfig, false,
// HttpURLConnection.HTTP_OK);
}

protected JsonObject restartOpenViduServer(Map<String, Object> newConfig, boolean force, int status) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.function.BiFunction;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
Expand Down Expand Up @@ -53,6 +55,19 @@ protected void gracefullyLeaveParticipants(OpenViduTestappUser user, int numberO
user.getEventManager().waitUntilEventReaches("connectionDestroyed", accumulatedConnectionDestroyed);
}
}

protected void waitForCondition(BiFunction<BrowserUser, WebElement, Boolean> conditionFunction, BrowserUser user,
WebElement video, int maxWaitTime, int intervalWait) throws InterruptedException {
long startTime = System.currentTimeMillis();
boolean conditionFulfilled = false;
while (!conditionFulfilled && (System.currentTimeMillis() - startTime) < maxWaitTime) {
conditionFulfilled = conditionFunction.apply(user, video);
if (!conditionFulfilled) {
Thread.sleep(intervalWait);
}
}
Assertions.assertTrue(conditionFulfilled, "Video does not meet the condition");
}

@AfterEach
protected void dispose() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import java.awt.Point;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
Expand All @@ -22,6 +23,7 @@
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
Expand All @@ -45,6 +47,7 @@
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;

import info.debatty.java.stringsimilarity.Cosine;
Expand All @@ -58,6 +61,7 @@
import io.openvidu.java.client.Recording;
import io.openvidu.java.client.RecordingProperties;
import io.openvidu.java.client.Session;
import io.openvidu.test.browsers.BrowserUser;
import io.openvidu.test.browsers.utils.CustomHttpClient;
import io.openvidu.test.browsers.utils.RecordingUtils;
import io.openvidu.test.browsers.utils.Unzipper;
Expand Down Expand Up @@ -635,17 +639,29 @@ void individualDynamicRecordTest() throws Exception {
user.getEventManager().waitUntilEventReaches("streamPlaying", 9);

// Get connectionId and streamId for the user configured to be recorded
JsonObject sessionInfo = restClient.rest(HttpMethod.GET, "/openvidu/api/sessions/" + sessionName,
HttpURLConnection.HTTP_OK);
JsonArray connections = sessionInfo.get("connections").getAsJsonObject().get("content").getAsJsonArray();
String connectionId1 = null;
String streamId1 = null;
for (JsonElement connection : connections) {
if (connection.getAsJsonObject().get("record").getAsBoolean()) {
connectionId1 = connection.getAsJsonObject().get("connectionId").getAsString();
streamId1 = connection.getAsJsonObject().get("publishers").getAsJsonArray().get(0).getAsJsonObject()
.get("streamId").getAsString();
break;
JsonObject sessionInfo;
JsonArray connections;
String[] connectionId1 = new String[1];
String[] streamId1 = new String[1];
while (connectionId1[0] == null && streamId1[0] == null) {
sessionInfo = restClient.rest(HttpMethod.GET, "/openvidu/api/sessions/" + sessionName,
HttpURLConnection.HTTP_OK);
connections = sessionInfo.get("connections").getAsJsonObject().get("content").getAsJsonArray();
Gson gson = new Gson();
Type listType = new TypeToken<List<JsonObject>>() {
}.getType();
List<JsonObject> gsonList = gson.fromJson(connections, listType);
if (gsonList.stream().filter(con -> {
if (con.get("record").getAsBoolean() && !con.get("publishers").isJsonNull()) {
connectionId1[0] = con.get("connectionId").getAsString();
streamId1[0] = con.get("publishers").getAsJsonArray().get(0).getAsJsonObject().get("streamId")
.getAsString();
return true;
} else {
return false;
}
}).findAny().orElse(null) == null) {
Thread.sleep(500);
}
}

Expand Down Expand Up @@ -713,9 +729,9 @@ void individualDynamicRecordTest() throws Exception {
for (JsonElement fileJson : syncArray) {
JsonObject file = fileJson.getAsJsonObject();
String fileStreamId = file.get("streamId").getAsString();
if (fileStreamId.equals(streamId1)) {
if (fileStreamId.equals(streamId1[0])) {
// Normal recorded user
Assertions.assertEquals(connectionId1, file.get("connectionId").getAsString(),
Assertions.assertEquals(connectionId1[0], file.get("connectionId").getAsString(),
"Wrong connectionId file metadata property");
long msDuration = file.get("endTimeOffset").getAsLong() - file.get("startTimeOffset").getAsLong();
Assertions.assertTrue(msDuration - 4000 < 750,
Expand Down Expand Up @@ -748,7 +764,7 @@ void individualDynamicRecordTest() throws Exception {
Assertions.fail("Metadata file element does not belong to a known stream (" + fileStreamId + ")");
}
}
Assertions.assertEquals(1, count1, "Wrong number of recording files for stream " + streamId1);
Assertions.assertEquals(1, count1, "Wrong number of recording files for stream " + streamId1[0]);
Assertions.assertEquals(3, count2, "Wrong number of recording files for stream " + streamId2);
Assertions.assertTrue(regexNames.isEmpty(), "Some expected file name didn't existed: " + regexNames.toString());
}
Expand Down Expand Up @@ -1176,6 +1192,8 @@ void networkQualityTest() throws Exception {
threadAssertions.add(event.get("oldValue") == null);
threadAssertions.add(event.has("newValue") && event.get("newValue").getAsInt() > 0
&& event.get("newValue").getAsInt() < 6);
threadAssertions.add(connectionId
.equals(event.get("connection").getAsJsonObject().get("connectionId").getAsString()));
latch1.countDown();
} catch (Exception e) {
log.error("Error analysing NetworkQualityLevelChangedEvent: {}. {}", e.getCause(), e.getMessage());
Expand All @@ -1201,20 +1219,16 @@ void networkQualityTest() throws Exception {
}

// Both events should have publisher's connection ID
Assertions
.assertTrue(
user.getDriver()
.findElement(By.cssSelector(
"#openvidu-instance-0 .mat-expansion-panel:last-child .event-content"))
.getAttribute("textContent").contains(connectionId),
"Wrong connectionId in event NetworkQualityLevelChangedEvent");
Assertions
.assertTrue(
user.getDriver()
.findElement(By.cssSelector(
"#openvidu-instance-1 .mat-expansion-panel:last-child .event-content"))
.getAttribute("textContent").contains(connectionId),
"Wrong connectionId in event NetworkQualityLevelChangedEvent");
Assertions.assertTrue(
user.getDriver().findElement(By.cssSelector(
"#openvidu-instance-0 .mat-expansion-panel .event-content.event-networkQualityLevelChanged"))
.getAttribute("textContent").contains(connectionId),
"Wrong connectionId in event NetworkQualityLevelChangedEvent");
Assertions.assertTrue(
user.getDriver().findElement(By.cssSelector(
"#openvidu-instance-1 .mat-expansion-panel .event-content.event-networkQualityLevelChanged"))
.getAttribute("textContent").contains(connectionId),
"Wrong connectionId in event NetworkQualityLevelChangedEvent");

gracefullyLeaveParticipants(user, 2);
}
Expand Down Expand Up @@ -1338,11 +1352,12 @@ void virtualBackgroundTest() throws Exception {
user.getWaiter().until(
ExpectedConditions.attributeContains(By.id("operation-response-text-area"), "value", "Filter removed"));

rgb = user.getBrowserUser().getAverageColorFromPixels(subscriberVideo,
Arrays.asList(new Point[] { new Point(93, 30), new Point(30, 50) }));

// Green
Assertions.assertTrue((rgb.get("r") < 150) && (rgb.get("g") > 240) && (rgb.get("b") < 100));
BiFunction<BrowserUser, WebElement, Boolean> waitForVideoToBeGreen = (browserUser, webVideo) -> {
Map<String, Long> rgbAux = browserUser.getAverageColorFromPixels(subscriberVideo,
Arrays.asList(new Point[] { new Point(93, 30), new Point(30, 50) }));
return (rgbAux.get("r") < 150) && (rgbAux.get("g") > 240) && (rgbAux.get("b") < 100);
};
waitForCondition(waitForVideoToBeGreen, user.getBrowserUser(), subscriberVideo, 5000, 500);

gracefullyLeaveParticipants(user, 2);
}
Expand Down Expand Up @@ -2833,6 +2848,7 @@ void sucessfullBroadcastTest() throws Exception {
"Number: 0. Changes: false"));

user.getDriver().findElement(By.className("join-btn")).sendKeys(Keys.ENTER);
user.getEventManager().waitUntilEventReaches("connectionCreated", 1);
user.getEventManager().waitUntilEventReaches("streamCreated", 1);
user.getEventManager().waitUntilEventReaches("streamPlaying", 1);

Expand Down
Loading

0 comments on commit 0c49be1

Please sign in to comment.