Debian Codegraph @

tests/test_pyautogui.py

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
1 from __future__ import division, print_function
2
3 import os
4 import random
5 import sys
6 import threading
7 import time
8 import unittest
9 import doctest
10 from collections import namedtuple # Added in Python 2.6.
11
12 import pyautogui
13
14 # Make the cwd the folder that this test_pyautogui.py file resides in:
15 scriptFolder = os.path.dirname(os.path.realpath(__file__))
16 os.chdir(scriptFolder)
17
18 runningOnPython2 = sys.version_info[0] == 2
19
20 if runningOnPython2:
21 INPUT_FUNC = raw_input
22 else:
23 INPUT_FUNC = input
24
25
26 try:
27 import pytweening
28 except:
29 assert False, "The PyTweening module must be installed to complete the tests: pip install pytweening"
30
31 try:
32 import pyscreeze
33 except:
34 assert False, "The PyScreeze module must be installed to complete the tests: pip install pyscreeze"
35
36 """
37 # TODO - pygetwindow is Windows-only for now, so don't require it for testing just yet.
38 try:
39 import pygetwindow
40 except:
41 assert False, 'The PyGetWindow module must be installed to complete the tests: pip install pygetwindow'
42 """
43
44 # TODO - note that currently most of the click-related functionality is not tested.
45
46
47 class P(namedtuple("P", ["x", "y"])):
48 """Simple, immutable, 2D point/vector class, including some basic
49 arithmetic functions.
50 """
51
52 def __str__(self):
53 return "{0},{1}".format(self.x, self.y)
54
55 def __repr__(self):
56 return "P({0}, {1})".format(self.x, self.y)
57
58 def __eq__(self, other):
59 return self.x == other.x and self.y == other.y
60
61 def __ne__(self, other):
62 return self.x != other.x and self.y != other.y
63
64 def __add__(self, other):
65 return P(self.x + other.x, self.y + other.y)
66
67 def __sub__(self, other):
68 return P(self.x - other.x, self.y - other.y)
69
70 def __mul__(self, other):
71 return P(self.x * other, self.y * other)
72
73 def __rmul__(self, other):
74 return self.__mul__(other)
75
76 def __floordiv__(self, other):
77 return P(self.x // other, self.y // other)
78
79 def __truediv__(self, other):
80 return P(self.x / other, self.y / other)
81
82 def __neg__(self):
83 return P(-self.x, -self.y)
84
85 def __pos__(self):
86 return self
87
88 def __neg__(self):
89 return P(abs(self.x), abs(self.y))
90
91
92 class TestGeneral(unittest.TestCase):
93 def setUp(self):
94 self.oldFailsafeSetting = pyautogui.FAILSAFE
95 pyautogui.FAILSAFE = False
96 pyautogui.moveTo(42, 42) # make sure failsafe isn't triggered during this test
97 pyautogui.FAILSAFE = True
98
99 def tearDown(self):
100 pyautogui.FAILSAFE = self.oldFailsafeSetting
101
102 def test_accessibleNames(self):
103 # Check that all the functions are defined.
104
105 # mouse-related API
106 pyautogui.moveTo
107 pyautogui.moveRel
108 pyautogui.dragTo
109 pyautogui.dragRel
110 pyautogui.mouseDown
111 pyautogui.mouseUp
112 pyautogui.click
113 pyautogui.rightClick
114 pyautogui.doubleClick
115 pyautogui.tripleClick
116
117 # keyboard-related API
118 pyautogui.typewrite
119 pyautogui.hotkey
120 pyautogui.keyDown
121 pyautogui.keyUp
122 pyautogui.press
123 pyautogui.hold
124
125 # The functions implemented in the platform-specific modules should also show up in the pyautogui namespace:
126 pyautogui.position
127 pyautogui.size
128 pyautogui.scroll
129 pyautogui.hscroll
130 pyautogui.vscroll
131
132 # util API
133 pyautogui.KEYBOARD_KEYS
134 pyautogui.isShiftCharacter
135
136 # Screenshot-related API
137 pyautogui.locateAll
138 pyautogui.locate
139 pyautogui.locateOnScreen
140 pyautogui.locateAllOnScreen
141 pyautogui.locateCenterOnScreen
142 pyautogui.center
143 pyautogui.pixelMatchesColor
144 pyautogui.pixel
145 pyautogui.screenshot
146 #pyautogui.grab # grab() was removed, use screenshot()
147
148 # TODO(denilsonsa): I believe we should get rid of these symbols. If someone wants tweening, import pytweening module instead!
149 # Tweening-related API
150 pyautogui.getPointOnLine
151 pyautogui.linear
152 pyautogui.easeInQuad
153 pyautogui.easeOutQuad
154 pyautogui.easeInOutQuad
155 pyautogui.easeInCubic
156 pyautogui.easeOutCubic
157 pyautogui.easeInOutCubic
158 pyautogui.easeInQuart
159 pyautogui.easeOutQuart
160 pyautogui.easeInOutQuart
161 pyautogui.easeInQuint
162 pyautogui.easeOutQuint
163 pyautogui.easeInOutQuint
164 pyautogui.easeInSine
165 pyautogui.easeOutSine
166 pyautogui.easeInOutSine
167 pyautogui.easeInExpo
168 pyautogui.easeOutExpo
169 pyautogui.easeInOutExpo
170 pyautogui.easeInCirc
171 pyautogui.easeOutCirc
172 pyautogui.easeInOutCirc
173 pyautogui.easeInElastic
174 pyautogui.easeOutElastic
175 pyautogui.easeInOutElastic
176 pyautogui.easeInBack
177 pyautogui.easeOutBack
178 pyautogui.easeInOutBack
179 pyautogui.easeInBounce
180 pyautogui.easeOutBounce
181 pyautogui.easeInOutBounce
182
183 def test_size(self):
184 width, height = pyautogui.size()
185
186 self.assertTrue(isinstance(width, int), "Type of width is %s" % (type(width)))
187 self.assertTrue(isinstance(height, int), "Type of height is %s" % (type(height)))
188 self.assertTrue(width > 0, "Width is set to %s" % (width))
189 self.assertTrue(height > 0, "Height is set to %s" % (height))
190
191 def test_position(self):
192 mousex, mousey = pyautogui.position()
193
194 self.assertTrue(isinstance(mousex, int), "Type of mousex is %s" % (type(mousex)))
195 self.assertTrue(isinstance(mousey, int), "Type of mousey is %s" % (type(mousey)))
196
197 # Test passing x and y arguments to position().
198 pyautogui.moveTo(mousex + 1, mousey + 1)
199 x, y = pyautogui.position(mousex, None)
200 self.assertEqual(x, mousex)
201 self.assertNotEqual(y, mousey)
202
203 x, y = pyautogui.position(None, mousey)
204 self.assertNotEqual(x, mousex)
205 self.assertEqual(y, mousey)
206
207 def test_onScreen(self):
208 zero = P(0, 0)
209 xone = P(1, 0)
210 yone = P(0, 1)
211 size = P(*pyautogui.size())
212 half = size / 2
213
214 on_screen = [zero, zero + xone, zero + yone, zero + xone + yone, half, size - xone - yone]
215 off_screen = [zero - xone, zero - yone, zero - xone - yone, size - xone, size - yone, size]
216
217 for value, coords in [(True, on_screen), (False, off_screen)]:
218 for coord in coords:
219 self.assertEqual(
220 value,
221 pyautogui.onScreen(*coord),
222 "onScreen({0}, {1}) should be {2}".format(coord.x, coord.y, value),
223 )
224 self.assertEqual(
225 value,
226 pyautogui.onScreen(list(coord)),
227 "onScreen([{0}, {1}]) should be {2}".format(coord.x, coord.y, value),
228 )
229 self.assertEqual(
230 value,
231 pyautogui.onScreen(tuple(coord)),
232 "onScreen(({0}, {1})) should be {2}".format(coord.x, coord.y, value),
233 )
234 self.assertEqual(
235 value, pyautogui.onScreen(coord), "onScreen({0}) should be {1}".format(repr(coord), value)
236 )
237
238 # These raise PyAutoGUIException.
239 with self.assertRaises(pyautogui.PyAutoGUIException):
240 pyautogui.onScreen([0, 0], 0)
241 with self.assertRaises(pyautogui.PyAutoGUIException):
242 pyautogui.onScreen((0, 0), 0)
243
244 def test_pause(self):
245 oldValue = pyautogui.PAUSE
246
247 startTime = time.time()
248 pyautogui.PAUSE = 0.35 # there should be a 0.35 second pause after each call
249 pyautogui.moveTo(1, 1)
250 pyautogui.moveRel(0, 1)
251 pyautogui.moveTo(1, 1)
252
253 elapsed = time.time() - startTime
•254 self.assertTrue(1.0 < elapsed < 1.5, "Took %s seconds, expected 1.0 < 1.5 seconds." % (elapsed))
255
256 pyautogui.PAUSE = oldValue # restore the old PAUSE value
257
258
259 class TestHelperFunctions(unittest.TestCase):
•260 @unittest.skip("flaky test")
261 def test__normalizeXYArgs(self):
262 self.assertEqual(pyautogui._normalizeXYArgs(1, 2), pyautogui.Point(x=1, y=2))
263 self.assertEqual(pyautogui._normalizeXYArgs((1, 2), None), pyautogui.Point(x=1, y=2))
264 self.assertEqual(pyautogui._normalizeXYArgs([1, 2], None), pyautogui.Point(x=1, y=2))
265
266 pyautogui.useImageNotFoundException()
267 with self.assertRaises(pyautogui.ImageNotFoundException):
268 pyautogui._normalizeXYArgs("100x100blueimage.png", None)
269 pyautogui.useImageNotFoundException(False)
270 self.assertEqual(pyautogui._normalizeXYArgs("100x100blueimage.png", None), None)
271
272
273 class TestDoctests(unittest.TestCase):
274 def test_doctests(self):
275 doctest.testmod(pyautogui)
276
277
278 class TestMouse(unittest.TestCase):
279 # NOTE - The user moving the mouse during many of these tests will cause them to fail.
280
281 # There is no need to test all tweening functions.
282 TWEENS = [
283 "linear",
284 "easeInElastic",
285 "easeOutElastic",
286 "easeInOutElastic",
287 "easeInBack",
288 "easeOutBack",
289 "easeInOutBack",
290 ]
291
292 def setUp(self):
293 self.oldFailsafeSetting = pyautogui.FAILSAFE
294 self.center = P(*pyautogui.size()) // 2
295
296 pyautogui.FAILSAFE = False
297 pyautogui.moveTo(*self.center) # make sure failsafe isn't triggered during this test
298 pyautogui.FAILSAFE = True
299
300 def tearDown(self):
301 pyautogui.FAILSAFE = self.oldFailsafeSetting
302
303 def test_moveTo(self):
304 # moving the mouse
305 desired = self.center
306 pyautogui.moveTo(*desired)
307 mousepos = P(*pyautogui.position())
308 self.assertEqual(mousepos, desired)
309
310 # no coordinate specified (should be a NO-OP)
311 pyautogui.moveTo(None, None)
312 mousepos = P(*pyautogui.position())
313 self.assertEqual(mousepos, desired)
314
315 # moving the mouse to a new location
316 desired += P(42, 42)
317 pyautogui.moveTo(*desired)
318 mousepos = P(*pyautogui.position())
319 self.assertEqual(mousepos, desired)
320
321 # moving the mouse over time (1/5 second)
322 desired -= P(42, 42)
323 pyautogui.moveTo(desired.x, desired.y, duration=0.2)
324 mousepos = P(*pyautogui.position())
325 self.assertEqual(mousepos, desired)
326
327 # Passing a list instead of separate x and y.
328 desired += P(42, 42)
329 pyautogui.moveTo(list(desired))
330 mousepos = P(*pyautogui.position())
331 self.assertEqual(mousepos, desired)
332
333 # Passing a tuple instead of separate x and y.
334 desired += P(42, 42)
335 pyautogui.moveTo(tuple(desired))
336 mousepos = P(*pyautogui.position())
337 self.assertEqual(mousepos, desired)
338
339 # Passing a sequence-like object instead of separate x and y.
340 desired -= P(42, 42)
341 pyautogui.moveTo(desired)
342 mousepos = P(*pyautogui.position())
343 self.assertEqual(mousepos, desired)
344
345 def test_moveToWithTween(self):
346 origin = self.center - P(100, 100)
347 destination = self.center + P(100, 100)
348
349 def resetMouse():
350 pyautogui.moveTo(*origin)
351 mousepos = P(*pyautogui.position())
352 self.assertEqual(mousepos, origin)
353
354 for tweenName in self.TWEENS:
355 tweenFunc = getattr(pyautogui, tweenName)
356 resetMouse()
357 pyautogui.moveTo(destination.x, destination.y, duration=pyautogui.MINIMUM_DURATION * 2, tween=tweenFunc)
358 mousepos = P(*pyautogui.position())
359 self.assertEqual(
360 mousepos,
361 destination,
362 "%s tween move failed. mousepos set to %s instead of %s" % (tweenName, mousepos, destination),
363 )
364
365 def test_moveRel(self):
366 # start at the center
367 desired = self.center
368 pyautogui.moveTo(*desired)
369 mousepos = P(*pyautogui.position())
370 self.assertEqual(mousepos, desired)
371
372 # move down and right
373 desired += P(42, 42)
374 pyautogui.moveRel(42, 42)
375 mousepos = P(*pyautogui.position())
376 self.assertEqual(mousepos, desired)
377
378 # move up and left
379 desired -= P(42, 42)
380 pyautogui.moveRel(-42, -42)
381 mousepos = P(*pyautogui.position())
382 self.assertEqual(mousepos, desired)
383
384 # move right
385 desired += P(42, 0)
386 pyautogui.moveRel(42, 0)
387 mousepos = P(*pyautogui.position())
388 self.assertEqual(mousepos, desired)
389
390 # move down
391 desired += P(0, 42)
392 pyautogui.moveRel(0, 42)
393 mousepos = P(*pyautogui.position())
394 self.assertEqual(mousepos, desired)
395
396 # move left
397 desired += P(-42, 0)
398 pyautogui.moveRel(-42, 0)
399 mousepos = P(*pyautogui.position())
400 self.assertEqual(mousepos, desired)
401
402 # move up
403 desired += P(0, -42)
404 pyautogui.moveRel(0, -42)
405 mousepos = P(*pyautogui.position())
406 self.assertEqual(mousepos, desired)
407
408 # Passing a list instead of separate x and y.
409 desired += P(42, 42)
410 pyautogui.moveRel([42, 42])
411 mousepos = P(*pyautogui.position())
412 self.assertEqual(mousepos, desired)
413
414 # Passing a tuple instead of separate x and y.
415 desired -= P(42, 42)
416 pyautogui.moveRel((-42, -42))
417 mousepos = P(*pyautogui.position())
418 self.assertEqual(mousepos, desired)
419
420 # Passing a sequence-like object instead of separate x and y.
421 desired += P(42, 42)
422 pyautogui.moveRel(P(42, 42))
423 mousepos = P(*pyautogui.position())
424 self.assertEqual(mousepos, desired)
425
426 def test_moveRelWithTween(self):
427 origin = self.center - P(100, 100)
428 delta = P(200, 200)
429 destination = origin + delta
430
431 def resetMouse():
432 pyautogui.moveTo(*origin)
433 mousepos = P(*pyautogui.position())
434 self.assertEqual(mousepos, origin)
435
436 for tweenName in self.TWEENS:
437 tweenFunc = getattr(pyautogui, tweenName)
438 resetMouse()
439 pyautogui.moveRel(delta.x, delta.y, duration=pyautogui.MINIMUM_DURATION * 2, tween=tweenFunc)
440 mousepos = P(*pyautogui.position())
441 self.assertEqual(
442 mousepos,
443 destination,
444 "%s tween move failed. mousepos set to %s instead of %s" % (tweenName, mousepos, destination),
445 )
446
447 def test_scroll(self):
448 # TODO - currently this just checks that scrolling doesn't result in an error.
449 pyautogui.scroll(1)
450 pyautogui.scroll(-1)
451 pyautogui.hscroll(1)
452 pyautogui.hscroll(-1)
453 pyautogui.vscroll(1)
454 pyautogui.vscroll(-1)
455
456
457 def test_mouse_button_swap(self):
458 pass # TODO - I'm not even sure how I could test this in an automated way. We'd need a separate GUI app.
459
460
461 class TestRun(unittest.TestCase):
462 def test_getNumberToken(self):
463 self.assertEqual(pyautogui._getNumberToken("5hello"), "5")
464 self.assertEqual(pyautogui._getNumberToken("-5hello"), "-5")
465 self.assertEqual(pyautogui._getNumberToken("+5hello"), "+5")
466 self.assertEqual(pyautogui._getNumberToken("5.5hello"), "5.5")
467 self.assertEqual(pyautogui._getNumberToken("+5.5hello"), "+5.5")
468 self.assertEqual(pyautogui._getNumberToken("-5.5hello"), "-5.5")
469 self.assertEqual(pyautogui._getNumberToken(" 5hello"), " 5")
470 self.assertEqual(pyautogui._getNumberToken(" -5hello"), " -5")
471 self.assertEqual(pyautogui._getNumberToken(" +5hello"), " +5")
472 self.assertEqual(pyautogui._getNumberToken(" 5.5hello"), " 5.5")
473 self.assertEqual(pyautogui._getNumberToken(" +5.5hello"), " +5.5")
474 self.assertEqual(pyautogui._getNumberToken(" -5.5hello"), " -5.5")
475
476 with self.assertRaises(pyautogui.PyAutoGUIException):
477 pyautogui._getNumberToken("") # Blank string and no number.
478 with self.assertRaises(pyautogui.PyAutoGUIException):
479 pyautogui._getNumberToken("hello") # Missing a number.
480 with self.assertRaises(pyautogui.PyAutoGUIException):
481 pyautogui._getNumberToken(" ") # Missing a number.
482 with self.assertRaises(pyautogui.PyAutoGUIException):
483 pyautogui._getNumberToken("hello 42") # Number is not at the start.
484
485 def test_getQuotedStringToken(self):
486 self.assertEqual(pyautogui._getQuotedStringToken("'hello'world"), "'hello'")
487 self.assertEqual(pyautogui._getQuotedStringToken("''world"), "''")
488 self.assertEqual(pyautogui._getQuotedStringToken(" 'hello'world"), " 'hello'")
489
490 with self.assertRaises(pyautogui.PyAutoGUIException):
491 pyautogui._getQuotedStringToken("xyz") # No quotes.
492 with self.assertRaises(pyautogui.PyAutoGUIException):
493 pyautogui._getQuotedStringToken("xyz") # No quotes.
494 with self.assertRaises(pyautogui.PyAutoGUIException):
495 pyautogui._getQuotedStringToken(" xyz") # No quotes, spaces in front.
496 with self.assertRaises(pyautogui.PyAutoGUIException):
497 pyautogui._getQuotedStringToken("'xyz") # Start quote only.
498 with self.assertRaises(pyautogui.PyAutoGUIException):
499 pyautogui._getQuotedStringToken("xyz'") # End quote only.
500 with self.assertRaises(pyautogui.PyAutoGUIException):
501 pyautogui._getQuotedStringToken('"xyz"') # Double quotes don't count.
502 with self.assertRaises(pyautogui.PyAutoGUIException):
503 pyautogui._getQuotedStringToken("") # Blank string.
504 with self.assertRaises(pyautogui.PyAutoGUIException):
505 pyautogui._getQuotedStringToken("xyz 'hello'") # Quoted string is not at the start.
506
507 def test_getCommaToken(self):
508 self.assertEqual(pyautogui._getCommaToken(","), ",")
509 self.assertEqual(pyautogui._getCommaToken(" ,"), " ,")
510
511 with self.assertRaises(pyautogui.PyAutoGUIException):
512 pyautogui._getCommaToken("") # Blank string.
513 with self.assertRaises(pyautogui.PyAutoGUIException):
514 pyautogui._getCommaToken("hello,") # Comma is not at the start.
515 with self.assertRaises(pyautogui.PyAutoGUIException):
516 pyautogui._getCommaToken("hello") # No comma.
517 with self.assertRaises(pyautogui.PyAutoGUIException):
518 pyautogui._getCommaToken(" ") # No comma.
519
520 def test_getParensCommandStrToken(self):
521 self.assertEqual(pyautogui._getParensCommandStrToken("()"), "()")
522 self.assertEqual(pyautogui._getParensCommandStrToken(" ()"), " ()")
523 self.assertEqual(pyautogui._getParensCommandStrToken("()hello"), "()")
524 self.assertEqual(pyautogui._getParensCommandStrToken(" ()hello"), " ()")
525 self.assertEqual(pyautogui._getParensCommandStrToken("(hello)world"), "(hello)")
526 self.assertEqual(pyautogui._getParensCommandStrToken(" (hello)world"), " (hello)")
527 self.assertEqual(pyautogui._getParensCommandStrToken("(he(ll)(o))world"), "(he(ll)(o))")
528 self.assertEqual(pyautogui._getParensCommandStrToken(" (he(ll)(o))world"), " (he(ll)(o))")
529
530 self.assertEqual(
531 pyautogui._getParensCommandStrToken("(he(ll)(o)))world"), "(he(ll)(o))"
532 ) # Extra close parentheses.
533 self.assertEqual(
534 pyautogui._getParensCommandStrToken(" (he(ll)(o)))world"), " (he(ll)(o))"
535 ) # Extra close parentheses.
536
537 with self.assertRaises(pyautogui.PyAutoGUIException):
538 pyautogui._getParensCommandStrToken("") # Blank string.
539 with self.assertRaises(pyautogui.PyAutoGUIException):
540 pyautogui._getParensCommandStrToken(" ") # No parens.
541 with self.assertRaises(pyautogui.PyAutoGUIException):
542 pyautogui._getParensCommandStrToken("hello") # No parens
543 with self.assertRaises(pyautogui.PyAutoGUIException):
544 pyautogui._getParensCommandStrToken(" (") # No close parenthesis.
545 with self.assertRaises(pyautogui.PyAutoGUIException):
546 pyautogui._getParensCommandStrToken("(he(ll)o") # Not enough close parentheses.
547 with self.assertRaises(pyautogui.PyAutoGUIException):
548 pyautogui._getParensCommandStrToken("") # Blank string.
549
550 def test_tokenizeCommandStr(self):
551 self.assertEqual(pyautogui._tokenizeCommandStr(""), []) # Empty command string.
552 self.assertEqual(pyautogui._tokenizeCommandStr(" "), []) # Whitespace only command string.
553 self.assertEqual(pyautogui._tokenizeCommandStr("c"), ["c"])
554 self.assertEqual(pyautogui._tokenizeCommandStr(" c "), ["c"])
555 self.assertEqual(pyautogui._tokenizeCommandStr("ccc"), ["c", "c", "c"])
556 self.assertEqual(pyautogui._tokenizeCommandStr(" c c c "), ["c", "c", "c"])
557 self.assertEqual(pyautogui._tokenizeCommandStr("clmr"), ["c", "l", "m", "r"])
558 self.assertEqual(pyautogui._tokenizeCommandStr("susdss"), ["su", "sd", "ss"])
559 self.assertEqual(pyautogui._tokenizeCommandStr(" su sd ss "), ["su", "sd", "ss"])
560 self.assertEqual(pyautogui._tokenizeCommandStr("clmrsusdss"), ["c", "l", "m", "r", "su", "sd", "ss"])
561
562 # Do a whole bunch of tests with random no-argument commands with random whitespace.
563 random.seed(42)
564 for i in range(100):
565 commands = []
566 commands.extend(["c"] * random.randint(0, 9))
567 commands.extend(["l"] * random.randint(0, 9))
568 commands.extend(["m"] * random.randint(0, 9))
569 commands.extend(["r"] * random.randint(0, 9))
570 commands.extend(["su"] * random.randint(0, 9))
571 commands.extend(["sd"] * random.randint(0, 9))
572 commands.extend(["ss"] * random.randint(0, 9))
573 random.shuffle(commands)
574 commandStr = []
575 for command in commands:
576 commandStr.append(command)
577 commandStr.append(" " * random.randint(0, 9))
578 commandStr = "".join(commandStr)
579 self.assertEqual(pyautogui._tokenizeCommandStr(commandStr), commands)
580
581 self.assertEqual(pyautogui._tokenizeCommandStr("g10,10"), ["g", "10", "10"])
582 self.assertEqual(pyautogui._tokenizeCommandStr("g 10,10"), ["g", "10", "10"])
583 self.assertEqual(pyautogui._tokenizeCommandStr("g10 ,10"), ["g", "10", "10"])
584 self.assertEqual(pyautogui._tokenizeCommandStr("g10, 10"), ["g", "10", "10"])
585 self.assertEqual(pyautogui._tokenizeCommandStr(" g 10 , 10 "), ["g", "10", "10"])
586 self.assertEqual(pyautogui._tokenizeCommandStr(" g 10 , 10 "), ["g", "10", "10"])
587
588 self.assertEqual(pyautogui._tokenizeCommandStr("g+10,+10"), ["g", "+10", "+10"])
589 self.assertEqual(pyautogui._tokenizeCommandStr("g +10,+10"), ["g", "+10", "+10"])
590 self.assertEqual(pyautogui._tokenizeCommandStr("g+10 ,+10"), ["g", "+10", "+10"])
591 self.assertEqual(pyautogui._tokenizeCommandStr("g+10, +10"), ["g", "+10", "+10"])
592 self.assertEqual(pyautogui._tokenizeCommandStr(" g +10 , +10 "), ["g", "+10", "+10"])
593 self.assertEqual(pyautogui._tokenizeCommandStr(" g +10 , +10 "), ["g", "+10", "+10"])
594
595 self.assertEqual(pyautogui._tokenizeCommandStr("g-10,-10"), ["g", "-10", "-10"])
596 self.assertEqual(pyautogui._tokenizeCommandStr("g -10,-10"), ["g", "-10", "-10"])
597 self.assertEqual(pyautogui._tokenizeCommandStr("g-10 ,-10"), ["g", "-10", "-10"])
598 self.assertEqual(pyautogui._tokenizeCommandStr("g-10, -10"), ["g", "-10", "-10"])
599 self.assertEqual(pyautogui._tokenizeCommandStr(" g -10 , -10 "), ["g", "-10", "-10"])
600 self.assertEqual(pyautogui._tokenizeCommandStr(" g -10 , -10 "), ["g", "-10", "-10"])
601
602 self.assertEqual(pyautogui._tokenizeCommandStr("d10,10"), ["d", "10", "10"])
603
604 self.assertEqual(pyautogui._tokenizeCommandStr("d1,2g3,4"), ["d", "1", "2", "g", "3", "4"])
605
606 self.assertEqual(pyautogui._tokenizeCommandStr("w'hello'"), ["w", "hello"])
607
608 self.assertEqual(
609 pyautogui._tokenizeCommandStr("d1,2w'hello'g3,4"), ["d", "1", "2", "w", "hello", "g", "3", "4"]
610 )
611
612 self.assertEqual(pyautogui._tokenizeCommandStr("s42"), ["s", "42"])
613 self.assertEqual(pyautogui._tokenizeCommandStr("s42.3"), ["s", "42.3"])
614
615 self.assertEqual(pyautogui._tokenizeCommandStr("f10(c)"), ["f", "10", ["c"]])
616 self.assertEqual(pyautogui._tokenizeCommandStr("f10(lmr)"), ["f", "10", ["l", "m", "r"]])
617 self.assertEqual(pyautogui._tokenizeCommandStr("f10(f5(cc))"), ["f", "10", ["f", "5", ["c", "c"]]])
618
619 # TODO add negative cases
620
621 # TODO add mocks for pyautogui for this.
622
623
624 class TypewriteThread(threading.Thread):
625 def __init__(self, msg, interval=0.0):
626 super(TypewriteThread, self).__init__()
627 self.msg = msg
628 self.interval = interval
629
630 def run(self):
631 time.sleep(0.25) # NOTE: BE SURE TO ACCOUNT FOR THIS QUARTER SECOND FOR TIMING TESTS!
632 pyautogui.typewrite(self.msg, self.interval)
633
634
635 class PressThread(threading.Thread):
636 def __init__(self, keysArg):
637 super(PressThread, self).__init__()
638 self.keysArg = keysArg
639
640 def run(self):
641 time.sleep(0.25) # NOTE: BE SURE TO ACCOUNT FOR THIS QUARTER SECOND FOR TIMING TESTS!
642 pyautogui.press(self.keysArg)
643
644
645 class HoldThread(threading.Thread):
646 def __init__(self, holdKeysArg, pressKeysArg=None):
647 super(HoldThread, self).__init__()
648 self.holdKeysArg = holdKeysArg
649 self.pressKeysArg = pressKeysArg
650
651
652 def run(self):
653 time.sleep(0.25) # NOTE: BE SURE TO ACCOUNT FOR THIS QUARTER SECOND FOR TIMING TESTS!
654 with pyautogui.hold(self.holdKeysArg):
655 if self.pressKeysArg is not None:
656 pyautogui.press(self.pressKeysArg)
657 else:
658 pass
659
660
661 class TestKeyboard(unittest.TestCase):
662 # NOTE: The terminal window running this script must be in focus during the keyboard tests.
663 # You cannot run this as a scheduled task or remotely.
664
665 def setUp(self):
666 self.oldFailsafeSetting = pyautogui.FAILSAFE
667 pyautogui.FAILSAFE = False
668 pyautogui.moveTo(42, 42) # make sure failsafe isn't triggered during this test
669 pyautogui.FAILSAFE = True
670
671 def tearDown(self):
672 pyautogui.FAILSAFE = self.oldFailsafeSetting
673
674 def test_typewrite(self):
675 # 'Hello world!\n' test
676 t = TypewriteThread("Hello world!\n")
677 t.start()
678 response = INPUT_FUNC()
679 self.assertEqual(response, "Hello world!")
680
681 # 'Hello world!\n' as a list argument
682 t = TypewriteThread(list("Hello world!\n"))
683 t.start()
684 response = INPUT_FUNC()
685 self.assertEqual(response, "Hello world!")
686
687 # All printable ASCII characters test
688 allKeys = []
689 for c in range(32, 127):
690 allKeys.append(chr(c))
691 allKeys = "".join(allKeys)
692
693 t = TypewriteThread(allKeys + "\n")
694 t.start()
695 response = INPUT_FUNC()
696 self.assertEqual(response, allKeys)
697
698 def checkForValidCharacters(self, msg):
699 for c in msg:
700 self.assertTrue(pyautogui.isValidKey(c), '"%c" is not a valid key on platform %s' % (c, sys.platform))
701
702 def test_typewrite_slow(self):
703
704 # Test out the interval parameter to make sure it adds pauses.
705 t = TypewriteThread("Hello world!\n", 0.1)
706 startTime = time.time()
707 t.start()
708 response = INPUT_FUNC()
709 self.assertEqual(response, "Hello world!")
710 elapsed = time.time() - startTime
711 self.assertTrue(1.0 < elapsed < 2.0, "Took %s seconds, expected 1.0 < x 2.0 seconds." % (elapsed))
712
713 def test_typewrite_editable(self):
714 # Backspace test
715 t = TypewriteThread(["a", "b", "c", "\b", "backspace", "x", "y", "z", "\n"])
716 t.start()
717 response = INPUT_FUNC()
718 self.assertEqual(response, "axyz")
719
720 # TODO - Currently the arrow keys don't seem to work entirely correctly on OS X.
721 if sys.platform != "darwin":
722 # Arrow key test
723 t = TypewriteThread(["a", "b", "c", "left", "left", "right", "x", "\n"])
724 t.start()
725 response = INPUT_FUNC()
726 self.assertEqual(response, "abxc")
727
728 # Del key test
729 t = TypewriteThread(["a", "b", "c", "left", "left", "left", "del", "delete", "\n"])
730 t.start()
731 response = INPUT_FUNC()
732 self.assertEqual(response, "c")
733
734 # Home and end key test
735 t = TypewriteThread(["a", "b", "c", "home", "x", "end", "z", "\n"])
736 t.start()
737 response = INPUT_FUNC()
738 self.assertEqual(response, "xabcz")
739
740 def test_press(self):
741 # '' test
742 t = PressThread("enter")
743 t.start()
744 response = INPUT_FUNC()
745 self.assertEqual(response, "")
746
747 # 'a' test, also test sending list of 1- and multi-length strings
748 t = PressThread(["a", "enter"])
749 t.start()
750 response = INPUT_FUNC()
751 self.assertEqual(response, "a")
752
753 # 'ba' test, also test sending list of 1- and multi-length strings
754 t = PressThread(["a", "left", "b", "enter"])
755 t.start()
756 response = INPUT_FUNC()
757 self.assertEqual(response, "ba")
758
759 def test_hold(self):
760 # '' test
761 t = HoldThread("enter")
762 t.start()
763 response = INPUT_FUNC()
764 self.assertEqual(response, "")
765
766 # 'a' test, also test sending list of 1- and multi-length strings
767 t = HoldThread(["a", "enter"])
768 t.start()
769 response = INPUT_FUNC()
770 self.assertEqual(response, "a")
771
772 # 'ba' test, also test sending list of 1- and multi-length strings
773 t = HoldThread(["a", "left", "b", "enter"])
774 t.start()
775 response = INPUT_FUNC()
776 self.assertEqual(response, "ba")
777
778 def test_press_during_hold(self):
779 # '' test
780 t = HoldThread("shift", "enter")
781 t.start()
782 response = INPUT_FUNC()
783 self.assertEqual(response, "")
784
785 # 'a' test, also test sending list of 1- and multi-length strings
786 t = HoldThread("shift", ["a", "enter"])
787 t.start()
788 response = INPUT_FUNC()
789 self.assertEqual(response, "A")
790
791 # 'ab' test, also test sending list of 1- and multi-length strings
792 t = HoldThread("shift", ["a", "b", "enter"])
793 t.start()
794 response = INPUT_FUNC()
795 self.assertEqual(response, "AB")
796
797 def test_typewrite_space(self):
798 # Backspace test
799 t = TypewriteThread(["space", " ", "\n"]) # test both 'space' and ' '
800 t.start()
801 response = INPUT_FUNC()
802 self.assertEqual(response, " ")
803
804 def test_isShiftCharacter(self):
805 for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + '~!@#$%^&*()_+{}|:"<>?':
806 self.assertTrue(pyautogui.isShiftCharacter(char))
807 for char in "abcdefghijklmnopqrstuvwxyz" + " `1234567890-=,./;'[]\\":
808 self.assertFalse(pyautogui.isShiftCharacter(char))
809
810
811 class TestFailSafe(unittest.TestCase):
812 def test_failsafe(self):
813 self.oldFailsafeSetting = pyautogui.FAILSAFE
814
815 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with
816 for x, y in pyautogui.FAILSAFE_POINTS:
817 pyautogui.FAILSAFE = True
818 # When move(), moveTo(), drag(), or dragTo() moves the mouse to a
819 # failsafe point, it shouldn't raise the fail safe. (This would
820 # be annoying. Only a human moving the mouse to a failsafe point
821 # should trigger the failsafe.)
822 pyautogui.moveTo(x, y)
823
824 pyautogui.FAILSAFE = False
825 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with (for the next iteration)
826
827 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with
828 for x, y in pyautogui.FAILSAFE_POINTS:
829 pyautogui.FAILSAFE = True
830 pyautogui.moveTo(x, y) # This line should not cause the fail safe exception to be raised.
831
832 # A second pyautogui function call to do something while the cursor is in a fail safe point SHOULD raise the failsafe:
833 self.assertRaises(pyautogui.FailSafeException, pyautogui.press, "esc")
834
835 pyautogui.FAILSAFE = False
836 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with (for the next iteration)
837
838 for x, y in pyautogui.FAILSAFE_POINTS:
839 pyautogui.FAILSAFE = False
840 pyautogui.moveTo(x, y) # This line should not cause the fail safe exception to be raised.
841
842 # This line shouldn't cause a failsafe to trigger because FAILSAFE is set to False.
843 pyautogui.press("esc")
844
845 pyautogui.FAILSAFE = self.oldFailsafeSetting
846
847
848 class TestPyScreezeFunctions(unittest.TestCase):
•849 @unittest.skip("flaky test")
850 def test_locateFunctions(self):
851 # TODO - for now, we only test that the "return None" and "raise pyautogui.ImageNotFoundException" is raised.
852
853 pyautogui.useImageNotFoundException()
854 with self.assertRaises(pyautogui.ImageNotFoundException):
855 pyautogui.locate("100x100blueimage.png", "100x100redimage.png")
856 # Commenting out the locateAll*() functions because they return generators, even if the image can't be found. Should they instead raise an exception? This is a question for pyscreeze's design.
857 # with self.assertRaises(pyautogui.ImageNotFoundException):
858 # pyautogui.locateAll('100x100blueimage.png', '100x100redimage.png')
859
860 # with self.assertRaises(pyautogui.ImageNotFoundException):
861 # pyautogui.locateAllOnScreen('100x100blueimage.png') # NOTE: This test fails if there is a blue square visible on the screen.
862 with self.assertRaises(pyautogui.ImageNotFoundException):
863 pyautogui.locateOnScreen(
864 "100x100blueimage.png"
865 ) # NOTE: This test fails if there is a blue square visible on the screen.
866 with self.assertRaises(pyautogui.ImageNotFoundException):
867 pyautogui.locateCenterOnScreen(
868 "100x100blueimage.png"
869 ) # NOTE: This test fails if there is a blue square visible on the screen.
870
871 pyautogui.useImageNotFoundException(False)
872 self.assertEqual(pyautogui.locate("100x100blueimage.png", "100x100redimage.png"), None)
873 # self.assertEqual(pyautogui.locateAll('100x100blueimage.png', '100x100redimage.png'), None)
874 # self.assertEqual(pyautogui.locateAllOnScreen('100x100blueimage.png'), None) # NOTE: This test fails if there is a blue square visible on the screen.
875 self.assertEqual(
876 pyautogui.locateOnScreen("100x100blueimage.png"), None
877 ) # NOTE: This test fails if there is a blue square visible on the screen.
878 self.assertEqual(
879 pyautogui.locateCenterOnScreen("100x100blueimage.png"), None
880 ) # NOTE: This test fails if there is a blue square visible on the screen.
881
882
883 if __name__ == "__main__":
884 unittest.main()