Debian Codegraph @

tests/test_pyautogui.py

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
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 def test__normalizeXYArgs(self):
261 self.assertEqual(pyautogui._normalizeXYArgs(1, 2), pyautogui.Point(x=1, y=2))
262 self.assertEqual(pyautogui._normalizeXYArgs((1, 2), None), pyautogui.Point(x=1, y=2))
263 self.assertEqual(pyautogui._normalizeXYArgs([1, 2], None), pyautogui.Point(x=1, y=2))
264
265 pyautogui.useImageNotFoundException()
266 with self.assertRaises(pyautogui.ImageNotFoundException):
267 pyautogui._normalizeXYArgs("100x100blueimage.png", None)
268 pyautogui.useImageNotFoundException(False)
269 self.assertEqual(pyautogui._normalizeXYArgs("100x100blueimage.png", None), None)
270
271
272 class TestDoctests(unittest.TestCase):
273 def test_doctests(self):
274 doctest.testmod(pyautogui)
275
276
277 class TestMouse(unittest.TestCase):
278 # NOTE - The user moving the mouse during many of these tests will cause them to fail.
279
280 # There is no need to test all tweening functions.
281 TWEENS = [
282 "linear",
283 "easeInElastic",
284 "easeOutElastic",
285 "easeInOutElastic",
286 "easeInBack",
287 "easeOutBack",
288 "easeInOutBack",
289 ]
290
291 def setUp(self):
292 self.oldFailsafeSetting = pyautogui.FAILSAFE
293 self.center = P(*pyautogui.size()) // 2
294
295 pyautogui.FAILSAFE = False
296 pyautogui.moveTo(*self.center) # make sure failsafe isn't triggered during this test
297 pyautogui.FAILSAFE = True
298
299 def tearDown(self):
300 pyautogui.FAILSAFE = self.oldFailsafeSetting
301
302 def test_moveTo(self):
303 # moving the mouse
304 desired = self.center
305 pyautogui.moveTo(*desired)
306 mousepos = P(*pyautogui.position())
307 self.assertEqual(mousepos, desired)
308
309 # no coordinate specified (should be a NO-OP)
310 pyautogui.moveTo(None, None)
311 mousepos = P(*pyautogui.position())
312 self.assertEqual(mousepos, desired)
313
314 # moving the mouse to a new location
315 desired += P(42, 42)
316 pyautogui.moveTo(*desired)
317 mousepos = P(*pyautogui.position())
318 self.assertEqual(mousepos, desired)
319
320 # moving the mouse over time (1/5 second)
321 desired -= P(42, 42)
322 pyautogui.moveTo(desired.x, desired.y, duration=0.2)
323 mousepos = P(*pyautogui.position())
324 self.assertEqual(mousepos, desired)
325
326 # Passing a list instead of separate x and y.
327 desired += P(42, 42)
328 pyautogui.moveTo(list(desired))
329 mousepos = P(*pyautogui.position())
330 self.assertEqual(mousepos, desired)
331
332 # Passing a tuple instead of separate x and y.
333 desired += P(42, 42)
334 pyautogui.moveTo(tuple(desired))
335 mousepos = P(*pyautogui.position())
336 self.assertEqual(mousepos, desired)
337
338 # Passing a sequence-like object instead of separate x and y.
339 desired -= P(42, 42)
340 pyautogui.moveTo(desired)
341 mousepos = P(*pyautogui.position())
342 self.assertEqual(mousepos, desired)
343
344 def test_moveToWithTween(self):
345 origin = self.center - P(100, 100)
346 destination = self.center + P(100, 100)
347
348 def resetMouse():
349 pyautogui.moveTo(*origin)
350 mousepos = P(*pyautogui.position())
351 self.assertEqual(mousepos, origin)
352
353 for tweenName in self.TWEENS:
354 tweenFunc = getattr(pyautogui, tweenName)
355 resetMouse()
356 pyautogui.moveTo(destination.x, destination.y, duration=pyautogui.MINIMUM_DURATION * 2, tween=tweenFunc)
357 mousepos = P(*pyautogui.position())
358 self.assertEqual(
359 mousepos,
360 destination,
361 "%s tween move failed. mousepos set to %s instead of %s" % (tweenName, mousepos, destination),
362 )
363
364 def test_moveRel(self):
365 # start at the center
366 desired = self.center
367 pyautogui.moveTo(*desired)
368 mousepos = P(*pyautogui.position())
369 self.assertEqual(mousepos, desired)
370
371 # move down and right
372 desired += P(42, 42)
373 pyautogui.moveRel(42, 42)
374 mousepos = P(*pyautogui.position())
375 self.assertEqual(mousepos, desired)
376
377 # move up and left
378 desired -= P(42, 42)
379 pyautogui.moveRel(-42, -42)
380 mousepos = P(*pyautogui.position())
381 self.assertEqual(mousepos, desired)
382
383 # move right
384 desired += P(42, 0)
385 pyautogui.moveRel(42, 0)
386 mousepos = P(*pyautogui.position())
387 self.assertEqual(mousepos, desired)
388
389 # move down
390 desired += P(0, 42)
391 pyautogui.moveRel(0, 42)
392 mousepos = P(*pyautogui.position())
393 self.assertEqual(mousepos, desired)
394
395 # move left
396 desired += P(-42, 0)
397 pyautogui.moveRel(-42, 0)
398 mousepos = P(*pyautogui.position())
399 self.assertEqual(mousepos, desired)
400
401 # move up
402 desired += P(0, -42)
403 pyautogui.moveRel(0, -42)
404 mousepos = P(*pyautogui.position())
405 self.assertEqual(mousepos, desired)
406
407 # Passing a list instead of separate x and y.
408 desired += P(42, 42)
409 pyautogui.moveRel([42, 42])
410 mousepos = P(*pyautogui.position())
411 self.assertEqual(mousepos, desired)
412
413 # Passing a tuple instead of separate x and y.
414 desired -= P(42, 42)
415 pyautogui.moveRel((-42, -42))
416 mousepos = P(*pyautogui.position())
417 self.assertEqual(mousepos, desired)
418
419 # Passing a sequence-like object instead of separate x and y.
420 desired += P(42, 42)
421 pyautogui.moveRel(P(42, 42))
422 mousepos = P(*pyautogui.position())
423 self.assertEqual(mousepos, desired)
424
425 def test_moveRelWithTween(self):
426 origin = self.center - P(100, 100)
427 delta = P(200, 200)
428 destination = origin + delta
429
430 def resetMouse():
431 pyautogui.moveTo(*origin)
432 mousepos = P(*pyautogui.position())
433 self.assertEqual(mousepos, origin)
434
435 for tweenName in self.TWEENS:
436 tweenFunc = getattr(pyautogui, tweenName)
437 resetMouse()
438 pyautogui.moveRel(delta.x, delta.y, duration=pyautogui.MINIMUM_DURATION * 2, tween=tweenFunc)
439 mousepos = P(*pyautogui.position())
440 self.assertEqual(
441 mousepos,
442 destination,
443 "%s tween move failed. mousepos set to %s instead of %s" % (tweenName, mousepos, destination),
444 )
445
446 def test_scroll(self):
447 # TODO - currently this just checks that scrolling doesn't result in an error.
448 pyautogui.scroll(1)
449 pyautogui.scroll(-1)
450 pyautogui.hscroll(1)
451 pyautogui.hscroll(-1)
452 pyautogui.vscroll(1)
453 pyautogui.vscroll(-1)
454
455
456 def test_mouse_button_swap(self):
457 pass # TODO - I'm not even sure how I could test this in an automated way. We'd need a separate GUI app.
458
459
460 class TestRun(unittest.TestCase):
461 def test_getNumberToken(self):
462 self.assertEqual(pyautogui._getNumberToken("5hello"), "5")
463 self.assertEqual(pyautogui._getNumberToken("-5hello"), "-5")
464 self.assertEqual(pyautogui._getNumberToken("+5hello"), "+5")
465 self.assertEqual(pyautogui._getNumberToken("5.5hello"), "5.5")
466 self.assertEqual(pyautogui._getNumberToken("+5.5hello"), "+5.5")
467 self.assertEqual(pyautogui._getNumberToken("-5.5hello"), "-5.5")
468 self.assertEqual(pyautogui._getNumberToken(" 5hello"), " 5")
469 self.assertEqual(pyautogui._getNumberToken(" -5hello"), " -5")
470 self.assertEqual(pyautogui._getNumberToken(" +5hello"), " +5")
471 self.assertEqual(pyautogui._getNumberToken(" 5.5hello"), " 5.5")
472 self.assertEqual(pyautogui._getNumberToken(" +5.5hello"), " +5.5")
473 self.assertEqual(pyautogui._getNumberToken(" -5.5hello"), " -5.5")
474
475 with self.assertRaises(pyautogui.PyAutoGUIException):
476 pyautogui._getNumberToken("") # Blank string and no number.
477 with self.assertRaises(pyautogui.PyAutoGUIException):
478 pyautogui._getNumberToken("hello") # Missing a number.
479 with self.assertRaises(pyautogui.PyAutoGUIException):
480 pyautogui._getNumberToken(" ") # Missing a number.
481 with self.assertRaises(pyautogui.PyAutoGUIException):
482 pyautogui._getNumberToken("hello 42") # Number is not at the start.
483
484 def test_getQuotedStringToken(self):
485 self.assertEqual(pyautogui._getQuotedStringToken("'hello'world"), "'hello'")
486 self.assertEqual(pyautogui._getQuotedStringToken("''world"), "''")
487 self.assertEqual(pyautogui._getQuotedStringToken(" 'hello'world"), " 'hello'")
488
489 with self.assertRaises(pyautogui.PyAutoGUIException):
490 pyautogui._getQuotedStringToken("xyz") # No quotes.
491 with self.assertRaises(pyautogui.PyAutoGUIException):
492 pyautogui._getQuotedStringToken("xyz") # No quotes.
493 with self.assertRaises(pyautogui.PyAutoGUIException):
494 pyautogui._getQuotedStringToken(" xyz") # No quotes, spaces in front.
495 with self.assertRaises(pyautogui.PyAutoGUIException):
496 pyautogui._getQuotedStringToken("'xyz") # Start quote only.
497 with self.assertRaises(pyautogui.PyAutoGUIException):
498 pyautogui._getQuotedStringToken("xyz'") # End quote only.
499 with self.assertRaises(pyautogui.PyAutoGUIException):
500 pyautogui._getQuotedStringToken('"xyz"') # Double quotes don't count.
501 with self.assertRaises(pyautogui.PyAutoGUIException):
502 pyautogui._getQuotedStringToken("") # Blank string.
503 with self.assertRaises(pyautogui.PyAutoGUIException):
504 pyautogui._getQuotedStringToken("xyz 'hello'") # Quoted string is not at the start.
505
506 def test_getCommaToken(self):
507 self.assertEqual(pyautogui._getCommaToken(","), ",")
508 self.assertEqual(pyautogui._getCommaToken(" ,"), " ,")
509
510 with self.assertRaises(pyautogui.PyAutoGUIException):
511 pyautogui._getCommaToken("") # Blank string.
512 with self.assertRaises(pyautogui.PyAutoGUIException):
513 pyautogui._getCommaToken("hello,") # Comma is not at the start.
514 with self.assertRaises(pyautogui.PyAutoGUIException):
515 pyautogui._getCommaToken("hello") # No comma.
516 with self.assertRaises(pyautogui.PyAutoGUIException):
517 pyautogui._getCommaToken(" ") # No comma.
518
519 def test_getParensCommandStrToken(self):
520 self.assertEqual(pyautogui._getParensCommandStrToken("()"), "()")
521 self.assertEqual(pyautogui._getParensCommandStrToken(" ()"), " ()")
522 self.assertEqual(pyautogui._getParensCommandStrToken("()hello"), "()")
523 self.assertEqual(pyautogui._getParensCommandStrToken(" ()hello"), " ()")
524 self.assertEqual(pyautogui._getParensCommandStrToken("(hello)world"), "(hello)")
525 self.assertEqual(pyautogui._getParensCommandStrToken(" (hello)world"), " (hello)")
526 self.assertEqual(pyautogui._getParensCommandStrToken("(he(ll)(o))world"), "(he(ll)(o))")
527 self.assertEqual(pyautogui._getParensCommandStrToken(" (he(ll)(o))world"), " (he(ll)(o))")
528
529 self.assertEqual(
530 pyautogui._getParensCommandStrToken("(he(ll)(o)))world"), "(he(ll)(o))"
531 ) # Extra close parentheses.
532 self.assertEqual(
533 pyautogui._getParensCommandStrToken(" (he(ll)(o)))world"), " (he(ll)(o))"
534 ) # Extra close parentheses.
535
536 with self.assertRaises(pyautogui.PyAutoGUIException):
537 pyautogui._getParensCommandStrToken("") # Blank string.
538 with self.assertRaises(pyautogui.PyAutoGUIException):
539 pyautogui._getParensCommandStrToken(" ") # No parens.
540 with self.assertRaises(pyautogui.PyAutoGUIException):
541 pyautogui._getParensCommandStrToken("hello") # No parens
542 with self.assertRaises(pyautogui.PyAutoGUIException):
543 pyautogui._getParensCommandStrToken(" (") # No close parenthesis.
544 with self.assertRaises(pyautogui.PyAutoGUIException):
545 pyautogui._getParensCommandStrToken("(he(ll)o") # Not enough close parentheses.
546 with self.assertRaises(pyautogui.PyAutoGUIException):
547 pyautogui._getParensCommandStrToken("") # Blank string.
548
549 def test_tokenizeCommandStr(self):
550 self.assertEqual(pyautogui._tokenizeCommandStr(""), []) # Empty command string.
551 self.assertEqual(pyautogui._tokenizeCommandStr(" "), []) # Whitespace only command string.
552 self.assertEqual(pyautogui._tokenizeCommandStr("c"), ["c"])
553 self.assertEqual(pyautogui._tokenizeCommandStr(" c "), ["c"])
554 self.assertEqual(pyautogui._tokenizeCommandStr("ccc"), ["c", "c", "c"])
555 self.assertEqual(pyautogui._tokenizeCommandStr(" c c c "), ["c", "c", "c"])
556 self.assertEqual(pyautogui._tokenizeCommandStr("clmr"), ["c", "l", "m", "r"])
557 self.assertEqual(pyautogui._tokenizeCommandStr("susdss"), ["su", "sd", "ss"])
558 self.assertEqual(pyautogui._tokenizeCommandStr(" su sd ss "), ["su", "sd", "ss"])
559 self.assertEqual(pyautogui._tokenizeCommandStr("clmrsusdss"), ["c", "l", "m", "r", "su", "sd", "ss"])
560
561 # Do a whole bunch of tests with random no-argument commands with random whitespace.
562 random.seed(42)
563 for i in range(100):
564 commands = []
565 commands.extend(["c"] * random.randint(0, 9))
566 commands.extend(["l"] * random.randint(0, 9))
567 commands.extend(["m"] * random.randint(0, 9))
568 commands.extend(["r"] * random.randint(0, 9))
569 commands.extend(["su"] * random.randint(0, 9))
570 commands.extend(["sd"] * random.randint(0, 9))
571 commands.extend(["ss"] * random.randint(0, 9))
572 random.shuffle(commands)
573 commandStr = []
574 for command in commands:
575 commandStr.append(command)
576 commandStr.append(" " * random.randint(0, 9))
577 commandStr = "".join(commandStr)
578 self.assertEqual(pyautogui._tokenizeCommandStr(commandStr), commands)
579
580 self.assertEqual(pyautogui._tokenizeCommandStr("g10,10"), ["g", "10", "10"])
581 self.assertEqual(pyautogui._tokenizeCommandStr("g 10,10"), ["g", "10", "10"])
582 self.assertEqual(pyautogui._tokenizeCommandStr("g10 ,10"), ["g", "10", "10"])
583 self.assertEqual(pyautogui._tokenizeCommandStr("g10, 10"), ["g", "10", "10"])
584 self.assertEqual(pyautogui._tokenizeCommandStr(" g 10 , 10 "), ["g", "10", "10"])
585 self.assertEqual(pyautogui._tokenizeCommandStr(" g 10 , 10 "), ["g", "10", "10"])
586
587 self.assertEqual(pyautogui._tokenizeCommandStr("g+10,+10"), ["g", "+10", "+10"])
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
594 self.assertEqual(pyautogui._tokenizeCommandStr("g-10,-10"), ["g", "-10", "-10"])
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
601 self.assertEqual(pyautogui._tokenizeCommandStr("d10,10"), ["d", "10", "10"])
602
603 self.assertEqual(pyautogui._tokenizeCommandStr("d1,2g3,4"), ["d", "1", "2", "g", "3", "4"])
604
605 self.assertEqual(pyautogui._tokenizeCommandStr("w'hello'"), ["w", "hello"])
606
607 self.assertEqual(
608 pyautogui._tokenizeCommandStr("d1,2w'hello'g3,4"), ["d", "1", "2", "w", "hello", "g", "3", "4"]
609 )
610
611 self.assertEqual(pyautogui._tokenizeCommandStr("s42"), ["s", "42"])
612 self.assertEqual(pyautogui._tokenizeCommandStr("s42.3"), ["s", "42.3"])
613
614 self.assertEqual(pyautogui._tokenizeCommandStr("f10(c)"), ["f", "10", ["c"]])
615 self.assertEqual(pyautogui._tokenizeCommandStr("f10(lmr)"), ["f", "10", ["l", "m", "r"]])
616 self.assertEqual(pyautogui._tokenizeCommandStr("f10(f5(cc))"), ["f", "10", ["f", "5", ["c", "c"]]])
617
618 # TODO add negative cases
619
620 # TODO add mocks for pyautogui for this.
621
622
623 class TypewriteThread(threading.Thread):
624 def __init__(self, msg, interval=0.0):
625 super(TypewriteThread, self).__init__()
626 self.msg = msg
627 self.interval = interval
628
629 def run(self):
630 time.sleep(0.25) # NOTE: BE SURE TO ACCOUNT FOR THIS QUARTER SECOND FOR TIMING TESTS!
631 pyautogui.typewrite(self.msg, self.interval)
632
633
634 class PressThread(threading.Thread):
635 def __init__(self, keysArg):
636 super(PressThread, self).__init__()
637 self.keysArg = keysArg
638
639 def run(self):
640 time.sleep(0.25) # NOTE: BE SURE TO ACCOUNT FOR THIS QUARTER SECOND FOR TIMING TESTS!
641 pyautogui.press(self.keysArg)
642
643
644 class HoldThread(threading.Thread):
645 def __init__(self, holdKeysArg, pressKeysArg=None):
646 super(HoldThread, self).__init__()
647 self.holdKeysArg = holdKeysArg
648 self.pressKeysArg = pressKeysArg
649
650
651 def run(self):
652 time.sleep(0.25) # NOTE: BE SURE TO ACCOUNT FOR THIS QUARTER SECOND FOR TIMING TESTS!
653 with pyautogui.hold(self.holdKeysArg):
654 if self.pressKeysArg is not None:
655 pyautogui.press(self.pressKeysArg)
656 else:
657 pass
658
659
660 class TestKeyboard(unittest.TestCase):
661 # NOTE: The terminal window running this script must be in focus during the keyboard tests.
662 # You cannot run this as a scheduled task or remotely.
663
664 def setUp(self):
665 self.oldFailsafeSetting = pyautogui.FAILSAFE
666 pyautogui.FAILSAFE = False
667 pyautogui.moveTo(42, 42) # make sure failsafe isn't triggered during this test
668 pyautogui.FAILSAFE = True
669
670 def tearDown(self):
671 pyautogui.FAILSAFE = self.oldFailsafeSetting
672
673 def test_typewrite(self):
674 # 'Hello world!\n' test
675 t = TypewriteThread("Hello world!\n")
676 t.start()
677 response = INPUT_FUNC()
678 self.assertEqual(response, "Hello world!")
679
680 # 'Hello world!\n' as a list argument
681 t = TypewriteThread(list("Hello world!\n"))
682 t.start()
683 response = INPUT_FUNC()
684 self.assertEqual(response, "Hello world!")
685
686 # All printable ASCII characters test
687 allKeys = []
688 for c in range(32, 127):
689 allKeys.append(chr(c))
690 allKeys = "".join(allKeys)
691
692 t = TypewriteThread(allKeys + "\n")
693 t.start()
694 response = INPUT_FUNC()
695 self.assertEqual(response, allKeys)
696
697 def checkForValidCharacters(self, msg):
698 for c in msg:
699 self.assertTrue(pyautogui.isValidKey(c), '"%c" is not a valid key on platform %s' % (c, sys.platform))
700
701 def test_typewrite_slow(self):
702
703 # Test out the interval parameter to make sure it adds pauses.
704 t = TypewriteThread("Hello world!\n", 0.1)
705 startTime = time.time()
706 t.start()
707 response = INPUT_FUNC()
708 self.assertEqual(response, "Hello world!")
709 elapsed = time.time() - startTime
710 self.assertTrue(1.0 < elapsed < 2.0, "Took %s seconds, expected 1.0 < x 2.0 seconds." % (elapsed))
711
712 def test_typewrite_editable(self):
713 # Backspace test
714 t = TypewriteThread(["a", "b", "c", "\b", "backspace", "x", "y", "z", "\n"])
715 t.start()
716 response = INPUT_FUNC()
717 self.assertEqual(response, "axyz")
718
719 # TODO - Currently the arrow keys don't seem to work entirely correctly on OS X.
720 if sys.platform != "darwin":
721 # Arrow key test
722 t = TypewriteThread(["a", "b", "c", "left", "left", "right", "x", "\n"])
723 t.start()
724 response = INPUT_FUNC()
725 self.assertEqual(response, "abxc")
726
727 # Del key test
728 t = TypewriteThread(["a", "b", "c", "left", "left", "left", "del", "delete", "\n"])
729 t.start()
730 response = INPUT_FUNC()
731 self.assertEqual(response, "c")
732
733 # Home and end key test
734 t = TypewriteThread(["a", "b", "c", "home", "x", "end", "z", "\n"])
735 t.start()
736 response = INPUT_FUNC()
737 self.assertEqual(response, "xabcz")
738
739 def test_press(self):
740 # '' test
741 t = PressThread("enter")
742 t.start()
743 response = INPUT_FUNC()
744 self.assertEqual(response, "")
745
746 # 'a' test, also test sending list of 1- and multi-length strings
747 t = PressThread(["a", "enter"])
748 t.start()
749 response = INPUT_FUNC()
750 self.assertEqual(response, "a")
751
752 # 'ba' test, also test sending list of 1- and multi-length strings
753 t = PressThread(["a", "left", "b", "enter"])
754 t.start()
755 response = INPUT_FUNC()
756 self.assertEqual(response, "ba")
757
758 def test_hold(self):
759 # '' test
760 t = HoldThread("enter")
761 t.start()
762 response = INPUT_FUNC()
763 self.assertEqual(response, "")
764
765 # 'a' test, also test sending list of 1- and multi-length strings
766 t = HoldThread(["a", "enter"])
767 t.start()
768 response = INPUT_FUNC()
769 self.assertEqual(response, "a")
770
771 # 'ba' test, also test sending list of 1- and multi-length strings
772 t = HoldThread(["a", "left", "b", "enter"])
773 t.start()
774 response = INPUT_FUNC()
775 self.assertEqual(response, "ba")
776
777 def test_press_during_hold(self):
778 # '' test
779 t = HoldThread("shift", "enter")
780 t.start()
781 response = INPUT_FUNC()
782 self.assertEqual(response, "")
783
784 # 'a' test, also test sending list of 1- and multi-length strings
785 t = HoldThread("shift", ["a", "enter"])
786 t.start()
787 response = INPUT_FUNC()
788 self.assertEqual(response, "A")
789
790 # 'ab' test, also test sending list of 1- and multi-length strings
791 t = HoldThread("shift", ["a", "b", "enter"])
792 t.start()
793 response = INPUT_FUNC()
794 self.assertEqual(response, "AB")
795
796 def test_typewrite_space(self):
797 # Backspace test
798 t = TypewriteThread(["space", " ", "\n"]) # test both 'space' and ' '
799 t.start()
800 response = INPUT_FUNC()
801 self.assertEqual(response, " ")
802
803 def test_isShiftCharacter(self):
804 for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + '~!@#$%^&*()_+{}|:"<>?':
805 self.assertTrue(pyautogui.isShiftCharacter(char))
806 for char in "abcdefghijklmnopqrstuvwxyz" + " `1234567890-=,./;'[]\\":
807 self.assertFalse(pyautogui.isShiftCharacter(char))
808
809
810 class TestFailSafe(unittest.TestCase):
811 def test_failsafe(self):
812 self.oldFailsafeSetting = pyautogui.FAILSAFE
813
814 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with
815 for x, y in pyautogui.FAILSAFE_POINTS:
816 pyautogui.FAILSAFE = True
817 # When move(), moveTo(), drag(), or dragTo() moves the mouse to a
818 # failsafe point, it shouldn't raise the fail safe. (This would
819 # be annoying. Only a human moving the mouse to a failsafe point
820 # should trigger the failsafe.)
821 pyautogui.moveTo(x, y)
822
823 pyautogui.FAILSAFE = False
824 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with (for the next iteration)
825
826 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with
827 for x, y in pyautogui.FAILSAFE_POINTS:
828 pyautogui.FAILSAFE = True
829 pyautogui.moveTo(x, y) # This line should not cause the fail safe exception to be raised.
830
831 # A second pyautogui function call to do something while the cursor is in a fail safe point SHOULD raise the failsafe:
832 self.assertRaises(pyautogui.FailSafeException, pyautogui.press, "esc")
833
834 pyautogui.FAILSAFE = False
835 pyautogui.moveTo(1, 1) # make sure mouse is not in failsafe position to begin with (for the next iteration)
836
837 for x, y in pyautogui.FAILSAFE_POINTS:
838 pyautogui.FAILSAFE = False
839 pyautogui.moveTo(x, y) # This line should not cause the fail safe exception to be raised.
840
841 # This line shouldn't cause a failsafe to trigger because FAILSAFE is set to False.
842 pyautogui.press("esc")
843
844 pyautogui.FAILSAFE = self.oldFailsafeSetting
845
846
847 class TestPyScreezeFunctions(unittest.TestCase):
848 def test_locateFunctions(self):
849 # TODO - for now, we only test that the "return None" and "raise pyautogui.ImageNotFoundException" is raised.
850
851 pyautogui.useImageNotFoundException()
852 with self.assertRaises(pyautogui.ImageNotFoundException):
853 pyautogui.locate("100x100blueimage.png", "100x100redimage.png")
854 # 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.
855 # with self.assertRaises(pyautogui.ImageNotFoundException):
856 # pyautogui.locateAll('100x100blueimage.png', '100x100redimage.png')
857
858 # with self.assertRaises(pyautogui.ImageNotFoundException):
859 # pyautogui.locateAllOnScreen('100x100blueimage.png') # NOTE: This test fails if there is a blue square visible on the screen.
860 with self.assertRaises(pyautogui.ImageNotFoundException):
861 pyautogui.locateOnScreen(
862 "100x100blueimage.png"
863 ) # NOTE: This test fails if there is a blue square visible on the screen.
864 with self.assertRaises(pyautogui.ImageNotFoundException):
865 pyautogui.locateCenterOnScreen(
866 "100x100blueimage.png"
867 ) # NOTE: This test fails if there is a blue square visible on the screen.
868
869 pyautogui.useImageNotFoundException(False)
870 self.assertEqual(pyautogui.locate("100x100blueimage.png", "100x100redimage.png"), None)
871 # self.assertEqual(pyautogui.locateAll('100x100blueimage.png', '100x100redimage.png'), None)
872 # self.assertEqual(pyautogui.locateAllOnScreen('100x100blueimage.png'), None) # NOTE: This test fails if there is a blue square visible on the screen.
873 self.assertEqual(
874 pyautogui.locateOnScreen("100x100blueimage.png"), None
875 ) # NOTE: This test fails if there is a blue square visible on the screen.
876 self.assertEqual(
877 pyautogui.locateCenterOnScreen("100x100blueimage.png"), None
878 ) # NOTE: This test fails if there is a blue square visible on the screen.
879
880
881 if __name__ == "__main__":
882 unittest.main()