microsoft / WinAppDriver

Windows Application Driver
MIT License
3.7k stars 1.4k forks source link

test is failing selenium.common.exceptions.WebDriverException: Message: Failed to locate opened application window with appId: #1520

Open nabilalakhani opened 3 years ago

nabilalakhani commented 3 years ago

Hi all, I started having this problem when the driver fails to interact with the app actually its an RDP i am trying to automate the RDP file is opening successfully but not able to click or interact with the RDP like clicking on connect button doesnt work

below is the code

`import unittest from time import sleep

from appium import webdriver from appium.webdriver.extensions import session

class SimpleCalculatorTests(unittest.TestCase):

@classmethod
def setUpClass(self):
    # set up appium
    desired_caps = {}
    desired_caps["app"] = r"C:\jtracker\jailtracker.rdp"
    self.driver = webdriver.Remote(
        command_executor='http://127.0.0.1:4723',
        desired_capabilities=desired_caps)

@classmethod
def tearDownClass(self):
    self.driver.quit()

def test_addition(self):
   self.driver.find_element_by_xpath("/Button[@ClassName=\"Button\"][@Name=\"Connect\"]").click()

    sleep(5)

if name == 'main': suite = unittest.TestLoader().loadTestsFromTestCase(SimpleCalculatorTests) unittest.TextTestRunner(verbosity=2).run(suite)

`

below is the error i m getting i console

Failure Traceback (most recent call last): File "C:\Program Files\Python374\lib\unittest\suite.py", line 163, in _handleClassSetUp setUpClass() File "C:\Users\VellaSR\PycharmProjects\JTracker\launchJtracker.py", line 17, in setUpClass desired_capabilities=desired_caps) File "C:\Users\VellaSR\PycharmProjects\JTracker\venv\lib\site-packages\appium\webdriver\webdriver.py", line 156, in init AppiumConnection(command_executor, keep_alive=keep_alive), desired_capabilities, browser_profile, proxy File "C:\Users\VellaSR\PycharmProjects\JTracker\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 157, in init self.start_session(capabilities, browser_profile) File "C:\Users\VellaSR\PycharmProjects\JTracker\venv\lib\site-packages\appium\webdriver\webdriver.py", line 225, in start_session response = self.execute(RemoteCommand.NEW_SESSION, parameters) File "C:\Users\VellaSR\PycharmProjects\JTracker\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\VellaSR\PycharmProjects\JTracker\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: Failed to locate opened application window with appId: C:\jtracker\jailtracker.rdp, and processId: 3488

C:\Program Files\Python374\lib\unittest\suite.py:170: ResourceWarning: unclosed <socket.socket fd=580, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 59865), raddr=('127.0.0.1', 4723)> self._addClassOrModuleLevelException(result, e, errorName) ResourceWarning: Enable tracemalloc to get the object allocation traceback

Ran 0 tests in 3.503s

FAILED (errors=1)

Process finished with exit code 1

anunay1 commented 3 years ago

your application has a splash screen, create a root session and then switch to the opened window

nabilalakhani commented 3 years ago

your application has a splash screen, create a root session and then switch to the opened window

can you please tell me how do i create root session and then switch to the opened window??? i mean the code for it??

anunay1 commented 3 years ago

check the bug #1296 it has the code for python

nabilalakhani commented 3 years ago

check the bug #1296 it has the code for python

thanks for your quick response so i tried below code but still i see error

`import subprocess import unittest from time import sleep

from appium import webdriver from appium.webdriver.extensions import session

class SimpleCalculatorTests(unittest.TestCase):

@classmethod

def setUpClass(self):
    global driver3
    #set up appium

    subprocess.Popen(['powershell.exe', r'C:\Users\Gamer\Documents\Default.rdp'])
    desired_caps = {}
    desired_caps["platformName"] = "Windows"
    desired_caps["app"] = "Root"
    driver = webdriver.Remote(
        command_executor='http://127.0.0.1:4723',
        desired_capabilities= desired_caps)
    print('Appium handles ', driver.window_handles)
    appWindow = driver.find_element_by_name("Remote Desktop Connection")
    appWindowHandle = appWindow.get_attribute("NativeWindowHandle")
    winHandle = format(int(appWindowHandle), 'x')
    desired_caps3 = {}
    desired_caps3["platformName"] = "Windows"
    desired_caps3["appTopLevelWindow"] = winHandle
    driver3 = webdriver.Remote(
        command_executor='http://127.0.0.1:4723/wd/hub',
        desired_capabilities=desired_caps3
    )
    driver3.switch_to.window(winHandle)
    driver3.find_element_by_xpath("/Button[@ClassName=\"Button\"][@Name=\"Connect\"]").click()

  #  driver3.find_element_by_accessibility_id('LoginPage_Username').send_keys('test11111')
  #  driver3.close_app()

@classmethod
def tearDownClass(self):
    self.driver.quit()

def getresults(self):
    displaytext = self.driver.find_element_by_accessibility_id("CalculatorResults").text
    displaytext = displaytext.strip("Display is " )
    displaytext = displaytext.rstrip(' ')
    displaytext = displaytext.lstrip(' ')
    return displaytext

def test_addition(self):
    driver3.close_app()
    sleep(5)

if name == 'main': suite = unittest.TestLoader().loadTestsFromTestCase(SimpleCalculatorTests) unittest.TextTestRunner(verbosity=2).run(suite) `

