Skip to content

Commit

Permalink
Enable fuzzydict unit tests, fix trailing spaces.
Browse files Browse the repository at this point in the history
  • Loading branch information
vasily-v-ryabov committed Oct 17, 2016
1 parent 30e7730 commit f6dc79d
Show file tree
Hide file tree
Showing 16 changed files with 72 additions and 81 deletions.
1 change: 1 addition & 0 deletions ci/runTestsuite.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ function run {
$output = "transformed.xml"

#nosetests --all-modules --with-xunit pywinauto/unittests
nosetests --nologcapture --exclude=testall --with-xunit --with-coverage --cover-html --cover-html-dir=Coverage_report --cover-package=pywinauto --verbosity=3 pywinauto\fuzzydict.py
nosetests --nologcapture --exclude=testall --with-xunit --with-coverage --cover-html --cover-html-dir=Coverage_report --cover-package=pywinauto --verbosity=3 pywinauto\unittests
$success = $?
Write-Host "result code of nosetests:" $success
Expand Down
11 changes: 4 additions & 7 deletions examples/notepad_fast.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def run_notepad():
print("\nRunning this script so it will load application data and run")
print("against any lanuguage version of Notepad/Windows")

# make sure that the app data gets read from the same folder as
# make sure that the app data gets read from the same folder as
# the script
app = application.Application(
os.path.join(scriptdir, "Notepad_fast.pkl"))
Expand All @@ -100,7 +100,7 @@ def run_notepad():
app.PageSetupDlg.SizeComboBox.select("Letter")
except ValueError:
app.PageSetupDlg.SizeComboBox.select('Letter (8.5" x 11")')

app.PageSetupDlg.SizeComboBox.select(2)

# run some tests on the Dialog. List of available tests:
Expand Down Expand Up @@ -150,7 +150,7 @@ def run_notepad():

doc_props = app.window_(title_re = ".*Properties$")
doc_props.Wait('exists', timeout = 40)

#
# # ----- Document Properties Dialog ----
# # some tab control selections
Expand Down Expand Up @@ -202,8 +202,7 @@ def run_notepad():
# window does not close cleanly :(
if doc_props.Cancel.Exists():
doc_props.OK.close_click()



# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.OK.close_click()
# ----- Page Setup Dialog ----
Expand Down Expand Up @@ -271,8 +270,6 @@ def run_notepad():
if not run_with_appdata:
app.WriteAppData(os.path.join(scriptdir, "Notepad_fast.pkl"))



print("That took %.3f to run"% (time.time() - start))

if __name__ == "__main__":
Expand Down
9 changes: 3 additions & 6 deletions examples/notepad_slow.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,7 @@
#application.set_timing(3, .5, 10, .5, .4, .2, .2, .1, .2, .5)

def run_notepad():
"Run notepad and do some small stuff with it"

"""Run notepad and do some small stuff with it"""
start = time.time()
app = application.Application()

Expand Down Expand Up @@ -173,13 +172,12 @@ def run_notepad():

# ----- Document Properties Dialog again ----
doc_props.Cancel.close_click()

# for some reason my current printer driver
# window does not close cleanly :(
if doc_props.Cancel.Exists():
doc_props.OK.close_click()



# ----- 2nd Page Setup Dialog again ----
app.PageSetupDlg.OK.close_click()
# ----- Page Setup Dialog ----
Expand Down Expand Up @@ -246,7 +244,6 @@ def run_notepad():
# app.WriteAppData(os.path.join(scriptdir, "Notepad_fast.pkl"))



print("That took %.3f to run"% (time.time() - start))

if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion pywinauto/clipboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def _get_standard_formats():
def GetClipboardFormats():
"""Get a list of the formats currently in the clipboard"""
win32clipboard.OpenClipboard()

available_formats = []
current_format = 0
while True:
Expand Down
13 changes: 5 additions & 8 deletions pywinauto/fuzzydict.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ def _search(self, lookfor, stop_on_first = False):
if stop_on_first is True then the method returns as soon
as it finds the first item.
"""

# if the item is in the dictionary then just return it
if self._dict_contains(lookfor):
return True, lookfor, self._dict_getitem(lookfor), 1
Expand Down Expand Up @@ -170,9 +169,9 @@ def __getitem__(self, lookfor):
import unittest

class FuzzyTestCase(unittest.TestCase):

"""Perform some tests"""

test_dict = {
'Hiya' : 1,
'hiy\xe4' : 2,
Expand All @@ -186,7 +185,7 @@ def test_creation_empty(self):
self.assertEquals(fd, {})

def test_creation_dict(self):
"Test creating a fuzzy dict"
"""Test creating a fuzzy dict"""
fd = FuzzyDict(self.test_dict)
self.assertEquals(fd, self.test_dict)
self.assertEquals(self.test_dict['Hiya'], fd['hiya'])
Expand All @@ -195,9 +194,8 @@ def test_creation_dict(self):
self.assertEquals(fd, self.test_dict)
self.assertRaises(KeyError, fd2.__getitem__, 'hiya')


def test_contains(self):
"Test checking if an item is in a FuzzyDict"
"""Test checking if an item is in a FuzzyDict"""
fd = FuzzyDict(self.test_dict)

self.assertEquals(True, fd.__contains__('hiya'))
Expand All @@ -212,9 +210,8 @@ def test_contains(self):

self.assertEquals(False, fd.__contains__(23))


def test_get_item(self):
"Test getting items from a FuzzyDict"
"""Test getting items from a FuzzyDict"""
fd = FuzzyDict(self.test_dict)

self.assertEquals(self.test_dict["Hiya"], fd['hiya'])
Expand Down
2 changes: 1 addition & 1 deletion pywinauto/handleprops.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def isenabled(handle):
#=========================================================================
def is64bitprocess(process_id):
"""Return True if the specified process is a 64-bit process on x64
Return False if it is only a 32-bit process running under Wow64.
Always return False for x86.
"""
Expand Down
2 changes: 1 addition & 1 deletion pywinauto/keyboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def __init__(self, key, down = True, up = True):

def _get_key_info(self):
"""Return virtual_key, scan_code, and flags for the action
This is one of the methods that will be overridden by sub classes"""
#print(self.key)
return 0, ord(self.key), KEYEVENTF_UNICODE
Expand Down
26 changes: 14 additions & 12 deletions pywinauto/remote_memory_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@
from .actionlogger import ActionLogger

class AccessDenied(RuntimeError):

"""Raised when we cannot allocate memory in the control's process"""

pass

#====================================================================
Expand All @@ -60,7 +62,7 @@ def __init__(self, ctrl, size = 4096): #4096): #16384):
self.size = size
self.process = 0
self.handle = ctrl.handle

if self.handle == 0xffffffff80000000:
raise Exception('Incorrect handle: ' + str(self.handle))

Expand Down Expand Up @@ -97,12 +99,12 @@ def __init__(self, ctrl, size = 4096): #4096): #16384):

if self.memAddress == 0:
raise ctypes.WinError()

if hex(self.memAddress) == '0xffffffff80000000' or hex(self.memAddress).upper() == '0xFFFFFFFF00000000':
raise Exception('Incorrect allocation: ' + hex(self.memAddress))

self._as_parameter_ = self.memAddress

# write guard signature at the end of memory block
signature = win32structures.LONG(0x66666666)
ret = win32functions.WriteProcessMemory(
Expand Down Expand Up @@ -136,7 +138,7 @@ def CleanUp(self):
# free up the memory we allocated
#win32api.SetLastError(0)
self.CheckGuardSignature()

ret = win32functions.VirtualFreeEx(
ctypes.c_void_p(self.process),
ctypes.c_void_p(self.memAddress),
Expand Down Expand Up @@ -180,14 +182,14 @@ def Write(self, data, address = None, size = None):
nSize = win32structures.ULONG_PTR(size)
else:
nSize = win32structures.ULONG_PTR(ctypes.sizeof(data))

if self.size < nSize.value:
raise Exception(('Write: RemoteMemoryBlock is too small ({0} bytes),' + \
' {1} is required.').format(self.size, nSize.value))

if hex(address).lower().startswith('0xffffff'):
raise Exception('Write: RemoteMemoryBlock has incorrect address = ' + hex(address))

ret = win32functions.WriteProcessMemory(
ctypes.c_void_p(self.process),
ctypes.c_void_p(address),
Expand Down Expand Up @@ -220,12 +222,12 @@ def Read(self, data, address = None, size = None):
if self.size < nSize.value:
raise Exception(('Read: RemoteMemoryBlock is too small ({0} bytes),' + \
' {1} is required.').format(self.size, nSize.value))

if hex(address).lower().startswith('0xffffff'):
raise Exception('Read: RemoteMemoryBlock has incorrect address =' + hex(address))

lpNumberOfBytesRead = ctypes.c_size_t(0)

ret = win32functions.ReadProcessMemory(
ctypes.c_void_p(self.process),
ctypes.c_void_p(address),
Expand Down Expand Up @@ -256,15 +258,15 @@ def Read(self, data, address = None, size = None):
ActionLogger().log('Error: ERROR_PARTIAL_COPY')
ActionLogger().log('\nRead: WARNING! self.memAddress =' + \
hex(self.memAddress) + ' data address =' + str(ctypes.byref(data)))

ActionLogger().log('lpNumberOfBytesRead =' + \
str(lpNumberOfBytesRead) + ' nSize =' + str(nSize))
raise ctypes.WinError()
else:
ActionLogger().log('Warning! Read OK: 2nd attempt!')
#else:
# print 'Read OK: lpNumberOfBytesRead =', lpNumberOfBytesRead, ' nSize =', nSize

self.CheckGuardSignature()
return data

Expand Down
9 changes: 4 additions & 5 deletions pywinauto/tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,16 @@ def run_tests(controls, tests_to_run = None, test_visible_only = True):

def get_bug_as_string(bug):
ctrls, info, bug_type, is_in_ref = bug

header = ["BugType:", str(bug_type), str(is_in_ref)]

for i in info:
header.append(six.text_type(i))
header.append(six.text_type(info[i]))

lines = []
lines.append(" ".join(header))

for i, ctrl in enumerate(ctrls):
lines.append(u'\t"%s" "%s" (%d %d %d %d) Vis: %d' % (
ctrl.window_text(),
Expand All @@ -81,7 +81,7 @@ def get_bug_as_string(bug):
ctrl.rectangle().right,
ctrl.rectangle().bottom,
ctrl.is_visible(),))

return u"\n".join(lines)


Expand All @@ -100,7 +100,6 @@ def print_bugs(bugs):
print(six.text_type(i).encode('utf-8'), six.text_type(info[i]).encode('utf-8'))
print()


for i, ctrl in enumerate(ctrls):
print('\t"%s" "%s" (%d %d %d %d) Vis: %d' % (
ctrl.window_text().encode('utf-8'),
Expand Down
2 changes: 1 addition & 1 deletion pywinauto/timings.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ def wait_until_decorator(func):
@wraps(func)
def wrapper(*args):
"""pre-callback, target function call and post-callback"""
return wait_until(timeout, retry_interval,
return wait_until(timeout, retry_interval,
func, value, op, *args)
return wrapper
return wait_until_decorator
Expand Down
24 changes: 12 additions & 12 deletions pywinauto/uia_defines.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class _Singleton(type):

"""
Singleton metaclass implementation from StackOverflow
http://stackoverflow.com/q/6760685/3648361
"""

Expand Down Expand Up @@ -76,15 +76,15 @@ def __init__(self):
self.root = self.iuia.GetRootElement()

self.get_focused_element = self.iuia.GetFocusedElement

# collect all known control types
start_len = len('UIA_')
end_len = len('ControlTypeId')
self._control_types = [attr[start_len:-end_len] for attr in dir(self.UIA_dll) if attr.endswith('ControlTypeId')]

self.known_control_types = {} # string id: numeric id
self.known_control_type_ids = {} # numeric id: string id

for ctrl_type in self._control_types:
type_id_name = 'UIA_' + ctrl_type + 'ControlTypeId'
type_id = self.UIA_dll.__getattribute__(type_id_name)
Expand All @@ -97,17 +97,17 @@ def build_condition(self, process=None, class_name=None, title=None, control_typ
conditions = []
if process:
conditions.append(self.iuia.CreatePropertyCondition(self.UIA_dll.UIA_ProcessIdPropertyId, process))

if class_name:
conditions.append(self.iuia.CreatePropertyCondition(self.UIA_dll.UIA_ClassNamePropertyId, class_name))

if control_type:
if isinstance(control_type, six.string_types):
control_type = self.known_control_types[control_type]
elif not isinstance(control_type, int):
raise TypeError('control_type must be string or integer')
conditions.append(self.iuia.CreatePropertyCondition(self.UIA_dll.UIA_ControlTypePropertyId, control_type))

if title:
# TODO: CreatePropertyConditionEx with PropertyConditionFlags_IgnoreCase
conditions.append(self.iuia.CreatePropertyCondition(self.UIA_dll.UIA_NamePropertyId, title))
Expand All @@ -118,10 +118,10 @@ def build_condition(self, process=None, class_name=None, title=None, control_typ

if len(conditions) > 1:
return self.iuia.CreateAndConditionFromArray(conditions)

if len(conditions) == 1:
return conditions[0]

return self.true_condition

# Build a list of named constants that identify Microsoft UI Automation
Expand Down Expand Up @@ -152,7 +152,7 @@ def _build_pattern_ids_dic():
# Windows 10 and later
'CustomNavigation'
]

ptrn_ids_dic = {}

# Loop over the all base names and try to retrieve control patterns
Expand All @@ -169,7 +169,7 @@ def _build_pattern_ids_dic():

# Update the registry of known patterns
ptrn_ids_dic[ptrn_name] = (ptrn_id, klass)

return ptrn_ids_dic

pattern_ids = _build_pattern_ids_dic()
Expand All @@ -179,7 +179,7 @@ def _build_pattern_ids_dic():
# enum ToggleState {
# ToggleState_Off,
# ToggleState_On,
# ToggleState_Indeterminate
# ToggleState_Indeterminate
# };
# The definition can also be found in the comtypes package
# In a file automatically generated according to UIAutomation GUID:
Expand Down
Loading

0 comments on commit f6dc79d

Please sign in to comment.