Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 46 additions & 11 deletions tests/system/libraries/ChromeLib.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2020 NV Access Limited
# Copyright (C) 2020-2021 NV Access Limited
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html

Expand All @@ -12,8 +12,15 @@
import tempfile as _tempfile
from typing import Optional as _Optional
from SystemTestSpy import (
_blockUntilConditionMet,
_getLib,
)
from SystemTestSpy.windows import (
GetForegroundWindowTitle,
GetVisibleWindowTitles,
SetForegroundWindow,
)
import re
from robot.libraries.BuiltIn import BuiltIn

# Imported for type information
Expand Down Expand Up @@ -64,6 +71,14 @@ def start_chrome(self, filePath):
_afterMarker = "After Test Case Marker"
_loadCompleteString = "Test page load complete"

@staticmethod
def getUniqueTestCaseTitle(testCase: str) -> str:
return f"{ChromeLib._testCaseTitle} ({abs(hash(testCase))})"

@staticmethod
def getUniqueTestCaseTitleRegex(testCase: str) -> re.Pattern:
return re.compile(f"^{ChromeLib._testCaseTitle} \\({abs(hash(testCase))}\\)")

@staticmethod
def _writeTestFile(testCase) -> str:
"""
Expand All @@ -75,7 +90,7 @@ def _writeTestFile(testCase) -> str:
filePath = ChromeLib._getTestCasePath("test.html")
fileContents = (f"""
<head>
<title>{ChromeLib._testCaseTitle}</title>
<title>{ChromeLib.getUniqueTestCaseTitle(testCase)}</title>
</head>
<body onload="document.getElementById('loadStatus').innerHTML='{ChromeLib._loadCompleteString}'">
<p>{ChromeLib._beforeMarker}</p>
Expand Down Expand Up @@ -116,6 +131,33 @@ def _waitForStartMarker(self, spy, lastSpeechIndex):
" See NVDA log for full speech."
)

def _focusChrome(self, startsWithTestCaseTitle: re.Pattern):
""" Ensure chrome started and is focused.
Different versions of chrome have variations in how the title is presented.
This may mean that there is a separator between document name and application name.
E.G. "htmlTest Google Chrome", "html – Google Chrome" or perhaps no application name at all.
Rather than try to get this right, just use the doc title.
If this continues to be unreliable we could use Selenium or similar to start chrome and inform us
when it is ready.
"""
success, _success = _blockUntilConditionMet(
getValue=lambda: SetForegroundWindow(startsWithTestCaseTitle),
giveUpAfterSeconds=3,
intervalBetweenSeconds=0.5
)
if success:
return
windowInformation = ""
try:
windowInformation = f"Foreground Window: {GetForegroundWindowTitle()}.\n"
windowInformation += f"Open Windows: {GetVisibleWindowTitles()}"
except OSError as e:
builtIn.log(f"Couldn't retrieve active window information.\nException: {e}")
raise AssertionError(
"Unable to focus Chrome.\n"
f"{windowInformation}"
)

def prepareChrome(self, testCase: str) -> None:
"""
Starts Chrome opening a file containing the HTML sample
Expand All @@ -127,15 +169,8 @@ def prepareChrome(self, testCase: str) -> None:
spy.wait_for_speech_to_finish()
lastSpeechIndex = spy.get_last_speech_index()
self.start_chrome(path)
# Ensure chrome started
# Different versions of chrome have variations in how the title is presented
# This may mean that there is a separator between document name and
# application name. E.G. "htmlTest Google Chrome", "html – Google Chrome" or perhaps no applcation
# name at all.
# Rather than try to get this right, just wait for the doc title.
# If this continues to be unreliable we could use solenium or similar to start chrome and inform us when
# it is ready.
applicationTitle = f"{self._testCaseTitle}"
self._focusChrome(ChromeLib.getUniqueTestCaseTitleRegex(testCase))
applicationTitle = ChromeLib.getUniqueTestCaseTitle(testCase)
appTitleIndex = spy.wait_for_specific_speech(applicationTitle, afterIndex=lastSpeechIndex)
self._waitForStartMarker(spy, appTitleIndex)
# Move to the loading status line, and wait fore it to become complete
Expand Down
71 changes: 71 additions & 0 deletions tests/system/libraries/SystemTestSpy/windows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2021 NV Access Limited
# This file may be used under the terms of the GNU General Public License, version 2 or later.
# For more details see: https://www.gnu.org/licenses/gpl-2.0.html

"""This module provides functions to interact with the Windows system.
"""

from ctypes.wintypes import HWND, LPARAM
from ctypes import c_bool, c_int, create_unicode_buffer, POINTER, WINFUNCTYPE, windll, WinError
import re
from typing import Callable, List, NamedTuple


class Window(NamedTuple):
hwnd: HWND
title: str


def _GetWindowTitle(hwnd: HWND) -> str:
length = windll.user32.GetWindowTextLengthW(hwnd)
if not length:
return ''
buff = create_unicode_buffer(length + 1)
if not windll.user32.GetWindowTextW(hwnd, buff, length + 1):
raise WinError()
return str(buff.value)


def _GetWindows(
filterUsingWindow: Callable[[Window], bool] = lambda _: True,
) -> List[Window]:
windows: List[Window] = []
EnumWindowsProc = WINFUNCTYPE(c_bool, POINTER(c_int), POINTER(c_int))

def _append_title(hwnd: HWND, _lParam: LPARAM) -> bool:
window = Window(hwnd, _GetWindowTitle(hwnd))
if filterUsingWindow(window):
windows.append(window)
return True

if not windll.user32.EnumWindows(EnumWindowsProc(_append_title), 0):
raise WinError()
return windows


def _GetVisibleWindows() -> List[Window]:
return _GetWindows(
filterUsingWindow=lambda window: windll.user32.IsWindowVisible(window.hwnd) and bool(window.title)
)


def SetForegroundWindow(targetTitle: re.Pattern) -> bool:
if re.match(targetTitle, GetForegroundWindowTitle()):
return True
windows = _GetWindows(
filterUsingWindow=lambda window: re.match(targetTitle, window.title)
)
for window in windows:
return windll.user32.SetForegroundWindow(window.hwnd)
return False


def GetVisibleWindowTitles() -> List[str]:
windows = _GetVisibleWindows()
return [w.title for w in windows]


def GetForegroundWindowTitle() -> str:
hwnd = windll.user32.GetForegroundWindow()
return _GetWindowTitle(hwnd)
1 change: 0 additions & 1 deletion tests/system/robot/chromeTests.robot
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ default teardown

default setup
start NVDA standard-dontShowWelcomeDialog.ini
Sleep 5s

*** Test Cases ***

Expand Down