Zapisy otwarte! Dołącz do kursu Selenium w Javie lub Selenium w C#. Tylko do 23.09.2021 do godz. 21:00. Zapisz się tutaj.

Selenium 10. Rozmiar i pozycja okna przeglądarki

Zanim przejdziemy do metod lokalizujących, pokażę Ci jeszcze jak wygląda obsługa okna przeglądarki w Selenium. Możemy na przykład ustawić rozmiar okna przeglądarki albo np. użyć trybu pełnego okna. Selenium poradzi sobie także tutaj.

Skalowanie ekranu

Testy, które zobaczysz w tej lekcji, zadziałają u Ciebie, jeżeli masz skalowanie ekranu ustawione na 100%. Jeżeli korzystasz z laptopa i nie masz zewnętrznego ekranu to najprawdopodobniej Twoje skalowanie to 125%. W kodzie zobaczysz w komentarzach wartości do asercji właśnie dla takiego skalowania.

Weź więc pod uwagę, że Twoje testy, które kiedyś napiszesz, a które będą korzystały z metody getSize() albo getPosition(), będą zwracały różne wartości w zależności od ustawień skalowania ekranu.

W Selenium możliwe jest:

  • wyświetlenie okna przeglądarki w trybie pełnego okna,
  • pobranie pozycji okna na ekranie,
  • pobranie wielkości okna,
  • maksymalizacja okna przeglądarki,
  • ustawienie pozycji okna,
  • ustawienie rozmiaru okna.

Dokumentacja dotycząca metod, które omawiam, dostępna jest pod tym linkiem: WebDriver.Window.

Kod

Ukryta treść

Nie masz dostępu do tego kursu. Wykup dostęp albo zaloguj się, by móc zobaczyć pełną lekcję.

Wsparcie merytoryczne