error below

C:\Users\Gamer\PycharmProjects\pythonProject2\venv\Scripts\python.exe C:/Users/Gamer/PycharmProjects/pythonProject2/test2.py Appium handles [] ERROR

====================================================================== ERROR: setUpClass (main.SimpleCalculatorTests)

Traceback (most recent call last): File "C:/Users/Gamer/PycharmProjects/pythonProject2/test2.py", line 25, in setUpClass appWindow = driver.find_element_by_name("Remote Desktop Connection") File "C:\Users\Gamer\PycharmProjects\pythonProject2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 496, in find_element_by_name return self.find_element(by=By.NAME, value=name) File "C:\Users\Gamer\PycharmProjects\pythonProject2\venv\lib\site-packages\appium\webdriver\webdriver.py", line 282, in find_element return self.execute(RemoteCommand.FIND_ELEMENT, {'using': by, 'value': value})['value'] File "C:\Users\Gamer\PycharmProjects\pythonProject2\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute self.error_handler.check_response(response) File "C:\Users\Gamer\PycharmProjects\pythonProject2\venv\lib\site-packages\appium\webdriver\errorhandler.py", line 31, in check_response raise wde File "C:\Users\Gamer\PycharmProjects\pythonProject2\venv\lib\site-packages\appium\webdriver\errorhandler.py", line 26, in check_response super().check_response(response) File "C:\Users\Gamer\PycharmProjects\pythonProject2\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: An element could not be located on the page using the given search parameters.


Ran 0 tests in 16.175s

FAILED (errors=1)

Process finished with exit code 0

anunay1 commented 3 years ago

The exception is different then the original one, is inspect able to find the elements

nabilalakhani commented 3 years ago

The exception is different then the original one, is inspect able to find the elements

i believe its not able to find the element since the execption throwing at below line of code while trying to find the window name

    appWindow = driver.find_element_by_name("Remote Desktop Connection")

Traceback (most recent call last): File "C:/Users/Gamer/PycharmProjects/pythonProject2/test2.py", line 25, in setUpClass appWindow = driver.find_element_by_name("Remote Desktop Connection")

also its not able to find any window handles names on below line of code

    print('Appium handles ', driver.window_handles)

output : Appium handles []

can you please suggest something on this

nabilalakhani commented 3 years ago

The exception is different then the original one, is inspect able to find the elements

hey so now i tried some tweaks on below code and it worked but the problem is its taking too long time like 20-30 seconds to click and sendkeys even thought i dont put waits why it takes so much time perform a action please find code below

` import subprocess import unittest from time import sleep

from appium import webdriver from appium.webdriver.extensions import session

class SimpleCalculatorTests(unittest.TestCase):

@classmethod
def setUpClass(self):
    # set up appium
    global driver

    subprocess.Popen(['powershell.exe',r"C:\jtracker\myrdp.rdp"])
    desired_caps = {}
    desired_caps["platformName"] = "Windows"
    desired_caps["app"] = "Root"
    self.driver = webdriver.Remote(
        command_executor='http://127.0.0.1:4723',
        desired_capabilities=desired_caps)

@classmethod
def tearDownClass(self):
    self.driver.quit()

def getresults(self):

    displaytext = displaytext.lstrip(' ')
    return displaytext

def test_connect(self):

    self.driver.find_element_by_xpath("//Button[@ClassName=\"Button\"][@Name=\"Connect\"]").click()
    self.driver.find_element_by_xpath("//Edit[@Name=\"Password\"][starts-with(@AutomationId,\"PasswordField_\")]").send_keys("pass")
    self.driver.find_element_by_xpath("//Button[@Name=\"OK\"][@AutomationId=\"OkButton\"]").click()

if name == 'main': suite = unittest.TestLoader().loadTestsFromTestCase(SimpleCalculatorTests) unittest.TextTestRunner(verbosity=2).run(suite)

`

anunay1 commented 3 years ago

There is a known issue with slowness with xpath, better use some other method to locate elements.

shoaibmansoor commented 3 years ago

Hi @nabilalakhani It looks, you are using desktop session directly to control the application. yes, it is slow with xpath or other types of identifiers as well.

I would suggest using desktop session for taking access to the application only, not to control the application. Use this feature to control already opened application through the desktop session. It will not be slow with xpath or any other element identifier.

Try to use this code to get access to the application

desktop_session = self.driver
element  = desktop_session.find_elements_by_xpath('XPATH_TO_SELECT_APPLICATION_HANDLE')
handle = element.get_attribute('NativeWindowHandle')
top_level_window_handle = str(hex(int(handle)))

new_desired_caps = {}
new_desired_caps['appTopLevelWindow'] = top_level_window_handle
new_desired_caps['deviceName] = 'WindowsPC'
new_desired_caps['platformName] = 'Windows'
new_desired_caps['newCommandTimeout] = 3000
self.driver = webdriver.Remote(command_executor='http://127.0.0.1:4723', desired_capabilities=new_desired_caps)

# Test code goes here