Nie masz dostępu do wsparcia merytorycznego dla tego kursu. Wykup dostęp albo zaloguj się, by móc zadawać pytania.

  1. Hej, mam problem z prawidłowym wykonaniem asercji. Otrzymuję komunikat:

    org.opentest4j.AssertionFailedError: Position of the window is not what expected. ==>
    Expected :(8, 30)
    Actual :(8, 29)

    Z czego to wynika? Dzięki z góry :).

    Mój kod:

    package DriverMethods;
    
    import org.junit.jupiter.api.AfterEach;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.openqa.selenium.Cookie;
    import org.openqa.selenium.Dimension;
    import org.openqa.selenium.Point;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import java.util.GregorianCalendar;
    import java.util.Set;
    
    public class Manage {
    
        WebDriver driver;
    
        @BeforeEach
        public void driverSetup() {
            System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
            driver = new ChromeDriver();
            driver.manage().window().setSize(new Dimension(1290, 730));
            driver.manage().window().setPosition(new Point(8,30));
            driver.navigate().to("https://www.amazon.com");
         try {
             Thread.sleep(1000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         Assertions.assertEquals(9, driver.manage().getCookies().size(), "Number of cookies is not what expected. ");
        }
    
    
        @AfterEach
        public void driverQuit() {
            driver.quit();
        }
    
        @Test
        public void gettingAndDeletingCookies() {
            Set cookies = driver.manage().getCookies();
            Cookie cookieSessionID = driver.manage().getCookieNamed("session-id");
            driver.manage().deleteCookie(cookieSessionID);
            driver.manage().deleteAllCookies();
            Assertions.assertEquals(0, driver.manage().getCookies().size(), "Number of cookies is not what expected.");
        }
    
        @Test
        public void addingCookies() {
            Cookie newCookie = new Cookie("test_cookie", "test_value", ".amazon.com", "/",
                    new GregorianCalendar(2019, 11, 31).getTime(), true, true); // tworzy date wyasniecia
            driver.manage().addCookie(newCookie);
            Cookie secondCookie = new Cookie("nowe_ciasteczko", "666");
            driver.manage().addCookie(secondCookie);
            Assertions.assertEquals(10, driver.manage().getCookies().size(), "Number of cookies is not what expected.");
        }
    
        @Test
        public void windowSettings(){
            Point position = driver.manage().window().getPosition();
            Assertions.assertEquals(new Point(8, 30), position, "Position of the window is not what expected.");
            Dimension size = driver.manage().window().getSize();
            Assertions.assertEquals(new Dimension(1290, 730), size, "Size of the window is not what expected.");
        }
    }
    
    Odpowiedz
  2. Niestety chyba nie w tym tkwi problem. Istotnie miałem inne wersje, ale po ich ustawieniu na te wskazane przez Ciebie nic nie zmienia się. Wklejam pełny komunikat, może to pomoże zidentyfikować problem.

    "C:\Users\mkownacki1\AppData\Local\JetBrains\IntelliJ IDEA Community Edition 2019.3.1\jbr\bin\java.exe" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:49562,suspend=y,server=n -ea -Didea.test.cyclic.buffer.size=1048576 -javaagent:C:\Users\mkownacki1\.IdeaIC2019.3\system\captureAgent\debugger-agent.jar -Dfile.encoding=UTF-8 -classpath "C:\Users\mkownacki1\AppData\Local\JetBrains\IntelliJ IDEA Community Edition 2019.3.1\lib\idea_rt.jar;C:\Users\mkownacki1\AppData\Local\JetBrains\IntelliJ IDEA Community Edition 2019.3.1\plugins\junit\lib\junit5-rt.jar;C:\Users\mkownacki1\AppData\Local\JetBrains\IntelliJ IDEA Community Edition 2019.3.1\plugins\junit\lib\junit-rt.jar;C:\Users\mkownacki1\IdeaProjects\kursSelenium\target\test-classes;C:\Users\mkownacki1\IdeaProjects\kursSelenium\target\classes;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-java\3.141.59\selenium-java-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-api\3.141.59\selenium-api-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-chrome-driver\3.141.59\selenium-chrome-driver-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-edge-driver\3.141.59\selenium-edge-driver-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-firefox-driver\3.141.59\selenium-firefox-driver-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-ie-driver\3.141.59\selenium-ie-driver-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-opera-driver\3.141.59\selenium-opera-driver-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-remote-driver\3.141.59\selenium-remote-driver-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-safari-driver\3.141.59\selenium-safari-driver-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\org\seleniumhq\selenium\selenium-support\3.141.59\selenium-support-3.141.59.jar;C:\Users\mkownacki1\.m2\repository\net\bytebuddy\byte-buddy\1.8.15\byte-buddy-1.8.15.jar;C:\Users\mkownacki1\.m2\repository\org\apache\commons\commons-exec\1.3\commons-exec-1.3.jar;C:\Users\mkownacki1\.m2\repository\com\google\guava\guava\25.0-jre\guava-25.0-jre.jar;C:\Users\mkownacki1\.m2\repository\com\google\code\findbugs\jsr305\1.3.9\jsr305-1.3.9.jar;C:\Users\mkownacki1\.m2\repository\org\checkerframework\checker-compat-qual\2.0.0\checker-compat-qual-2.0.0.jar;C:\Users\mkownacki1\.m2\repository\com\google\errorprone\error_prone_annotations\2.1.3\error_prone_annotations-2.1.3.jar;C:\Users\mkownacki1\.m2\repository\com\google\j2objc\j2objc-annotations\1.1\j2objc-annotations-1.1.jar;C:\Users\mkownacki1\.m2\repository\org\codehaus\mojo\animal-sniffer-annotations\1.14\animal-sniffer-annotations-1.14.jar;C:\Users\mkownacki1\.m2\repository\com\squareup\okhttp3\okhttp\3.11.0\okhttp-3.11.0.jar;C:\Users\mkownacki1\.m2\repository\com\squareup\okio\okio\1.14.0\okio-1.14.0.jar;C:\Users\mkownacki1\.m2\repository\org\junit\jupiter\junit-jupiter-api\5.2.0\junit-jupiter-api-5.2.0.jar;C:\Users\mkownacki1\.m2\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;C:\Users\mkownacki1\.m2\repository\org\opentest4j\opentest4j\1.1.0\opentest4j-1.1.0.jar;C:\Users\mkownacki1\.m2\repository\org\junit\platform\junit-platform-commons\1.2.0\junit-platform-commons-1.2.0.jar;C:\Users\mkownacki1\.m2\repository\org\junit\platform\junit-platform-launcher\1.2.0\junit-platform-launcher-1.2.0.jar;C:\Users\mkownacki1\.m2\repository\org\junit\platform\junit-platform-engine\1.2.0\junit-platform-engine-1.2.0.jar;C:\Users\mkownacki1\.m2\repository\org\junit\jupiter\junit-jupiter-engine\5.2.0\junit-jupiter-engine-5.2.0.jar" com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit5 DriverMethods.Manage,windowSettings
    Connected to the target VM, address: '127.0.0.1:49562', transport: 'socket'
    OpenJDK 64-Bit Server VM warning: Sharing is only supported for boot loader classes because bootstrap classpath has been appended

    Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 36857
    Only local connections are allowed.
    Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
    [1582296413.879][WARNING]: Timed out connecting to Chrome, retrying...
    lut 21, 2020 3:46:55 PM org.openqa.selenium.remote.ProtocolHandshake createSession
    INFO: Detected dialect: W3C
    [1582296417.972][WARNING]: Timed out connecting to Chrome, retrying...
    [1582296420.709][SEVERE]: Timed out receiving message from renderer: 0.100
    [1582296421.183][SEVERE]: Timed out receiving message from renderer: 0.100

    org.opentest4j.AssertionFailedError: Position of the window is not what expected. ==>
    Expected :(8, 30)
    Actual :(8, 29)

    at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:56)
    at org.junit.jupiter.api.AssertEquals.failNotEqual(AssertEquals.java:197)
    at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:186)
    at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:511)
    at DriverMethods.Manage.windowSettings(Manage.java:62)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:513)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:113)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:121)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:121)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

    Disconnected from the target VM, address: '127.0.0.1:49562', transport: 'socket'

    Process finished with exit code -1

    Odpowiedz
  3. hej, to znowu ja:)
    nie przechodzą mi asercje.

    public class ManageCookies {
        WebDriver driver;
    
        @BeforeTest
        public void driverSetup(){
            System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
            driver = new ChromeDriver();
            driver.manage().window().setSize(new Dimension(1290, 730));
            driver.manage().window().setPosition(new Point(8,30));
            driver.navigate().to("https://www.amazon.com");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        @AfterTest
        public void closeAndQuit(){
            driver.close();
            driver.quit();
        }
        @Test
        public void gettingAndDeletingCookies(){
            driver.manage().deleteCookieNamed("session-id");
            Assert.assertNull(driver.manage().getCookieNamed("session-id"), "Cookie is not deleted.");
            driver.manage().deleteAllCookies();
            Assert.assertEquals(0, driver.manage().getCookies().size(), "Number of cookies is not what expected.");
        }
        @Test
        public void addingAndDeletingCookies(){
            Cookie newCookie = new Cookie("test_cookie", "test_value", ".amazon.com", "/",
                    new GregorianCalendar(2021,11,31).getTime(), true, true);
            driver.manage().addCookie(newCookie);
            Assert.assertNotNull(driver.manage().getCookieNamed("test_cookie"), "Cookie doesn't exist.");
            Cookie secondCookie = new Cookie("test_cookie2", "test_value2");
            driver.manage().addCookie(secondCookie);
            Assert.assertNotNull(driver.manage().getCookieNamed("test_cookie2"), "Cookie doesn't exist.");
            driver.manage().deleteCookie(newCookie);
            Assert.assertNull(driver.manage().getCookieNamed("test_cookie"), "Cookie is not deleted.");
        }
        @Test
        public void windowsSettings(){
            Point position = driver.manage().window().getPosition();
            Assert.assertEquals(new Point(8,30), position, "The position of the window is now what expected");
            Dimension size = driver.manage().window().getSize();
            Assert.assertEquals(new Dimension(1290,730), size, "The size of the window is now what expected");
        }
    }

    a daje mi taki komunikat:

    java.lang.AssertionError: The size of the window is now what expected expected [(1292, 734)] but found [(1290, 730)]
    Expected :(1292, 734)
    Actual :(1290, 730)

    skąd takie wartości w expected?

    Odpowiedz
  4. Też mam ten problem co osoby powyżej (i dokładnie te same wyniki dla size i position).
    To prawdopodobnie kwestia skalowania ekranu, jeśli ktoś używa laptopa. Domyślnym ustawieniem skalowania jest tu 125% (podczas gdy dla normalnego "samodzielnego" monitora jest to zwykle 100%).
    Zmiana skalowania ekranu laptopa na 100% (albo wyłączenie ekranu laptopa i korzystanie z monitora) powoduje, że wartości ustawione dla setPosition() i setSize() będą takie same jak te zwracane w getPosition() i getSize().
    https://snipboard.io/YzHel0.jpg
    Sprawdzałam dla różnych innych wartości i też się zgadza.
    To problemu nie rozwiązuje, ale chyba wyjaśnia dlaczego niektórym działa bez zarzutu, a niektórym wychodzi actual: (8, 29) / (1292, 734).

    Odpowiedz