Set PYTHONUNBUFFERED on shell startup.
[emacs.git] / test / automated / python-tests.el
blobf84ded8cad20f4e02a6d334d4c679a112ead5b93
1 ;;; python-tests.el --- Test suite for python.el
3 ;; Copyright (C) 2013-2014 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
7 ;; GNU Emacs is free software: you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
20 ;;; Commentary:
22 ;;; Code:
24 (require 'ert)
25 (require 'python)
27 (defmacro python-tests-with-temp-buffer (contents &rest body)
28 "Create a `python-mode' enabled temp buffer with CONTENTS.
29 BODY is code to be executed within the temp buffer. Point is
30 always located at the beginning of buffer."
31 (declare (indent 1) (debug t))
32 `(with-temp-buffer
33 (python-mode)
34 (insert ,contents)
35 (goto-char (point-min))
36 ,@body))
38 (defmacro python-tests-with-temp-file (contents &rest body)
39 "Create a `python-mode' enabled file with CONTENTS.
40 BODY is code to be executed within the temp buffer. Point is
41 always located at the beginning of buffer."
42 (declare (indent 1) (debug t))
43 ;; temp-file never actually used for anything?
44 `(let* ((temp-file (make-temp-file "python-tests" nil ".py"))
45 (buffer (find-file-noselect temp-file)))
46 (unwind-protect
47 (with-current-buffer buffer
48 (python-mode)
49 (insert ,contents)
50 (goto-char (point-min))
51 ,@body)
52 (and buffer (kill-buffer buffer))
53 (delete-file temp-file))))
55 (defun python-tests-look-at (string &optional num restore-point)
56 "Move point at beginning of STRING in the current buffer.
57 Optional argument NUM defaults to 1 and is an integer indicating
58 how many occurrences must be found, when positive the search is
59 done forwards, otherwise backwards. When RESTORE-POINT is
60 non-nil the point is not moved but the position found is still
61 returned. When searching forward and point is already looking at
62 STRING, it is skipped so the next STRING occurrence is selected."
63 (let* ((num (or num 1))
64 (starting-point (point))
65 (string (regexp-quote string))
66 (search-fn (if (> num 0) #'re-search-forward #'re-search-backward))
67 (deinc-fn (if (> num 0) #'1- #'1+))
68 (found-point))
69 (prog2
70 (catch 'exit
71 (while (not (= num 0))
72 (when (and (> num 0)
73 (looking-at string))
74 ;; Moving forward and already looking at STRING, skip it.
75 (forward-char (length (match-string-no-properties 0))))
76 (and (not (funcall search-fn string nil t))
77 (throw 'exit t))
78 (when (> num 0)
79 ;; `re-search-forward' leaves point at the end of the
80 ;; occurrence, move back so point is at the beginning
81 ;; instead.
82 (forward-char (- (length (match-string-no-properties 0)))))
83 (setq
84 num (funcall deinc-fn num)
85 found-point (point))))
86 found-point
87 (and restore-point (goto-char starting-point)))))
89 (defun python-tests-self-insert (char-or-str)
90 "Call `self-insert-command' for chars in CHAR-OR-STR."
91 (let ((chars
92 (cond
93 ((characterp char-or-str)
94 (list char-or-str))
95 ((stringp char-or-str)
96 (string-to-list char-or-str))
97 ((not
98 (cl-remove-if #'characterp char-or-str))
99 char-or-str)
100 (t (error "CHAR-OR-STR must be a char, string, or list of char")))))
101 (mapc
102 (lambda (char)
103 (let ((last-command-event char))
104 (call-interactively 'self-insert-command)))
105 chars)))
108 ;;; Tests for your tests, so you can test while you test.
110 (ert-deftest python-tests-look-at-1 ()
111 "Test forward movement."
112 (python-tests-with-temp-buffer
113 "Lorem ipsum dolor sit amet, consectetur adipisicing elit,
114 sed do eiusmod tempor incididunt ut labore et dolore magna
115 aliqua."
116 (let ((expected (save-excursion
117 (dotimes (i 3)
118 (re-search-forward "et" nil t))
119 (forward-char -2)
120 (point))))
121 (should (= (python-tests-look-at "et" 3 t) expected))
122 ;; Even if NUM is bigger than found occurrences the point of last
123 ;; one should be returned.
124 (should (= (python-tests-look-at "et" 6 t) expected))
125 ;; If already looking at STRING, it should skip it.
126 (dotimes (i 2) (re-search-forward "et"))
127 (forward-char -2)
128 (should (= (python-tests-look-at "et") expected)))))
130 (ert-deftest python-tests-look-at-2 ()
131 "Test backward movement."
132 (python-tests-with-temp-buffer
133 "Lorem ipsum dolor sit amet, consectetur adipisicing elit,
134 sed do eiusmod tempor incididunt ut labore et dolore magna
135 aliqua."
136 (let ((expected
137 (save-excursion
138 (re-search-forward "et" nil t)
139 (forward-char -2)
140 (point))))
141 (dotimes (i 3)
142 (re-search-forward "et" nil t))
143 (should (= (python-tests-look-at "et" -3 t) expected))
144 (should (= (python-tests-look-at "et" -6 t) expected)))))
147 ;;; Bindings
150 ;;; Python specialized rx
153 ;;; Font-lock and syntax
155 (ert-deftest python-syntax-after-python-backspace ()
156 ;; `python-indent-dedent-line-backspace' garbles syntax
157 :expected-result :failed
158 (python-tests-with-temp-buffer
159 "\"\"\""
160 (goto-char (point-max))
161 (python-indent-dedent-line-backspace 1)
162 (should (string= (buffer-string) "\"\""))
163 (should (null (nth 3 (syntax-ppss))))))
166 ;;; Indentation
168 ;; See: http://www.python.org/dev/peps/pep-0008/#indentation
170 (ert-deftest python-indent-pep8-1 ()
171 "First pep8 case."
172 (python-tests-with-temp-buffer
173 "# Aligned with opening delimiter
174 foo = long_function_name(var_one, var_two,
175 var_three, var_four)
177 (should (eq (car (python-indent-context)) 'no-indent))
178 (should (= (python-indent-calculate-indentation) 0))
179 (python-tests-look-at "foo = long_function_name(var_one, var_two,")
180 (should (eq (car (python-indent-context)) 'after-line))
181 (should (= (python-indent-calculate-indentation) 0))
182 (python-tests-look-at "var_three, var_four)")
183 (should (eq (car (python-indent-context)) 'inside-paren))
184 (should (= (python-indent-calculate-indentation) 25))))
186 (ert-deftest python-indent-pep8-2 ()
187 "Second pep8 case."
188 (python-tests-with-temp-buffer
189 "# More indentation included to distinguish this from the rest.
190 def long_function_name(
191 var_one, var_two, var_three,
192 var_four):
193 print (var_one)
195 (should (eq (car (python-indent-context)) 'no-indent))
196 (should (= (python-indent-calculate-indentation) 0))
197 (python-tests-look-at "def long_function_name(")
198 (should (eq (car (python-indent-context)) 'after-line))
199 (should (= (python-indent-calculate-indentation) 0))
200 (python-tests-look-at "var_one, var_two, var_three,")
201 (should (eq (car (python-indent-context)) 'inside-paren))
202 (should (= (python-indent-calculate-indentation) 8))
203 (python-tests-look-at "var_four):")
204 (should (eq (car (python-indent-context)) 'inside-paren))
205 (should (= (python-indent-calculate-indentation) 8))
206 (python-tests-look-at "print (var_one)")
207 (should (eq (car (python-indent-context)) 'after-beginning-of-block))
208 (should (= (python-indent-calculate-indentation) 4))))
210 (ert-deftest python-indent-pep8-3 ()
211 "Third pep8 case."
212 (python-tests-with-temp-buffer
213 "# Extra indentation is not necessary.
214 foo = long_function_name(
215 var_one, var_two,
216 var_three, var_four)
218 (should (eq (car (python-indent-context)) 'no-indent))
219 (should (= (python-indent-calculate-indentation) 0))
220 (python-tests-look-at "foo = long_function_name(")
221 (should (eq (car (python-indent-context)) 'after-line))
222 (should (= (python-indent-calculate-indentation) 0))
223 (python-tests-look-at "var_one, var_two,")
224 (should (eq (car (python-indent-context)) 'inside-paren))
225 (should (= (python-indent-calculate-indentation) 4))
226 (python-tests-look-at "var_three, var_four)")
227 (should (eq (car (python-indent-context)) 'inside-paren))
228 (should (= (python-indent-calculate-indentation) 4))))
230 (ert-deftest python-indent-after-comment-1 ()
231 "The most simple after-comment case that shouldn't fail."
232 (python-tests-with-temp-buffer
233 "# Contents will be modified to correct indentation
234 class Blag(object):
235 def _on_child_complete(self, child_future):
236 if self.in_terminal_state():
237 pass
238 # We only complete when all our async children have entered a
239 # terminal state. At that point, if any child failed, we fail
240 # with the exception with which the first child failed.
242 (python-tests-look-at "# We only complete")
243 (should (eq (car (python-indent-context)) 'after-line))
244 (should (= (python-indent-calculate-indentation) 8))
245 (python-tests-look-at "# terminal state")
246 (should (eq (car (python-indent-context)) 'after-comment))
247 (should (= (python-indent-calculate-indentation) 8))
248 (python-tests-look-at "# with the exception")
249 (should (eq (car (python-indent-context)) 'after-comment))
250 ;; This one indents relative to previous block, even given the fact
251 ;; that it was under-indented.
252 (should (= (python-indent-calculate-indentation) 4))
253 (python-tests-look-at "# terminal state" -1)
254 ;; It doesn't hurt to check again.
255 (should (eq (car (python-indent-context)) 'after-comment))
256 (python-indent-line)
257 (should (= (current-indentation) 8))
258 (python-tests-look-at "# with the exception")
259 (should (eq (car (python-indent-context)) 'after-comment))
260 ;; Now everything should be lined up.
261 (should (= (python-indent-calculate-indentation) 8))))
263 (ert-deftest python-indent-after-comment-2 ()
264 "Test after-comment in weird cases."
265 (python-tests-with-temp-buffer
266 "# Contents will be modified to correct indentation
267 def func(arg):
268 # I don't do much
269 return arg
270 # This comment is badly indented just because.
271 # But we won't mess with the user in this line.
273 now_we_do_mess_cause_this_is_not_a_comment = 1
275 # yeah, that.
277 (python-tests-look-at "# I don't do much")
278 (should (eq (car (python-indent-context)) 'after-beginning-of-block))
279 (should (= (python-indent-calculate-indentation) 4))
280 (python-tests-look-at "return arg")
281 ;; Comment here just gets ignored, this line is not a comment so
282 ;; the rules won't apply here.
283 (should (eq (car (python-indent-context)) 'after-beginning-of-block))
284 (should (= (python-indent-calculate-indentation) 4))
285 (python-tests-look-at "# This comment is badly")
286 (should (eq (car (python-indent-context)) 'after-line))
287 ;; The return keyword moves indentation backwards 4 spaces, but
288 ;; let's assume this comment was placed there because the user
289 ;; wanted to (manually adding spaces or whatever).
290 (should (= (python-indent-calculate-indentation) 0))
291 (python-tests-look-at "# but we won't mess")
292 (should (eq (car (python-indent-context)) 'after-comment))
293 (should (= (python-indent-calculate-indentation) 4))
294 ;; Behave the same for blank lines: potentially a comment.
295 (forward-line 1)
296 (should (eq (car (python-indent-context)) 'after-comment))
297 (should (= (python-indent-calculate-indentation) 4))
298 (python-tests-look-at "now_we_do_mess")
299 ;; Here is where comment indentation starts to get ignored and
300 ;; where the user can't freely indent anymore.
301 (should (eq (car (python-indent-context)) 'after-line))
302 (should (= (python-indent-calculate-indentation) 0))
303 (python-tests-look-at "# yeah, that.")
304 (should (eq (car (python-indent-context)) 'after-line))
305 (should (= (python-indent-calculate-indentation) 0))))
307 (ert-deftest python-indent-inside-paren-1 ()
308 "The most simple inside-paren case that shouldn't fail."
309 (python-tests-with-temp-buffer
311 data = {
312 'key':
314 'objlist': [
316 'pk': 1,
317 'name': 'first',
320 'pk': 2,
321 'name': 'second',
327 (python-tests-look-at "data = {")
328 (should (eq (car (python-indent-context)) 'after-line))
329 (should (= (python-indent-calculate-indentation) 0))
330 (python-tests-look-at "'key':")
331 (should (eq (car (python-indent-context)) 'inside-paren))
332 (should (= (python-indent-calculate-indentation) 4))
333 (python-tests-look-at "{")
334 (should (eq (car (python-indent-context)) 'inside-paren))
335 (should (= (python-indent-calculate-indentation) 4))
336 (python-tests-look-at "'objlist': [")
337 (should (eq (car (python-indent-context)) 'inside-paren))
338 (should (= (python-indent-calculate-indentation) 8))
339 (python-tests-look-at "{")
340 (should (eq (car (python-indent-context)) 'inside-paren))
341 (should (= (python-indent-calculate-indentation) 12))
342 (python-tests-look-at "'pk': 1,")
343 (should (eq (car (python-indent-context)) 'inside-paren))
344 (should (= (python-indent-calculate-indentation) 16))
345 (python-tests-look-at "'name': 'first',")
346 (should (eq (car (python-indent-context)) 'inside-paren))
347 (should (= (python-indent-calculate-indentation) 16))
348 (python-tests-look-at "},")
349 (should (eq (car (python-indent-context)) 'inside-paren))
350 (should (= (python-indent-calculate-indentation) 12))
351 (python-tests-look-at "{")
352 (should (eq (car (python-indent-context)) 'inside-paren))
353 (should (= (python-indent-calculate-indentation) 12))
354 (python-tests-look-at "'pk': 2,")
355 (should (eq (car (python-indent-context)) 'inside-paren))
356 (should (= (python-indent-calculate-indentation) 16))
357 (python-tests-look-at "'name': 'second',")
358 (should (eq (car (python-indent-context)) 'inside-paren))
359 (should (= (python-indent-calculate-indentation) 16))
360 (python-tests-look-at "}")
361 (should (eq (car (python-indent-context)) 'inside-paren))
362 (should (= (python-indent-calculate-indentation) 12))
363 (python-tests-look-at "]")
364 (should (eq (car (python-indent-context)) 'inside-paren))
365 (should (= (python-indent-calculate-indentation) 8))
366 (python-tests-look-at "}")
367 (should (eq (car (python-indent-context)) 'inside-paren))
368 (should (= (python-indent-calculate-indentation) 4))
369 (python-tests-look-at "}")
370 (should (eq (car (python-indent-context)) 'inside-paren))
371 (should (= (python-indent-calculate-indentation) 0))))
373 (ert-deftest python-indent-inside-paren-2 ()
374 "Another more compact paren group style."
375 (python-tests-with-temp-buffer
377 data = {'key': {
378 'objlist': [
379 {'pk': 1,
380 'name': 'first'},
381 {'pk': 2,
382 'name': 'second'}
386 (python-tests-look-at "data = {")
387 (should (eq (car (python-indent-context)) 'after-line))
388 (should (= (python-indent-calculate-indentation) 0))
389 (python-tests-look-at "'objlist': [")
390 (should (eq (car (python-indent-context)) 'inside-paren))
391 (should (= (python-indent-calculate-indentation) 4))
392 (python-tests-look-at "{'pk': 1,")
393 (should (eq (car (python-indent-context)) 'inside-paren))
394 (should (= (python-indent-calculate-indentation) 8))
395 (python-tests-look-at "'name': 'first'},")
396 (should (eq (car (python-indent-context)) 'inside-paren))
397 (should (= (python-indent-calculate-indentation) 9))
398 (python-tests-look-at "{'pk': 2,")
399 (should (eq (car (python-indent-context)) 'inside-paren))
400 (should (= (python-indent-calculate-indentation) 8))
401 (python-tests-look-at "'name': 'second'}")
402 (should (eq (car (python-indent-context)) 'inside-paren))
403 (should (= (python-indent-calculate-indentation) 9))
404 (python-tests-look-at "]")
405 (should (eq (car (python-indent-context)) 'inside-paren))
406 (should (= (python-indent-calculate-indentation) 4))
407 (python-tests-look-at "}}")
408 (should (eq (car (python-indent-context)) 'inside-paren))
409 (should (= (python-indent-calculate-indentation) 0))
410 (python-tests-look-at "}")
411 (should (eq (car (python-indent-context)) 'inside-paren))
412 (should (= (python-indent-calculate-indentation) 0))))
414 (ert-deftest python-indent-after-block-1 ()
415 "The most simple after-block case that shouldn't fail."
416 (python-tests-with-temp-buffer
418 def foo(a, b, c=True):
420 (should (eq (car (python-indent-context)) 'no-indent))
421 (should (= (python-indent-calculate-indentation) 0))
422 (goto-char (point-max))
423 (should (eq (car (python-indent-context)) 'after-beginning-of-block))
424 (should (= (python-indent-calculate-indentation) 4))))
426 (ert-deftest python-indent-after-block-2 ()
427 "A weird (malformed) multiline block statement."
428 (python-tests-with-temp-buffer
430 def foo(a, b, c={
431 'a':
434 (goto-char (point-max))
435 (should (eq (car (python-indent-context)) 'after-beginning-of-block))
436 (should (= (python-indent-calculate-indentation) 4))))
438 (ert-deftest python-indent-after-backslash-1 ()
439 "The most common case."
440 (python-tests-with-temp-buffer
442 from foo.bar.baz import something, something_1 \\\\
443 something_2 something_3, \\\\
444 something_4, something_5
446 (python-tests-look-at "from foo.bar.baz import something, something_1")
447 (should (eq (car (python-indent-context)) 'after-line))
448 (should (= (python-indent-calculate-indentation) 0))
449 (python-tests-look-at "something_2 something_3,")
450 (should (eq (car (python-indent-context)) 'after-backslash))
451 (should (= (python-indent-calculate-indentation) 4))
452 (python-tests-look-at "something_4, something_5")
453 (should (eq (car (python-indent-context)) 'after-backslash))
454 (should (= (python-indent-calculate-indentation) 4))
455 (goto-char (point-max))
456 (should (eq (car (python-indent-context)) 'after-line))
457 (should (= (python-indent-calculate-indentation) 0))))
459 (ert-deftest python-indent-after-backslash-2 ()
460 "A pretty extreme complicated case."
461 (python-tests-with-temp-buffer
463 objects = Thing.objects.all() \\\\
464 .filter(
465 type='toy',
466 status='bought'
467 ) \\\\
468 .aggregate(
469 Sum('amount')
470 ) \\\\
471 .values_list()
473 (python-tests-look-at "objects = Thing.objects.all()")
474 (should (eq (car (python-indent-context)) 'after-line))
475 (should (= (python-indent-calculate-indentation) 0))
476 (python-tests-look-at ".filter(")
477 (should (eq (car (python-indent-context)) 'after-backslash))
478 (should (= (python-indent-calculate-indentation) 23))
479 (python-tests-look-at "type='toy',")
480 (should (eq (car (python-indent-context)) 'inside-paren))
481 (should (= (python-indent-calculate-indentation) 27))
482 (python-tests-look-at "status='bought'")
483 (should (eq (car (python-indent-context)) 'inside-paren))
484 (should (= (python-indent-calculate-indentation) 27))
485 (python-tests-look-at ") \\\\")
486 (should (eq (car (python-indent-context)) 'inside-paren))
487 (should (= (python-indent-calculate-indentation) 23))
488 (python-tests-look-at ".aggregate(")
489 (should (eq (car (python-indent-context)) 'after-backslash))
490 (should (= (python-indent-calculate-indentation) 23))
491 (python-tests-look-at "Sum('amount')")
492 (should (eq (car (python-indent-context)) 'inside-paren))
493 (should (= (python-indent-calculate-indentation) 27))
494 (python-tests-look-at ") \\\\")
495 (should (eq (car (python-indent-context)) 'inside-paren))
496 (should (= (python-indent-calculate-indentation) 23))
497 (python-tests-look-at ".values_list()")
498 (should (eq (car (python-indent-context)) 'after-backslash))
499 (should (= (python-indent-calculate-indentation) 23))
500 (forward-line 1)
501 (should (eq (car (python-indent-context)) 'after-line))
502 (should (= (python-indent-calculate-indentation) 0))))
504 (ert-deftest python-indent-block-enders-1 ()
505 "Test de-indentation for pass keyword."
506 (python-tests-with-temp-buffer
508 Class foo(object):
510 def bar(self):
511 if self.baz:
512 return (1,
516 else:
517 pass
519 (python-tests-look-at "3)")
520 (forward-line 1)
521 (should (= (python-indent-calculate-indentation) 8))
522 (python-tests-look-at "pass")
523 (forward-line 1)
524 (should (= (python-indent-calculate-indentation) 8))))
526 (ert-deftest python-indent-block-enders-2 ()
527 "Test de-indentation for return keyword."
528 (python-tests-with-temp-buffer
530 Class foo(object):
531 '''raise lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
533 eiusmod tempor incididunt ut labore et dolore magna aliqua.
535 def bar(self):
536 \"return (1, 2, 3).\"
537 if self.baz:
538 return (1,
542 (python-tests-look-at "def")
543 (should (= (python-indent-calculate-indentation) 4))
544 (python-tests-look-at "if")
545 (should (= (python-indent-calculate-indentation) 8))
546 (python-tests-look-at "return")
547 (should (= (python-indent-calculate-indentation) 12))
548 (goto-char (point-max))
549 (should (= (python-indent-calculate-indentation) 8))))
551 (ert-deftest python-indent-block-enders-3 ()
552 "Test de-indentation for continue keyword."
553 (python-tests-with-temp-buffer
555 for element in lst:
556 if element is None:
557 continue
559 (python-tests-look-at "if")
560 (should (= (python-indent-calculate-indentation) 4))
561 (python-tests-look-at "continue")
562 (should (= (python-indent-calculate-indentation) 8))
563 (forward-line 1)
564 (should (= (python-indent-calculate-indentation) 4))))
566 (ert-deftest python-indent-block-enders-4 ()
567 "Test de-indentation for break keyword."
568 (python-tests-with-temp-buffer
570 for element in lst:
571 if element is None:
572 break
574 (python-tests-look-at "if")
575 (should (= (python-indent-calculate-indentation) 4))
576 (python-tests-look-at "break")
577 (should (= (python-indent-calculate-indentation) 8))
578 (forward-line 1)
579 (should (= (python-indent-calculate-indentation) 4))))
581 (ert-deftest python-indent-block-enders-5 ()
582 "Test de-indentation for raise keyword."
583 (python-tests-with-temp-buffer
585 for element in lst:
586 if element is None:
587 raise ValueError('Element cannot be None')
589 (python-tests-look-at "if")
590 (should (= (python-indent-calculate-indentation) 4))
591 (python-tests-look-at "raise")
592 (should (= (python-indent-calculate-indentation) 8))
593 (forward-line 1)
594 (should (= (python-indent-calculate-indentation) 4))))
596 (ert-deftest python-indent-dedenters-1 ()
597 "Test de-indentation for the elif keyword."
598 (python-tests-with-temp-buffer
600 if save:
601 try:
602 write_to_disk(data)
603 finally:
604 cleanup()
605 elif
607 (python-tests-look-at "elif\n")
608 (should (eq (car (python-indent-context)) 'dedenter-statement))
609 (should (= (python-indent-calculate-indentation) 0))
610 (should (equal (python-indent-calculate-levels) '(0)))))
612 (ert-deftest python-indent-dedenters-2 ()
613 "Test de-indentation for the else keyword."
614 (python-tests-with-temp-buffer
616 if save:
617 try:
618 write_to_disk(data)
619 except IOError:
620 msg = 'Error saving to disk'
621 message(msg)
622 logger.exception(msg)
623 except Exception:
624 if hide_details:
625 logger.exception('Unhandled exception')
626 else
627 finally:
628 data.free()
630 (python-tests-look-at "else\n")
631 (should (eq (car (python-indent-context)) 'dedenter-statement))
632 (should (= (python-indent-calculate-indentation) 8))
633 (should (equal (python-indent-calculate-levels) '(0 4 8)))))
635 (ert-deftest python-indent-dedenters-3 ()
636 "Test de-indentation for the except keyword."
637 (python-tests-with-temp-buffer
639 if save:
640 try:
641 write_to_disk(data)
642 except
644 (python-tests-look-at "except\n")
645 (should (eq (car (python-indent-context)) 'dedenter-statement))
646 (should (= (python-indent-calculate-indentation) 4))
647 (should (equal (python-indent-calculate-levels) '(4)))))
649 (ert-deftest python-indent-dedenters-4 ()
650 "Test de-indentation for the finally keyword."
651 (python-tests-with-temp-buffer
653 if save:
654 try:
655 write_to_disk(data)
656 finally
658 (python-tests-look-at "finally\n")
659 (should (eq (car (python-indent-context)) 'dedenter-statement))
660 (should (= (python-indent-calculate-indentation) 4))
661 (should (equal (python-indent-calculate-levels) '(4)))))
663 (ert-deftest python-indent-dedenters-5 ()
664 "Test invalid levels are skipped in a complex example."
665 (python-tests-with-temp-buffer
667 if save:
668 try:
669 write_to_disk(data)
670 except IOError:
671 msg = 'Error saving to disk'
672 message(msg)
673 logger.exception(msg)
674 finally:
675 if cleanup:
676 do_cleanup()
677 else
679 (python-tests-look-at "else\n")
680 (should (eq (car (python-indent-context)) 'dedenter-statement))
681 (should (= (python-indent-calculate-indentation) 8))
682 (should (equal (python-indent-calculate-levels) '(0 8)))))
684 (ert-deftest python-indent-dedenters-6 ()
685 "Test indentation is zero when no opening block for dedenter."
686 (python-tests-with-temp-buffer
688 try:
689 # if save:
690 write_to_disk(data)
691 else
693 (python-tests-look-at "else\n")
694 (should (eq (car (python-indent-context)) 'dedenter-statement))
695 (should (= (python-indent-calculate-indentation) 0))
696 (should (equal (python-indent-calculate-levels) '(0)))))
698 (ert-deftest python-indent-dedenters-7 ()
699 "Test indentation case from Bug#15163."
700 (python-tests-with-temp-buffer
702 if a:
703 if b:
704 pass
705 else:
706 pass
707 else:
709 (python-tests-look-at "else:" 2)
710 (should (eq (car (python-indent-context)) 'dedenter-statement))
711 (should (= (python-indent-calculate-indentation) 0))
712 (should (equal (python-indent-calculate-levels) '(0)))))
714 (ert-deftest python-indent-dedenters-8 ()
715 "Test indentation for Bug#18432."
716 (python-tests-with-temp-buffer
718 if (a == 1 or
719 a == 2):
720 pass
721 elif (a == 3 or
722 a == 4):
724 (python-tests-look-at "a == 4):\n")
725 (should (eq (car (python-indent-context)) 'inside-paren))
726 (should (= (python-indent-calculate-indentation) 6))
727 (should (equal (python-indent-calculate-levels) '(0 4 6)))))
729 (ert-deftest python-indent-electric-colon-1 ()
730 "Test indentation case from Bug#18228."
731 (python-tests-with-temp-buffer
733 def a():
734 pass
736 def b()
738 (python-tests-look-at "def b()")
739 (goto-char (line-end-position))
740 (python-tests-self-insert ":")
741 (should (= (current-indentation) 0))))
743 (ert-deftest python-indent-region-1 ()
744 "Test indentation case from Bug#18843."
745 (let ((contents "
746 def foo ():
747 try:
748 pass
749 except:
750 pass
752 (python-tests-with-temp-buffer
753 contents
754 (python-indent-region (point-min) (point-max))
755 (should (string= (buffer-substring-no-properties (point-min) (point-max))
756 contents)))))
758 (ert-deftest python-indent-region-2 ()
759 "Test region indentation on comments."
760 (let ((contents "
761 def f():
762 if True:
763 pass
765 # This is
766 # some multiline
767 # comment
769 (python-tests-with-temp-buffer
770 contents
771 (python-indent-region (point-min) (point-max))
772 (should (string= (buffer-substring-no-properties (point-min) (point-max))
773 contents)))))
775 (ert-deftest python-indent-region-3 ()
776 "Test region indentation on comments."
777 (let ((contents "
778 def f():
779 if True:
780 pass
781 # This is
782 # some multiline
783 # comment
785 (expected "
786 def f():
787 if True:
788 pass
789 # This is
790 # some multiline
791 # comment
793 (python-tests-with-temp-buffer
794 contents
795 (python-indent-region (point-min) (point-max))
796 (should (string= (buffer-substring-no-properties (point-min) (point-max))
797 expected)))))
799 (ert-deftest python-indent-region-4 ()
800 "Test region indentation block starts, dedenders and enders."
801 (let ((contents "
802 def f():
803 if True:
804 a = 5
805 else:
806 a = 10
807 return a
809 (expected "
810 def f():
811 if True:
812 a = 5
813 else:
814 a = 10
815 return a
817 (python-tests-with-temp-buffer
818 contents
819 (python-indent-region (point-min) (point-max))
820 (should (string= (buffer-substring-no-properties (point-min) (point-max))
821 expected)))))
823 (ert-deftest python-indent-region-5 ()
824 "Test region indentation leaves strings untouched (start delimiter)."
825 (let ((contents "
826 def f():
828 this is
829 a multiline
830 string
833 (expected "
834 def f():
836 this is
837 a multiline
838 string
841 (python-tests-with-temp-buffer
842 contents
843 (python-indent-region (point-min) (point-max))
844 (should (string= (buffer-substring-no-properties (point-min) (point-max))
845 expected)))))
848 ;;; Navigation
850 (ert-deftest python-nav-beginning-of-defun-1 ()
851 (python-tests-with-temp-buffer
853 def decoratorFunctionWithArguments(arg1, arg2, arg3):
854 '''print decorated function call data to stdout.
856 Usage:
858 @decoratorFunctionWithArguments('arg1', 'arg2')
859 def func(a, b, c=True):
860 pass
863 def wwrap(f):
864 print 'Inside wwrap()'
865 def wrapped_f(*args):
866 print 'Inside wrapped_f()'
867 print 'Decorator arguments:', arg1, arg2, arg3
868 f(*args)
869 print 'After f(*args)'
870 return wrapped_f
871 return wwrap
873 (python-tests-look-at "return wrap")
874 (should (= (save-excursion
875 (python-nav-beginning-of-defun)
876 (point))
877 (save-excursion
878 (python-tests-look-at "def wrapped_f(*args):" -1)
879 (beginning-of-line)
880 (point))))
881 (python-tests-look-at "def wrapped_f(*args):" -1)
882 (should (= (save-excursion
883 (python-nav-beginning-of-defun)
884 (point))
885 (save-excursion
886 (python-tests-look-at "def wwrap(f):" -1)
887 (beginning-of-line)
888 (point))))
889 (python-tests-look-at "def wwrap(f):" -1)
890 (should (= (save-excursion
891 (python-nav-beginning-of-defun)
892 (point))
893 (save-excursion
894 (python-tests-look-at "def decoratorFunctionWithArguments" -1)
895 (beginning-of-line)
896 (point))))))
898 (ert-deftest python-nav-beginning-of-defun-2 ()
899 (python-tests-with-temp-buffer
901 class C(object):
903 def m(self):
904 self.c()
906 def b():
907 pass
909 def a():
910 pass
912 def c(self):
913 pass
915 ;; Nested defuns, are handled with care.
916 (python-tests-look-at "def c(self):")
917 (should (= (save-excursion
918 (python-nav-beginning-of-defun)
919 (point))
920 (save-excursion
921 (python-tests-look-at "def m(self):" -1)
922 (beginning-of-line)
923 (point))))
924 ;; Defuns on same levels should be respected.
925 (python-tests-look-at "def a():" -1)
926 (should (= (save-excursion
927 (python-nav-beginning-of-defun)
928 (point))
929 (save-excursion
930 (python-tests-look-at "def b():" -1)
931 (beginning-of-line)
932 (point))))
933 ;; Jump to a top level defun.
934 (python-tests-look-at "def b():" -1)
935 (should (= (save-excursion
936 (python-nav-beginning-of-defun)
937 (point))
938 (save-excursion
939 (python-tests-look-at "def m(self):" -1)
940 (beginning-of-line)
941 (point))))
942 ;; Jump to a top level defun again.
943 (python-tests-look-at "def m(self):" -1)
944 (should (= (save-excursion
945 (python-nav-beginning-of-defun)
946 (point))
947 (save-excursion
948 (python-tests-look-at "class C(object):" -1)
949 (beginning-of-line)
950 (point))))))
952 (ert-deftest python-nav-end-of-defun-1 ()
953 (python-tests-with-temp-buffer
955 class C(object):
957 def m(self):
958 self.c()
960 def b():
961 pass
963 def a():
964 pass
966 def c(self):
967 pass
969 (should (= (save-excursion
970 (python-tests-look-at "class C(object):")
971 (python-nav-end-of-defun)
972 (point))
973 (save-excursion
974 (point-max))))
975 (should (= (save-excursion
976 (python-tests-look-at "def m(self):")
977 (python-nav-end-of-defun)
978 (point))
979 (save-excursion
980 (python-tests-look-at "def c(self):")
981 (forward-line -1)
982 (point))))
983 (should (= (save-excursion
984 (python-tests-look-at "def b():")
985 (python-nav-end-of-defun)
986 (point))
987 (save-excursion
988 (python-tests-look-at "def b():")
989 (forward-line 2)
990 (point))))
991 (should (= (save-excursion
992 (python-tests-look-at "def c(self):")
993 (python-nav-end-of-defun)
994 (point))
995 (save-excursion
996 (point-max))))))
998 (ert-deftest python-nav-end-of-defun-2 ()
999 (python-tests-with-temp-buffer
1001 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1002 '''print decorated function call data to stdout.
1004 Usage:
1006 @decoratorFunctionWithArguments('arg1', 'arg2')
1007 def func(a, b, c=True):
1008 pass
1011 def wwrap(f):
1012 print 'Inside wwrap()'
1013 def wrapped_f(*args):
1014 print 'Inside wrapped_f()'
1015 print 'Decorator arguments:', arg1, arg2, arg3
1016 f(*args)
1017 print 'After f(*args)'
1018 return wrapped_f
1019 return wwrap
1021 (should (= (save-excursion
1022 (python-tests-look-at "def decoratorFunctionWithArguments")
1023 (python-nav-end-of-defun)
1024 (point))
1025 (save-excursion
1026 (point-max))))
1027 (should (= (save-excursion
1028 (python-tests-look-at "@decoratorFunctionWithArguments")
1029 (python-nav-end-of-defun)
1030 (point))
1031 (save-excursion
1032 (point-max))))
1033 (should (= (save-excursion
1034 (python-tests-look-at "def wwrap(f):")
1035 (python-nav-end-of-defun)
1036 (point))
1037 (save-excursion
1038 (python-tests-look-at "return wwrap")
1039 (line-beginning-position))))
1040 (should (= (save-excursion
1041 (python-tests-look-at "def wrapped_f(*args):")
1042 (python-nav-end-of-defun)
1043 (point))
1044 (save-excursion
1045 (python-tests-look-at "return wrapped_f")
1046 (line-beginning-position))))
1047 (should (= (save-excursion
1048 (python-tests-look-at "f(*args)")
1049 (python-nav-end-of-defun)
1050 (point))
1051 (save-excursion
1052 (python-tests-look-at "return wrapped_f")
1053 (line-beginning-position))))))
1055 (ert-deftest python-nav-backward-defun-1 ()
1056 (python-tests-with-temp-buffer
1058 class A(object): # A
1060 def a(self): # a
1061 pass
1063 def b(self): # b
1064 pass
1066 class B(object): # B
1068 class C(object): # C
1070 def d(self): # d
1071 pass
1073 # def e(self): # e
1074 # pass
1076 def c(self): # c
1077 pass
1079 # def d(self): # d
1080 # pass
1082 (goto-char (point-max))
1083 (should (= (save-excursion (python-nav-backward-defun))
1084 (python-tests-look-at " def c(self): # c" -1)))
1085 (should (= (save-excursion (python-nav-backward-defun))
1086 (python-tests-look-at " def d(self): # d" -1)))
1087 (should (= (save-excursion (python-nav-backward-defun))
1088 (python-tests-look-at " class C(object): # C" -1)))
1089 (should (= (save-excursion (python-nav-backward-defun))
1090 (python-tests-look-at " class B(object): # B" -1)))
1091 (should (= (save-excursion (python-nav-backward-defun))
1092 (python-tests-look-at " def b(self): # b" -1)))
1093 (should (= (save-excursion (python-nav-backward-defun))
1094 (python-tests-look-at " def a(self): # a" -1)))
1095 (should (= (save-excursion (python-nav-backward-defun))
1096 (python-tests-look-at "class A(object): # A" -1)))
1097 (should (not (python-nav-backward-defun)))))
1099 (ert-deftest python-nav-backward-defun-2 ()
1100 (python-tests-with-temp-buffer
1102 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1103 '''print decorated function call data to stdout.
1105 Usage:
1107 @decoratorFunctionWithArguments('arg1', 'arg2')
1108 def func(a, b, c=True):
1109 pass
1112 def wwrap(f):
1113 print 'Inside wwrap()'
1114 def wrapped_f(*args):
1115 print 'Inside wrapped_f()'
1116 print 'Decorator arguments:', arg1, arg2, arg3
1117 f(*args)
1118 print 'After f(*args)'
1119 return wrapped_f
1120 return wwrap
1122 (goto-char (point-max))
1123 (should (= (save-excursion (python-nav-backward-defun))
1124 (python-tests-look-at " def wrapped_f(*args):" -1)))
1125 (should (= (save-excursion (python-nav-backward-defun))
1126 (python-tests-look-at " def wwrap(f):" -1)))
1127 (should (= (save-excursion (python-nav-backward-defun))
1128 (python-tests-look-at "def decoratorFunctionWithArguments(arg1, arg2, arg3):" -1)))
1129 (should (not (python-nav-backward-defun)))))
1131 (ert-deftest python-nav-backward-defun-3 ()
1132 (python-tests-with-temp-buffer
1135 def u(self):
1136 pass
1138 def v(self):
1139 pass
1141 def w(self):
1142 pass
1145 class A(object):
1146 pass
1148 (goto-char (point-min))
1149 (let ((point (python-tests-look-at "class A(object):")))
1150 (should (not (python-nav-backward-defun)))
1151 (should (= point (point))))))
1153 (ert-deftest python-nav-forward-defun-1 ()
1154 (python-tests-with-temp-buffer
1156 class A(object): # A
1158 def a(self): # a
1159 pass
1161 def b(self): # b
1162 pass
1164 class B(object): # B
1166 class C(object): # C
1168 def d(self): # d
1169 pass
1171 # def e(self): # e
1172 # pass
1174 def c(self): # c
1175 pass
1177 # def d(self): # d
1178 # pass
1180 (goto-char (point-min))
1181 (should (= (save-excursion (python-nav-forward-defun))
1182 (python-tests-look-at "(object): # A")))
1183 (should (= (save-excursion (python-nav-forward-defun))
1184 (python-tests-look-at "(self): # a")))
1185 (should (= (save-excursion (python-nav-forward-defun))
1186 (python-tests-look-at "(self): # b")))
1187 (should (= (save-excursion (python-nav-forward-defun))
1188 (python-tests-look-at "(object): # B")))
1189 (should (= (save-excursion (python-nav-forward-defun))
1190 (python-tests-look-at "(object): # C")))
1191 (should (= (save-excursion (python-nav-forward-defun))
1192 (python-tests-look-at "(self): # d")))
1193 (should (= (save-excursion (python-nav-forward-defun))
1194 (python-tests-look-at "(self): # c")))
1195 (should (not (python-nav-forward-defun)))))
1197 (ert-deftest python-nav-forward-defun-2 ()
1198 (python-tests-with-temp-buffer
1200 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1201 '''print decorated function call data to stdout.
1203 Usage:
1205 @decoratorFunctionWithArguments('arg1', 'arg2')
1206 def func(a, b, c=True):
1207 pass
1210 def wwrap(f):
1211 print 'Inside wwrap()'
1212 def wrapped_f(*args):
1213 print 'Inside wrapped_f()'
1214 print 'Decorator arguments:', arg1, arg2, arg3
1215 f(*args)
1216 print 'After f(*args)'
1217 return wrapped_f
1218 return wwrap
1220 (goto-char (point-min))
1221 (should (= (save-excursion (python-nav-forward-defun))
1222 (python-tests-look-at "(arg1, arg2, arg3):")))
1223 (should (= (save-excursion (python-nav-forward-defun))
1224 (python-tests-look-at "(f):")))
1225 (should (= (save-excursion (python-nav-forward-defun))
1226 (python-tests-look-at "(*args):")))
1227 (should (not (python-nav-forward-defun)))))
1229 (ert-deftest python-nav-forward-defun-3 ()
1230 (python-tests-with-temp-buffer
1232 class A(object):
1233 pass
1236 def u(self):
1237 pass
1239 def v(self):
1240 pass
1242 def w(self):
1243 pass
1246 (goto-char (point-min))
1247 (let ((point (python-tests-look-at "(object):")))
1248 (should (not (python-nav-forward-defun)))
1249 (should (= point (point))))))
1251 (ert-deftest python-nav-beginning-of-statement-1 ()
1252 (python-tests-with-temp-buffer
1254 v1 = 123 + \
1255 456 + \
1257 v2 = (value1,
1258 value2,
1260 value3,
1261 value4)
1262 v3 = ('this is a string'
1264 'that is continued'
1265 'between lines'
1266 'within a paren',
1267 # this is a comment, yo
1268 'continue previous line')
1269 v4 = '''
1270 a very long
1271 string
1274 (python-tests-look-at "v2 =")
1275 (python-util-forward-comment -1)
1276 (should (= (save-excursion
1277 (python-nav-beginning-of-statement)
1278 (point))
1279 (python-tests-look-at "v1 =" -1 t)))
1280 (python-tests-look-at "v3 =")
1281 (python-util-forward-comment -1)
1282 (should (= (save-excursion
1283 (python-nav-beginning-of-statement)
1284 (point))
1285 (python-tests-look-at "v2 =" -1 t)))
1286 (python-tests-look-at "v4 =")
1287 (python-util-forward-comment -1)
1288 (should (= (save-excursion
1289 (python-nav-beginning-of-statement)
1290 (point))
1291 (python-tests-look-at "v3 =" -1 t)))
1292 (goto-char (point-max))
1293 (python-util-forward-comment -1)
1294 (should (= (save-excursion
1295 (python-nav-beginning-of-statement)
1296 (point))
1297 (python-tests-look-at "v4 =" -1 t)))))
1299 (ert-deftest python-nav-end-of-statement-1 ()
1300 (python-tests-with-temp-buffer
1302 v1 = 123 + \
1303 456 + \
1305 v2 = (value1,
1306 value2,
1308 value3,
1309 value4)
1310 v3 = ('this is a string'
1312 'that is continued'
1313 'between lines'
1314 'within a paren',
1315 # this is a comment, yo
1316 'continue previous line')
1317 v4 = '''
1318 a very long
1319 string
1322 (python-tests-look-at "v1 =")
1323 (should (= (save-excursion
1324 (python-nav-end-of-statement)
1325 (point))
1326 (save-excursion
1327 (python-tests-look-at "789")
1328 (line-end-position))))
1329 (python-tests-look-at "v2 =")
1330 (should (= (save-excursion
1331 (python-nav-end-of-statement)
1332 (point))
1333 (save-excursion
1334 (python-tests-look-at "value4)")
1335 (line-end-position))))
1336 (python-tests-look-at "v3 =")
1337 (should (= (save-excursion
1338 (python-nav-end-of-statement)
1339 (point))
1340 (save-excursion
1341 (python-tests-look-at
1342 "'continue previous line')")
1343 (line-end-position))))
1344 (python-tests-look-at "v4 =")
1345 (should (= (save-excursion
1346 (python-nav-end-of-statement)
1347 (point))
1348 (save-excursion
1349 (goto-char (point-max))
1350 (python-util-forward-comment -1)
1351 (point))))))
1353 (ert-deftest python-nav-forward-statement-1 ()
1354 (python-tests-with-temp-buffer
1356 v1 = 123 + \
1357 456 + \
1359 v2 = (value1,
1360 value2,
1362 value3,
1363 value4)
1364 v3 = ('this is a string'
1366 'that is continued'
1367 'between lines'
1368 'within a paren',
1369 # this is a comment, yo
1370 'continue previous line')
1371 v4 = '''
1372 a very long
1373 string
1376 (python-tests-look-at "v1 =")
1377 (should (= (save-excursion
1378 (python-nav-forward-statement)
1379 (point))
1380 (python-tests-look-at "v2 =")))
1381 (should (= (save-excursion
1382 (python-nav-forward-statement)
1383 (point))
1384 (python-tests-look-at "v3 =")))
1385 (should (= (save-excursion
1386 (python-nav-forward-statement)
1387 (point))
1388 (python-tests-look-at "v4 =")))
1389 (should (= (save-excursion
1390 (python-nav-forward-statement)
1391 (point))
1392 (point-max)))))
1394 (ert-deftest python-nav-backward-statement-1 ()
1395 (python-tests-with-temp-buffer
1397 v1 = 123 + \
1398 456 + \
1400 v2 = (value1,
1401 value2,
1403 value3,
1404 value4)
1405 v3 = ('this is a string'
1407 'that is continued'
1408 'between lines'
1409 'within a paren',
1410 # this is a comment, yo
1411 'continue previous line')
1412 v4 = '''
1413 a very long
1414 string
1417 (goto-char (point-max))
1418 (should (= (save-excursion
1419 (python-nav-backward-statement)
1420 (point))
1421 (python-tests-look-at "v4 =" -1)))
1422 (should (= (save-excursion
1423 (python-nav-backward-statement)
1424 (point))
1425 (python-tests-look-at "v3 =" -1)))
1426 (should (= (save-excursion
1427 (python-nav-backward-statement)
1428 (point))
1429 (python-tests-look-at "v2 =" -1)))
1430 (should (= (save-excursion
1431 (python-nav-backward-statement)
1432 (point))
1433 (python-tests-look-at "v1 =" -1)))))
1435 (ert-deftest python-nav-backward-statement-2 ()
1436 :expected-result :failed
1437 (python-tests-with-temp-buffer
1439 v1 = 123 + \
1440 456 + \
1442 v2 = (value1,
1443 value2,
1445 value3,
1446 value4)
1448 ;; FIXME: For some reason `python-nav-backward-statement' is moving
1449 ;; back two sentences when starting from 'value4)'.
1450 (goto-char (point-max))
1451 (python-util-forward-comment -1)
1452 (should (= (save-excursion
1453 (python-nav-backward-statement)
1454 (point))
1455 (python-tests-look-at "v2 =" -1 t)))))
1457 (ert-deftest python-nav-beginning-of-block-1 ()
1458 (python-tests-with-temp-buffer
1460 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1461 '''print decorated function call data to stdout.
1463 Usage:
1465 @decoratorFunctionWithArguments('arg1', 'arg2')
1466 def func(a, b, c=True):
1467 pass
1470 def wwrap(f):
1471 print 'Inside wwrap()'
1472 def wrapped_f(*args):
1473 print 'Inside wrapped_f()'
1474 print 'Decorator arguments:', arg1, arg2, arg3
1475 f(*args)
1476 print 'After f(*args)'
1477 return wrapped_f
1478 return wwrap
1480 (python-tests-look-at "return wwrap")
1481 (should (= (save-excursion
1482 (python-nav-beginning-of-block)
1483 (point))
1484 (python-tests-look-at "def decoratorFunctionWithArguments" -1)))
1485 (python-tests-look-at "print 'Inside wwrap()'")
1486 (should (= (save-excursion
1487 (python-nav-beginning-of-block)
1488 (point))
1489 (python-tests-look-at "def wwrap(f):" -1)))
1490 (python-tests-look-at "print 'After f(*args)'")
1491 (end-of-line)
1492 (should (= (save-excursion
1493 (python-nav-beginning-of-block)
1494 (point))
1495 (python-tests-look-at "def wrapped_f(*args):" -1)))
1496 (python-tests-look-at "return wrapped_f")
1497 (should (= (save-excursion
1498 (python-nav-beginning-of-block)
1499 (point))
1500 (python-tests-look-at "def wwrap(f):" -1)))))
1502 (ert-deftest python-nav-end-of-block-1 ()
1503 (python-tests-with-temp-buffer
1505 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1506 '''print decorated function call data to stdout.
1508 Usage:
1510 @decoratorFunctionWithArguments('arg1', 'arg2')
1511 def func(a, b, c=True):
1512 pass
1515 def wwrap(f):
1516 print 'Inside wwrap()'
1517 def wrapped_f(*args):
1518 print 'Inside wrapped_f()'
1519 print 'Decorator arguments:', arg1, arg2, arg3
1520 f(*args)
1521 print 'After f(*args)'
1522 return wrapped_f
1523 return wwrap
1525 (python-tests-look-at "def decoratorFunctionWithArguments")
1526 (should (= (save-excursion
1527 (python-nav-end-of-block)
1528 (point))
1529 (save-excursion
1530 (goto-char (point-max))
1531 (python-util-forward-comment -1)
1532 (point))))
1533 (python-tests-look-at "def wwrap(f):")
1534 (should (= (save-excursion
1535 (python-nav-end-of-block)
1536 (point))
1537 (save-excursion
1538 (python-tests-look-at "return wrapped_f")
1539 (line-end-position))))
1540 (end-of-line)
1541 (should (= (save-excursion
1542 (python-nav-end-of-block)
1543 (point))
1544 (save-excursion
1545 (python-tests-look-at "return wrapped_f")
1546 (line-end-position))))
1547 (python-tests-look-at "f(*args)")
1548 (should (= (save-excursion
1549 (python-nav-end-of-block)
1550 (point))
1551 (save-excursion
1552 (python-tests-look-at "print 'After f(*args)'")
1553 (line-end-position))))))
1555 (ert-deftest python-nav-forward-block-1 ()
1556 "This also accounts as a test for `python-nav-backward-block'."
1557 (python-tests-with-temp-buffer
1559 if request.user.is_authenticated():
1560 # def block():
1561 # pass
1562 try:
1563 profile = request.user.get_profile()
1564 except Profile.DoesNotExist:
1565 profile = Profile.objects.create(user=request.user)
1566 else:
1567 if profile.stats:
1568 profile.recalculate_stats()
1569 else:
1570 profile.clear_stats()
1571 finally:
1572 profile.views += 1
1573 profile.save()
1575 (should (= (save-excursion (python-nav-forward-block))
1576 (python-tests-look-at "if request.user.is_authenticated():")))
1577 (should (= (save-excursion (python-nav-forward-block))
1578 (python-tests-look-at "try:")))
1579 (should (= (save-excursion (python-nav-forward-block))
1580 (python-tests-look-at "except Profile.DoesNotExist:")))
1581 (should (= (save-excursion (python-nav-forward-block))
1582 (python-tests-look-at "else:")))
1583 (should (= (save-excursion (python-nav-forward-block))
1584 (python-tests-look-at "if profile.stats:")))
1585 (should (= (save-excursion (python-nav-forward-block))
1586 (python-tests-look-at "else:")))
1587 (should (= (save-excursion (python-nav-forward-block))
1588 (python-tests-look-at "finally:")))
1589 ;; When point is at the last block, leave it there and return nil
1590 (should (not (save-excursion (python-nav-forward-block))))
1591 ;; Move backwards, and even if the number of moves is less than the
1592 ;; provided argument return the point.
1593 (should (= (save-excursion (python-nav-forward-block -10))
1594 (python-tests-look-at
1595 "if request.user.is_authenticated():" -1)))))
1597 (ert-deftest python-nav-forward-sexp-1 ()
1598 (python-tests-with-temp-buffer
1604 (python-tests-look-at "a()")
1605 (python-nav-forward-sexp)
1606 (should (looking-at "$"))
1607 (should (save-excursion
1608 (beginning-of-line)
1609 (looking-at "a()")))
1610 (python-nav-forward-sexp)
1611 (should (looking-at "$"))
1612 (should (save-excursion
1613 (beginning-of-line)
1614 (looking-at "b()")))
1615 (python-nav-forward-sexp)
1616 (should (looking-at "$"))
1617 (should (save-excursion
1618 (beginning-of-line)
1619 (looking-at "c()")))
1620 ;; Movement next to a paren should do what lisp does and
1621 ;; unfortunately It can't change, because otherwise
1622 ;; `blink-matching-open' breaks.
1623 (python-nav-forward-sexp -1)
1624 (should (looking-at "()"))
1625 (should (save-excursion
1626 (beginning-of-line)
1627 (looking-at "c()")))
1628 (python-nav-forward-sexp -1)
1629 (should (looking-at "c()"))
1630 (python-nav-forward-sexp -1)
1631 (should (looking-at "b()"))
1632 (python-nav-forward-sexp -1)
1633 (should (looking-at "a()"))))
1635 (ert-deftest python-nav-forward-sexp-2 ()
1636 (python-tests-with-temp-buffer
1638 def func():
1639 if True:
1640 aaa = bbb
1641 ccc = ddd
1642 eee = fff
1643 return ggg
1645 (python-tests-look-at "aa =")
1646 (python-nav-forward-sexp)
1647 (should (looking-at " = bbb"))
1648 (python-nav-forward-sexp)
1649 (should (looking-at "$"))
1650 (should (save-excursion
1651 (back-to-indentation)
1652 (looking-at "aaa = bbb")))
1653 (python-nav-forward-sexp)
1654 (should (looking-at "$"))
1655 (should (save-excursion
1656 (back-to-indentation)
1657 (looking-at "ccc = ddd")))
1658 (python-nav-forward-sexp)
1659 (should (looking-at "$"))
1660 (should (save-excursion
1661 (back-to-indentation)
1662 (looking-at "eee = fff")))
1663 (python-nav-forward-sexp)
1664 (should (looking-at "$"))
1665 (should (save-excursion
1666 (back-to-indentation)
1667 (looking-at "return ggg")))
1668 (python-nav-forward-sexp -1)
1669 (should (looking-at "def func():"))))
1671 (ert-deftest python-nav-forward-sexp-3 ()
1672 (python-tests-with-temp-buffer
1674 from some_module import some_sub_module
1675 from another_module import another_sub_module
1677 def another_statement():
1678 pass
1680 (python-tests-look-at "some_module")
1681 (python-nav-forward-sexp)
1682 (should (looking-at " import"))
1683 (python-nav-forward-sexp)
1684 (should (looking-at " some_sub_module"))
1685 (python-nav-forward-sexp)
1686 (should (looking-at "$"))
1687 (should
1688 (save-excursion
1689 (back-to-indentation)
1690 (looking-at
1691 "from some_module import some_sub_module")))
1692 (python-nav-forward-sexp)
1693 (should (looking-at "$"))
1694 (should
1695 (save-excursion
1696 (back-to-indentation)
1697 (looking-at
1698 "from another_module import another_sub_module")))
1699 (python-nav-forward-sexp)
1700 (should (looking-at "$"))
1701 (should
1702 (save-excursion
1703 (back-to-indentation)
1704 (looking-at
1705 "pass")))
1706 (python-nav-forward-sexp -1)
1707 (should (looking-at "def another_statement():"))
1708 (python-nav-forward-sexp -1)
1709 (should (looking-at "from another_module import another_sub_module"))
1710 (python-nav-forward-sexp -1)
1711 (should (looking-at "from some_module import some_sub_module"))))
1713 (ert-deftest python-nav-forward-sexp-safe-1 ()
1714 (python-tests-with-temp-buffer
1716 profile = Profile.objects.create(user=request.user)
1717 profile.notify()
1719 (python-tests-look-at "profile =")
1720 (python-nav-forward-sexp-safe 1)
1721 (should (looking-at "$"))
1722 (beginning-of-line 1)
1723 (python-tests-look-at "user=request.user")
1724 (python-nav-forward-sexp-safe -1)
1725 (should (looking-at "(user=request.user)"))
1726 (python-nav-forward-sexp-safe -4)
1727 (should (looking-at "profile ="))
1728 (python-tests-look-at "user=request.user")
1729 (python-nav-forward-sexp-safe 3)
1730 (should (looking-at ")"))
1731 (python-nav-forward-sexp-safe 1)
1732 (should (looking-at "$"))
1733 (python-nav-forward-sexp-safe 1)
1734 (should (looking-at "$"))))
1736 (ert-deftest python-nav-up-list-1 ()
1737 (python-tests-with-temp-buffer
1739 def f():
1740 if True:
1741 return [i for i in range(3)]
1743 (python-tests-look-at "3)]")
1744 (python-nav-up-list)
1745 (should (looking-at "]"))
1746 (python-nav-up-list)
1747 (should (looking-at "$"))))
1749 (ert-deftest python-nav-backward-up-list-1 ()
1750 :expected-result :failed
1751 (python-tests-with-temp-buffer
1753 def f():
1754 if True:
1755 return [i for i in range(3)]
1757 (python-tests-look-at "3)]")
1758 (python-nav-backward-up-list)
1759 (should (looking-at "(3)\\]"))
1760 (python-nav-backward-up-list)
1761 (should (looking-at
1762 "\\[i for i in range(3)\\]"))
1763 ;; FIXME: Need to move to beginning-of-statement.
1764 (python-nav-backward-up-list)
1765 (should (looking-at
1766 "return \\[i for i in range(3)\\]"))
1767 (python-nav-backward-up-list)
1768 (should (looking-at "if True:"))
1769 (python-nav-backward-up-list)
1770 (should (looking-at "def f():"))))
1773 ;;; Shell integration
1775 (defvar python-tests-shell-interpreter "python")
1777 (ert-deftest python-shell-get-process-name-1 ()
1778 "Check process name calculation on different scenarios."
1779 (python-tests-with-temp-buffer
1781 (should (string= (python-shell-get-process-name nil)
1782 python-shell-buffer-name))
1783 ;; When the `current-buffer' doesn't have `buffer-file-name', even
1784 ;; if dedicated flag is non-nil should not include its name.
1785 (should (string= (python-shell-get-process-name t)
1786 python-shell-buffer-name)))
1787 (python-tests-with-temp-file
1789 ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
1790 ;; should be respected.
1791 (should (string= (python-shell-get-process-name nil)
1792 python-shell-buffer-name))
1793 (should (string=
1794 (python-shell-get-process-name t)
1795 (format "%s[%s]" python-shell-buffer-name buffer-file-name)))))
1797 (ert-deftest python-shell-internal-get-process-name-1 ()
1798 "Check the internal process name is config-unique."
1799 (let* ((python-shell-interpreter python-tests-shell-interpreter)
1800 (python-shell-interpreter-args "")
1801 (python-shell-prompt-regexp ">>> ")
1802 (python-shell-prompt-block-regexp "[.][.][.] ")
1803 (python-shell-setup-codes "")
1804 (python-shell-process-environment "")
1805 (python-shell-extra-pythonpaths "")
1806 (python-shell-exec-path "")
1807 (python-shell-virtualenv-path "")
1808 (expected (python-tests-with-temp-buffer
1809 "" (python-shell-internal-get-process-name))))
1810 ;; Same configurations should match.
1811 (should
1812 (string= expected
1813 (python-tests-with-temp-buffer
1814 "" (python-shell-internal-get-process-name))))
1815 (let ((python-shell-interpreter-args "-B"))
1816 ;; A minimal change should generate different names.
1817 (should
1818 (not (string=
1819 expected
1820 (python-tests-with-temp-buffer
1821 "" (python-shell-internal-get-process-name))))))))
1823 (ert-deftest python-shell-parse-command-1 ()
1824 "Check the command to execute is calculated correctly.
1825 Using `python-shell-interpreter' and
1826 `python-shell-interpreter-args'."
1827 (skip-unless (executable-find python-tests-shell-interpreter))
1828 (let ((python-shell-interpreter (executable-find
1829 python-tests-shell-interpreter))
1830 (python-shell-interpreter-args "-B"))
1831 (should (string=
1832 (format "%s %s"
1833 python-shell-interpreter
1834 python-shell-interpreter-args)
1835 (python-shell-parse-command)))))
1837 (ert-deftest python-shell-calculate-process-environment-1 ()
1838 "Test `python-shell-process-environment' modification."
1839 (let* ((original-process-environment process-environment)
1840 (python-shell-process-environment
1841 '("TESTVAR1=value1" "TESTVAR2=value2"))
1842 (process-environment
1843 (python-shell-calculate-process-environment)))
1844 (should (equal (getenv "TESTVAR1") "value1"))
1845 (should (equal (getenv "TESTVAR2") "value2"))))
1847 (ert-deftest python-shell-calculate-process-environment-2 ()
1848 "Test `python-shell-extra-pythonpaths' modification."
1849 (let* ((original-process-environment process-environment)
1850 (original-pythonpath (getenv "PYTHONPATH"))
1851 (paths '("path1" "path2"))
1852 (python-shell-extra-pythonpaths paths)
1853 (process-environment
1854 (python-shell-calculate-process-environment)))
1855 (should (equal (getenv "PYTHONPATH")
1856 (concat
1857 (mapconcat 'identity paths path-separator)
1858 path-separator original-pythonpath)))))
1860 (ert-deftest python-shell-calculate-process-environment-3 ()
1861 "Test `python-shell-virtualenv-path' modification."
1862 (let* ((original-process-environment process-environment)
1863 (original-path (or (getenv "PATH") ""))
1864 (python-shell-virtualenv-path
1865 (directory-file-name user-emacs-directory))
1866 (process-environment
1867 (python-shell-calculate-process-environment)))
1868 (should (not (getenv "PYTHONHOME")))
1869 (should (string= (getenv "VIRTUAL_ENV") python-shell-virtualenv-path))
1870 (should (equal (getenv "PATH")
1871 (format "%s/bin%s%s"
1872 python-shell-virtualenv-path
1873 path-separator original-path)))))
1875 (ert-deftest python-shell-calculate-process-environment-4 ()
1876 "Test `python-shell-unbuffered' modification."
1877 (setenv "PYTHONUNBUFFERED")
1878 (let* ((process-environment
1879 (python-shell-calculate-process-environment)))
1880 ;; Defaults to t
1881 (should python-shell-unbuffered)
1882 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
1884 (ert-deftest python-shell-calculate-process-environment-5 ()
1885 (setenv "PYTHONUNBUFFERED")
1886 "Test `python-shell-unbuffered' modification."
1887 (let* ((python-shell-unbuffered nil)
1888 (process-environment
1889 (python-shell-calculate-process-environment)))
1890 (should (not (getenv "PYTHONUNBUFFERED")))))
1892 (ert-deftest python-shell-calculate-exec-path-1 ()
1893 "Test `python-shell-exec-path' modification."
1894 (let* ((original-exec-path exec-path)
1895 (python-shell-exec-path '("path1" "path2"))
1896 (exec-path (python-shell-calculate-exec-path)))
1897 (should (equal
1898 exec-path
1899 (append python-shell-exec-path
1900 original-exec-path)))))
1902 (ert-deftest python-shell-calculate-exec-path-2 ()
1903 "Test `python-shell-exec-path' modification."
1904 (let* ((original-exec-path exec-path)
1905 (python-shell-virtualenv-path
1906 (directory-file-name (expand-file-name user-emacs-directory)))
1907 (exec-path (python-shell-calculate-exec-path)))
1908 (should (equal
1909 exec-path
1910 (append (cons
1911 (format "%s/bin" python-shell-virtualenv-path)
1912 original-exec-path))))))
1914 (ert-deftest python-shell-make-comint-1 ()
1915 "Check comint creation for global shell buffer."
1916 (skip-unless (executable-find python-tests-shell-interpreter))
1917 ;; The interpreter can get killed too quickly to allow it to clean
1918 ;; up the tempfiles that the default python-shell-setup-codes create,
1919 ;; so it leaves tempfiles behind, which is a minor irritation.
1920 (let* ((python-shell-setup-codes nil)
1921 (python-shell-interpreter
1922 (executable-find python-tests-shell-interpreter))
1923 (proc-name (python-shell-get-process-name nil))
1924 (shell-buffer
1925 (python-tests-with-temp-buffer
1926 "" (python-shell-make-comint
1927 (python-shell-parse-command) proc-name)))
1928 (process (get-buffer-process shell-buffer)))
1929 (unwind-protect
1930 (progn
1931 (set-process-query-on-exit-flag process nil)
1932 (should (process-live-p process))
1933 (with-current-buffer shell-buffer
1934 (should (eq major-mode 'inferior-python-mode))
1935 (should (string= (buffer-name) (format "*%s*" proc-name)))))
1936 (kill-buffer shell-buffer))))
1938 (ert-deftest python-shell-make-comint-2 ()
1939 "Check comint creation for internal shell buffer."
1940 (skip-unless (executable-find python-tests-shell-interpreter))
1941 (let* ((python-shell-setup-codes nil)
1942 (python-shell-interpreter
1943 (executable-find python-tests-shell-interpreter))
1944 (proc-name (python-shell-internal-get-process-name))
1945 (shell-buffer
1946 (python-tests-with-temp-buffer
1947 "" (python-shell-make-comint
1948 (python-shell-parse-command) proc-name nil t)))
1949 (process (get-buffer-process shell-buffer)))
1950 (unwind-protect
1951 (progn
1952 (set-process-query-on-exit-flag process nil)
1953 (should (process-live-p process))
1954 (with-current-buffer shell-buffer
1955 (should (eq major-mode 'inferior-python-mode))
1956 (should (string= (buffer-name) (format " *%s*" proc-name)))))
1957 (kill-buffer shell-buffer))))
1959 (ert-deftest python-shell-make-comint-3 ()
1960 "Check comint creation with overridden python interpreter and args.
1961 The command passed to `python-shell-make-comint' as argument must
1962 locally override global values set in `python-shell-interpreter'
1963 and `python-shell-interpreter-args' in the new shell buffer."
1964 (skip-unless (executable-find python-tests-shell-interpreter))
1965 (let* ((python-shell-setup-codes nil)
1966 (python-shell-interpreter "interpreter")
1967 (python-shell-interpreter-args "--some-args")
1968 (proc-name (python-shell-get-process-name nil))
1969 (interpreter-override
1970 (concat (executable-find python-tests-shell-interpreter) " " "-i"))
1971 (shell-buffer
1972 (python-tests-with-temp-buffer
1973 "" (python-shell-make-comint interpreter-override proc-name nil)))
1974 (process (get-buffer-process shell-buffer)))
1975 (unwind-protect
1976 (progn
1977 (set-process-query-on-exit-flag process nil)
1978 (should (process-live-p process))
1979 (with-current-buffer shell-buffer
1980 (should (eq major-mode 'inferior-python-mode))
1981 (should (file-equal-p
1982 python-shell-interpreter
1983 (executable-find python-tests-shell-interpreter)))
1984 (should (string= python-shell-interpreter-args "-i"))))
1985 (kill-buffer shell-buffer))))
1987 (ert-deftest python-shell-make-comint-4 ()
1988 "Check shell calculated prompts regexps are set."
1989 (skip-unless (executable-find python-tests-shell-interpreter))
1990 (let* ((process-environment process-environment)
1991 (python-shell-setup-codes nil)
1992 (python-shell-interpreter
1993 (executable-find python-tests-shell-interpreter))
1994 (python-shell-interpreter-args "-i")
1995 (python-shell--prompt-calculated-input-regexp nil)
1996 (python-shell--prompt-calculated-output-regexp nil)
1997 (python-shell-prompt-detect-enabled t)
1998 (python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
1999 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2000 (python-shell-prompt-regexp "in")
2001 (python-shell-prompt-block-regexp "block")
2002 (python-shell-prompt-pdb-regexp "pdf")
2003 (python-shell-prompt-output-regexp "output")
2004 (startup-code (concat "import sys\n"
2005 "sys.ps1 = 'py> '\n"
2006 "sys.ps2 = '..> '\n"
2007 "sys.ps3 = 'out '\n"))
2008 (startup-file (python-shell--save-temp-file startup-code))
2009 (proc-name (python-shell-get-process-name nil))
2010 (shell-buffer
2011 (progn
2012 (setenv "PYTHONSTARTUP" startup-file)
2013 (python-tests-with-temp-buffer
2014 "" (python-shell-make-comint
2015 (python-shell-parse-command) proc-name nil))))
2016 (process (get-buffer-process shell-buffer)))
2017 (unwind-protect
2018 (progn
2019 (set-process-query-on-exit-flag process nil)
2020 (should (process-live-p process))
2021 (with-current-buffer shell-buffer
2022 (should (eq major-mode 'inferior-python-mode))
2023 (should (string=
2024 python-shell--prompt-calculated-input-regexp
2025 (concat "^\\(extralargeinputprompt\\|\\.\\.> \\|"
2026 "block\\|py> \\|pdf\\|sml\\|in\\)")))
2027 (should (string=
2028 python-shell--prompt-calculated-output-regexp
2029 "^\\(extralargeoutputprompt\\|output\\|out \\|sml\\)"))))
2030 (delete-file startup-file)
2031 (kill-buffer shell-buffer))))
2033 (ert-deftest python-shell-get-process-1 ()
2034 "Check dedicated shell process preference over global."
2035 (skip-unless (executable-find python-tests-shell-interpreter))
2036 (python-tests-with-temp-file
2038 (let* ((python-shell-setup-codes nil)
2039 (python-shell-interpreter
2040 (executable-find python-tests-shell-interpreter))
2041 (global-proc-name (python-shell-get-process-name nil))
2042 (dedicated-proc-name (python-shell-get-process-name t))
2043 (global-shell-buffer
2044 (python-shell-make-comint
2045 (python-shell-parse-command) global-proc-name))
2046 (dedicated-shell-buffer
2047 (python-shell-make-comint
2048 (python-shell-parse-command) dedicated-proc-name))
2049 (global-process (get-buffer-process global-shell-buffer))
2050 (dedicated-process (get-buffer-process dedicated-shell-buffer)))
2051 (unwind-protect
2052 (progn
2053 (set-process-query-on-exit-flag global-process nil)
2054 (set-process-query-on-exit-flag dedicated-process nil)
2055 ;; Prefer dedicated if global also exists.
2056 (should (equal (python-shell-get-process) dedicated-process))
2057 (kill-buffer dedicated-shell-buffer)
2058 ;; If there's only global, use it.
2059 (should (equal (python-shell-get-process) global-process))
2060 (kill-buffer global-shell-buffer)
2061 ;; No buffer available.
2062 (should (not (python-shell-get-process))))
2063 (ignore-errors (kill-buffer global-shell-buffer))
2064 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2066 (ert-deftest python-shell-get-or-create-process-1 ()
2067 "Check shell dedicated process creation."
2068 (skip-unless (executable-find python-tests-shell-interpreter))
2069 (python-tests-with-temp-file
2071 (let* ((cmd
2072 (concat (executable-find python-tests-shell-interpreter) " -i"))
2073 (use-dialog-box)
2074 (dedicated-process-name (python-shell-get-process-name t))
2075 (dedicated-process (python-shell-get-or-create-process cmd t))
2076 (dedicated-shell-buffer (process-buffer dedicated-process)))
2077 (unwind-protect
2078 (progn
2079 (set-process-query-on-exit-flag dedicated-process nil)
2080 ;; should be dedicated.
2081 (should (equal (process-name dedicated-process)
2082 dedicated-process-name))
2083 (kill-buffer dedicated-shell-buffer)
2084 ;; Check there are no processes for current buffer.
2085 (should (not (python-shell-get-process))))
2086 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2088 (ert-deftest python-shell-get-or-create-process-2 ()
2089 "Check shell global process creation."
2090 (skip-unless (executable-find python-tests-shell-interpreter))
2091 (python-tests-with-temp-file
2093 (let* ((cmd
2094 (concat (executable-find python-tests-shell-interpreter) " -i"))
2095 (use-dialog-box)
2096 (process-name (python-shell-get-process-name nil))
2097 (process (python-shell-get-or-create-process cmd))
2098 (shell-buffer (process-buffer process)))
2099 (unwind-protect
2100 (progn
2101 (set-process-query-on-exit-flag process nil)
2102 ;; should be global.
2103 (should (equal (process-name process) process-name))
2104 (kill-buffer shell-buffer)
2105 ;; Check there are no processes for current buffer.
2106 (should (not (python-shell-get-process))))
2107 (ignore-errors (kill-buffer shell-buffer))))))
2109 (ert-deftest python-shell-get-or-create-process-3 ()
2110 "Check shell dedicated/global process preference."
2111 (skip-unless (executable-find python-tests-shell-interpreter))
2112 (python-tests-with-temp-file
2114 (let* ((cmd
2115 (concat (executable-find python-tests-shell-interpreter) " -i"))
2116 (python-shell-interpreter python-tests-shell-interpreter)
2117 (use-dialog-box)
2118 (dedicated-process-name (python-shell-get-process-name t))
2119 (global-process)
2120 (dedicated-process))
2121 (progn
2122 ;; Create global process
2123 (run-python cmd nil)
2124 (setq global-process (get-buffer-process "*Python*"))
2125 (should global-process)
2126 (set-process-query-on-exit-flag global-process nil)
2127 ;; Create dedicated process
2128 (run-python cmd t)
2129 (setq dedicated-process (get-process dedicated-process-name))
2130 (should dedicated-process)
2131 (set-process-query-on-exit-flag dedicated-process nil)
2132 ;; Prefer dedicated.
2133 (should (equal (python-shell-get-or-create-process)
2134 dedicated-process))
2135 ;; Kill the dedicated so the global takes over.
2136 (kill-buffer (process-buffer dedicated-process))
2137 ;; Detect global.
2138 (should (equal (python-shell-get-or-create-process) global-process))
2139 ;; Kill the global.
2140 (kill-buffer (process-buffer global-process))
2141 ;; Check there are no processes for current buffer.
2142 (should (not (python-shell-get-process)))))))
2144 (ert-deftest python-shell-internal-get-or-create-process-1 ()
2145 "Check internal shell process creation fallback."
2146 (skip-unless (executable-find python-tests-shell-interpreter))
2147 (python-tests-with-temp-file
2149 (should (not (process-live-p (python-shell-internal-get-process-name))))
2150 (let* ((python-shell-interpreter
2151 (executable-find python-tests-shell-interpreter))
2152 (internal-process-name (python-shell-internal-get-process-name))
2153 (internal-process (python-shell-internal-get-or-create-process))
2154 (internal-shell-buffer (process-buffer internal-process)))
2155 (unwind-protect
2156 (progn
2157 (set-process-query-on-exit-flag internal-process nil)
2158 (should (equal (process-name internal-process)
2159 internal-process-name))
2160 (should (equal internal-process
2161 (python-shell-internal-get-or-create-process)))
2162 ;; Assert the internal process is not a user process
2163 (should (not (python-shell-get-process)))
2164 (kill-buffer internal-shell-buffer))
2165 (ignore-errors (kill-buffer internal-shell-buffer))))))
2167 (ert-deftest python-shell-prompt-detect-1 ()
2168 "Check prompt autodetection."
2169 (skip-unless (executable-find python-tests-shell-interpreter))
2170 (let ((process-environment process-environment))
2171 ;; Ensure no startup file is enabled
2172 (setenv "PYTHONSTARTUP" "")
2173 (should python-shell-prompt-detect-enabled)
2174 (should (equal (python-shell-prompt-detect) '(">>> " "... " "")))))
2176 (ert-deftest python-shell-prompt-detect-2 ()
2177 "Check prompt autodetection with startup file. Bug#17370."
2178 (skip-unless (executable-find python-tests-shell-interpreter))
2179 (let* ((process-environment process-environment)
2180 (startup-code (concat "import sys\n"
2181 "sys.ps1 = 'py> '\n"
2182 "sys.ps2 = '..> '\n"
2183 "sys.ps3 = 'out '\n"))
2184 (startup-file (python-shell--save-temp-file startup-code)))
2185 (unwind-protect
2186 (progn
2187 ;; Ensure startup file is enabled
2188 (setenv "PYTHONSTARTUP" startup-file)
2189 (should python-shell-prompt-detect-enabled)
2190 (should (equal (python-shell-prompt-detect) '("py> " "..> " "out "))))
2191 (ignore-errors (delete-file startup-file)))))
2193 (ert-deftest python-shell-prompt-detect-3 ()
2194 "Check prompts are not autodetected when feature is disabled."
2195 (skip-unless (executable-find python-tests-shell-interpreter))
2196 (let ((process-environment process-environment)
2197 (python-shell-prompt-detect-enabled nil))
2198 ;; Ensure no startup file is enabled
2199 (should (not python-shell-prompt-detect-enabled))
2200 (should (not (python-shell-prompt-detect)))))
2202 (ert-deftest python-shell-prompt-detect-4 ()
2203 "Check warning is shown when detection fails."
2204 (skip-unless (executable-find python-tests-shell-interpreter))
2205 (let* ((process-environment process-environment)
2206 ;; Trigger failure by removing prompts in the startup file
2207 (startup-code (concat "import sys\n"
2208 "sys.ps1 = ''\n"
2209 "sys.ps2 = ''\n"
2210 "sys.ps3 = ''\n"))
2211 (startup-file (python-shell--save-temp-file startup-code)))
2212 (unwind-protect
2213 (progn
2214 (kill-buffer (get-buffer-create "*Warnings*"))
2215 (should (not (get-buffer "*Warnings*")))
2216 (setenv "PYTHONSTARTUP" startup-file)
2217 (should python-shell-prompt-detect-failure-warning)
2218 (should python-shell-prompt-detect-enabled)
2219 (should (not (python-shell-prompt-detect)))
2220 (should (get-buffer "*Warnings*")))
2221 (ignore-errors (delete-file startup-file)))))
2223 (ert-deftest python-shell-prompt-detect-5 ()
2224 "Check disabled warnings are not shown when detection fails."
2225 (skip-unless (executable-find python-tests-shell-interpreter))
2226 (let* ((process-environment process-environment)
2227 (startup-code (concat "import sys\n"
2228 "sys.ps1 = ''\n"
2229 "sys.ps2 = ''\n"
2230 "sys.ps3 = ''\n"))
2231 (startup-file (python-shell--save-temp-file startup-code))
2232 (python-shell-prompt-detect-failure-warning nil))
2233 (unwind-protect
2234 (progn
2235 (kill-buffer (get-buffer-create "*Warnings*"))
2236 (should (not (get-buffer "*Warnings*")))
2237 (setenv "PYTHONSTARTUP" startup-file)
2238 (should (not python-shell-prompt-detect-failure-warning))
2239 (should python-shell-prompt-detect-enabled)
2240 (should (not (python-shell-prompt-detect)))
2241 (should (not (get-buffer "*Warnings*"))))
2242 (ignore-errors (delete-file startup-file)))))
2244 (ert-deftest python-shell-prompt-detect-6 ()
2245 "Warnings are not shown when detection is disabled."
2246 (skip-unless (executable-find python-tests-shell-interpreter))
2247 (let* ((process-environment process-environment)
2248 (startup-code (concat "import sys\n"
2249 "sys.ps1 = ''\n"
2250 "sys.ps2 = ''\n"
2251 "sys.ps3 = ''\n"))
2252 (startup-file (python-shell--save-temp-file startup-code))
2253 (python-shell-prompt-detect-failure-warning t)
2254 (python-shell-prompt-detect-enabled nil))
2255 (unwind-protect
2256 (progn
2257 (kill-buffer (get-buffer-create "*Warnings*"))
2258 (should (not (get-buffer "*Warnings*")))
2259 (setenv "PYTHONSTARTUP" startup-file)
2260 (should python-shell-prompt-detect-failure-warning)
2261 (should (not python-shell-prompt-detect-enabled))
2262 (should (not (python-shell-prompt-detect)))
2263 (should (not (get-buffer "*Warnings*"))))
2264 (ignore-errors (delete-file startup-file)))))
2266 (ert-deftest python-shell-prompt-validate-regexps-1 ()
2267 "Check `python-shell-prompt-input-regexps' are validated."
2268 (let* ((python-shell-prompt-input-regexps '("\\("))
2269 (error-data (should-error (python-shell-prompt-validate-regexps)
2270 :type 'user-error)))
2271 (should
2272 (string= (cadr error-data)
2273 "Invalid regexp \\( in `python-shell-prompt-input-regexps'"))))
2275 (ert-deftest python-shell-prompt-validate-regexps-2 ()
2276 "Check `python-shell-prompt-output-regexps' are validated."
2277 (let* ((python-shell-prompt-output-regexps '("\\("))
2278 (error-data (should-error (python-shell-prompt-validate-regexps)
2279 :type 'user-error)))
2280 (should
2281 (string= (cadr error-data)
2282 "Invalid regexp \\( in `python-shell-prompt-output-regexps'"))))
2284 (ert-deftest python-shell-prompt-validate-regexps-3 ()
2285 "Check `python-shell-prompt-regexp' is validated."
2286 (let* ((python-shell-prompt-regexp "\\(")
2287 (error-data (should-error (python-shell-prompt-validate-regexps)
2288 :type 'user-error)))
2289 (should
2290 (string= (cadr error-data)
2291 "Invalid regexp \\( in `python-shell-prompt-regexp'"))))
2293 (ert-deftest python-shell-prompt-validate-regexps-4 ()
2294 "Check `python-shell-prompt-block-regexp' is validated."
2295 (let* ((python-shell-prompt-block-regexp "\\(")
2296 (error-data (should-error (python-shell-prompt-validate-regexps)
2297 :type 'user-error)))
2298 (should
2299 (string= (cadr error-data)
2300 "Invalid regexp \\( in `python-shell-prompt-block-regexp'"))))
2302 (ert-deftest python-shell-prompt-validate-regexps-5 ()
2303 "Check `python-shell-prompt-pdb-regexp' is validated."
2304 (let* ((python-shell-prompt-pdb-regexp "\\(")
2305 (error-data (should-error (python-shell-prompt-validate-regexps)
2306 :type 'user-error)))
2307 (should
2308 (string= (cadr error-data)
2309 "Invalid regexp \\( in `python-shell-prompt-pdb-regexp'"))))
2311 (ert-deftest python-shell-prompt-validate-regexps-6 ()
2312 "Check `python-shell-prompt-output-regexp' is validated."
2313 (let* ((python-shell-prompt-output-regexp "\\(")
2314 (error-data (should-error (python-shell-prompt-validate-regexps)
2315 :type 'user-error)))
2316 (should
2317 (string= (cadr error-data)
2318 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2320 (ert-deftest python-shell-prompt-validate-regexps-7 ()
2321 "Check default regexps are valid."
2322 ;; should not signal error
2323 (python-shell-prompt-validate-regexps))
2325 (ert-deftest python-shell-prompt-set-calculated-regexps-1 ()
2326 "Check regexps are validated."
2327 (let* ((python-shell-prompt-output-regexp '("\\("))
2328 (python-shell--prompt-calculated-input-regexp nil)
2329 (python-shell--prompt-calculated-output-regexp nil)
2330 (python-shell-prompt-detect-enabled nil)
2331 (error-data (should-error (python-shell-prompt-set-calculated-regexps)
2332 :type 'user-error)))
2333 (should
2334 (string= (cadr error-data)
2335 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2337 (ert-deftest python-shell-prompt-set-calculated-regexps-2 ()
2338 "Check `python-shell-prompt-input-regexps' are set."
2339 (let* ((python-shell-prompt-input-regexps '("my" "prompt"))
2340 (python-shell-prompt-output-regexps '(""))
2341 (python-shell-prompt-regexp "")
2342 (python-shell-prompt-block-regexp "")
2343 (python-shell-prompt-pdb-regexp "")
2344 (python-shell-prompt-output-regexp "")
2345 (python-shell--prompt-calculated-input-regexp nil)
2346 (python-shell--prompt-calculated-output-regexp nil)
2347 (python-shell-prompt-detect-enabled nil))
2348 (python-shell-prompt-set-calculated-regexps)
2349 (should (string= python-shell--prompt-calculated-input-regexp
2350 "^\\(prompt\\|my\\|\\)"))))
2352 (ert-deftest python-shell-prompt-set-calculated-regexps-3 ()
2353 "Check `python-shell-prompt-output-regexps' are set."
2354 (let* ((python-shell-prompt-input-regexps '(""))
2355 (python-shell-prompt-output-regexps '("my" "prompt"))
2356 (python-shell-prompt-regexp "")
2357 (python-shell-prompt-block-regexp "")
2358 (python-shell-prompt-pdb-regexp "")
2359 (python-shell-prompt-output-regexp "")
2360 (python-shell--prompt-calculated-input-regexp nil)
2361 (python-shell--prompt-calculated-output-regexp nil)
2362 (python-shell-prompt-detect-enabled nil))
2363 (python-shell-prompt-set-calculated-regexps)
2364 (should (string= python-shell--prompt-calculated-output-regexp
2365 "^\\(prompt\\|my\\|\\)"))))
2367 (ert-deftest python-shell-prompt-set-calculated-regexps-4 ()
2368 "Check user defined prompts are set."
2369 (let* ((python-shell-prompt-input-regexps '(""))
2370 (python-shell-prompt-output-regexps '(""))
2371 (python-shell-prompt-regexp "prompt")
2372 (python-shell-prompt-block-regexp "block")
2373 (python-shell-prompt-pdb-regexp "pdb")
2374 (python-shell-prompt-output-regexp "output")
2375 (python-shell--prompt-calculated-input-regexp nil)
2376 (python-shell--prompt-calculated-output-regexp nil)
2377 (python-shell-prompt-detect-enabled nil))
2378 (python-shell-prompt-set-calculated-regexps)
2379 (should (string= python-shell--prompt-calculated-input-regexp
2380 "^\\(prompt\\|block\\|pdb\\|\\)"))
2381 (should (string= python-shell--prompt-calculated-output-regexp
2382 "^\\(output\\|\\)"))))
2384 (ert-deftest python-shell-prompt-set-calculated-regexps-5 ()
2385 "Check order of regexps (larger first)."
2386 (let* ((python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2387 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2388 (python-shell-prompt-regexp "in")
2389 (python-shell-prompt-block-regexp "block")
2390 (python-shell-prompt-pdb-regexp "pdf")
2391 (python-shell-prompt-output-regexp "output")
2392 (python-shell--prompt-calculated-input-regexp nil)
2393 (python-shell--prompt-calculated-output-regexp nil)
2394 (python-shell-prompt-detect-enabled nil))
2395 (python-shell-prompt-set-calculated-regexps)
2396 (should (string= python-shell--prompt-calculated-input-regexp
2397 "^\\(extralargeinputprompt\\|block\\|pdf\\|sml\\|in\\)"))
2398 (should (string= python-shell--prompt-calculated-output-regexp
2399 "^\\(extralargeoutputprompt\\|output\\|sml\\)"))))
2401 (ert-deftest python-shell-prompt-set-calculated-regexps-6 ()
2402 "Check detected prompts are included `regexp-quote'd."
2403 (skip-unless (executable-find python-tests-shell-interpreter))
2404 (let* ((python-shell-prompt-input-regexps '(""))
2405 (python-shell-prompt-output-regexps '(""))
2406 (python-shell-prompt-regexp "")
2407 (python-shell-prompt-block-regexp "")
2408 (python-shell-prompt-pdb-regexp "")
2409 (python-shell-prompt-output-regexp "")
2410 (python-shell--prompt-calculated-input-regexp nil)
2411 (python-shell--prompt-calculated-output-regexp nil)
2412 (python-shell-prompt-detect-enabled t)
2413 (process-environment process-environment)
2414 (startup-code (concat "import sys\n"
2415 "sys.ps1 = 'p.> '\n"
2416 "sys.ps2 = '..> '\n"
2417 "sys.ps3 = 'o.t '\n"))
2418 (startup-file (python-shell--save-temp-file startup-code)))
2419 (unwind-protect
2420 (progn
2421 (setenv "PYTHONSTARTUP" startup-file)
2422 (python-shell-prompt-set-calculated-regexps)
2423 (should (string= python-shell--prompt-calculated-input-regexp
2424 "^\\(\\.\\.> \\|p\\.> \\|\\)"))
2425 (should (string= python-shell--prompt-calculated-output-regexp
2426 "^\\(o\\.t \\|\\)")))
2427 (ignore-errors (delete-file startup-file)))))
2430 ;;; Shell completion
2433 ;;; PDB Track integration
2436 ;;; Symbol completion
2439 ;;; Fill paragraph
2442 ;;; Skeletons
2445 ;;; FFAP
2448 ;;; Code check
2451 ;;; Eldoc
2454 ;;; Imenu
2456 (ert-deftest python-imenu-create-index-1 ()
2457 (python-tests-with-temp-buffer
2459 class Foo(models.Model):
2460 pass
2463 class Bar(models.Model):
2464 pass
2467 def decorator(arg1, arg2, arg3):
2468 '''print decorated function call data to stdout.
2470 Usage:
2472 @decorator('arg1', 'arg2')
2473 def func(a, b, c=True):
2474 pass
2477 def wrap(f):
2478 print ('wrap')
2479 def wrapped_f(*args):
2480 print ('wrapped_f')
2481 print ('Decorator arguments:', arg1, arg2, arg3)
2482 f(*args)
2483 print ('called f(*args)')
2484 return wrapped_f
2485 return wrap
2488 class Baz(object):
2490 def a(self):
2491 pass
2493 def b(self):
2494 pass
2496 class Frob(object):
2498 def c(self):
2499 pass
2501 (goto-char (point-max))
2502 (should (equal
2503 (list
2504 (cons "Foo (class)" (copy-marker 2))
2505 (cons "Bar (class)" (copy-marker 38))
2506 (list
2507 "decorator (def)"
2508 (cons "*function definition*" (copy-marker 74))
2509 (list
2510 "wrap (def)"
2511 (cons "*function definition*" (copy-marker 254))
2512 (cons "wrapped_f (def)" (copy-marker 294))))
2513 (list
2514 "Baz (class)"
2515 (cons "*class definition*" (copy-marker 519))
2516 (cons "a (def)" (copy-marker 539))
2517 (cons "b (def)" (copy-marker 570))
2518 (list
2519 "Frob (class)"
2520 (cons "*class definition*" (copy-marker 601))
2521 (cons "c (def)" (copy-marker 626)))))
2522 (python-imenu-create-index)))))
2524 (ert-deftest python-imenu-create-index-2 ()
2525 (python-tests-with-temp-buffer
2527 class Foo(object):
2528 def foo(self):
2529 def foo1():
2530 pass
2532 def foobar(self):
2533 pass
2535 (goto-char (point-max))
2536 (should (equal
2537 (list
2538 (list
2539 "Foo (class)"
2540 (cons "*class definition*" (copy-marker 2))
2541 (list
2542 "foo (def)"
2543 (cons "*function definition*" (copy-marker 21))
2544 (cons "foo1 (def)" (copy-marker 40)))
2545 (cons "foobar (def)" (copy-marker 78))))
2546 (python-imenu-create-index)))))
2548 (ert-deftest python-imenu-create-index-3 ()
2549 (python-tests-with-temp-buffer
2551 class Foo(object):
2552 def foo(self):
2553 def foo1():
2554 pass
2555 def foo2():
2556 pass
2558 (goto-char (point-max))
2559 (should (equal
2560 (list
2561 (list
2562 "Foo (class)"
2563 (cons "*class definition*" (copy-marker 2))
2564 (list
2565 "foo (def)"
2566 (cons "*function definition*" (copy-marker 21))
2567 (cons "foo1 (def)" (copy-marker 40))
2568 (cons "foo2 (def)" (copy-marker 77)))))
2569 (python-imenu-create-index)))))
2571 (ert-deftest python-imenu-create-index-4 ()
2572 (python-tests-with-temp-buffer
2574 class Foo(object):
2575 class Bar(object):
2576 def __init__(self):
2577 pass
2579 def __str__(self):
2580 pass
2582 def __init__(self):
2583 pass
2585 (goto-char (point-max))
2586 (should (equal
2587 (list
2588 (list
2589 "Foo (class)"
2590 (cons "*class definition*" (copy-marker 2))
2591 (list
2592 "Bar (class)"
2593 (cons "*class definition*" (copy-marker 21))
2594 (cons "__init__ (def)" (copy-marker 44))
2595 (cons "__str__ (def)" (copy-marker 90)))
2596 (cons "__init__ (def)" (copy-marker 135))))
2597 (python-imenu-create-index)))))
2599 (ert-deftest python-imenu-create-flat-index-1 ()
2600 (python-tests-with-temp-buffer
2602 class Foo(models.Model):
2603 pass
2606 class Bar(models.Model):
2607 pass
2610 def decorator(arg1, arg2, arg3):
2611 '''print decorated function call data to stdout.
2613 Usage:
2615 @decorator('arg1', 'arg2')
2616 def func(a, b, c=True):
2617 pass
2620 def wrap(f):
2621 print ('wrap')
2622 def wrapped_f(*args):
2623 print ('wrapped_f')
2624 print ('Decorator arguments:', arg1, arg2, arg3)
2625 f(*args)
2626 print ('called f(*args)')
2627 return wrapped_f
2628 return wrap
2631 class Baz(object):
2633 def a(self):
2634 pass
2636 def b(self):
2637 pass
2639 class Frob(object):
2641 def c(self):
2642 pass
2644 (goto-char (point-max))
2645 (should (equal
2646 (list (cons "Foo" (copy-marker 2))
2647 (cons "Bar" (copy-marker 38))
2648 (cons "decorator" (copy-marker 74))
2649 (cons "decorator.wrap" (copy-marker 254))
2650 (cons "decorator.wrap.wrapped_f" (copy-marker 294))
2651 (cons "Baz" (copy-marker 519))
2652 (cons "Baz.a" (copy-marker 539))
2653 (cons "Baz.b" (copy-marker 570))
2654 (cons "Baz.Frob" (copy-marker 601))
2655 (cons "Baz.Frob.c" (copy-marker 626)))
2656 (python-imenu-create-flat-index)))))
2658 (ert-deftest python-imenu-create-flat-index-2 ()
2659 (python-tests-with-temp-buffer
2661 class Foo(object):
2662 class Bar(object):
2663 def __init__(self):
2664 pass
2666 def __str__(self):
2667 pass
2669 def __init__(self):
2670 pass
2672 (goto-char (point-max))
2673 (should (equal
2674 (list
2675 (cons "Foo" (copy-marker 2))
2676 (cons "Foo.Bar" (copy-marker 21))
2677 (cons "Foo.Bar.__init__" (copy-marker 44))
2678 (cons "Foo.Bar.__str__" (copy-marker 90))
2679 (cons "Foo.__init__" (copy-marker 135)))
2680 (python-imenu-create-flat-index)))))
2683 ;;; Misc helpers
2685 (ert-deftest python-info-current-defun-1 ()
2686 (python-tests-with-temp-buffer
2688 def foo(a, b):
2690 (forward-line 1)
2691 (should (string= "foo" (python-info-current-defun)))
2692 (should (string= "def foo" (python-info-current-defun t)))
2693 (forward-line 1)
2694 (should (not (python-info-current-defun)))
2695 (indent-for-tab-command)
2696 (should (string= "foo" (python-info-current-defun)))
2697 (should (string= "def foo" (python-info-current-defun t)))))
2699 (ert-deftest python-info-current-defun-2 ()
2700 (python-tests-with-temp-buffer
2702 class C(object):
2704 def m(self):
2705 if True:
2706 return [i for i in range(3)]
2707 else:
2708 return []
2710 def b():
2711 do_b()
2713 def a():
2714 do_a()
2716 def c(self):
2717 do_c()
2719 (forward-line 1)
2720 (should (string= "C" (python-info-current-defun)))
2721 (should (string= "class C" (python-info-current-defun t)))
2722 (python-tests-look-at "return [i for ")
2723 (should (string= "C.m" (python-info-current-defun)))
2724 (should (string= "def C.m" (python-info-current-defun t)))
2725 (python-tests-look-at "def b():")
2726 (should (string= "C.m.b" (python-info-current-defun)))
2727 (should (string= "def C.m.b" (python-info-current-defun t)))
2728 (forward-line 2)
2729 (indent-for-tab-command)
2730 (python-indent-dedent-line-backspace 1)
2731 (should (string= "C.m" (python-info-current-defun)))
2732 (should (string= "def C.m" (python-info-current-defun t)))
2733 (python-tests-look-at "def c(self):")
2734 (forward-line -1)
2735 (indent-for-tab-command)
2736 (should (string= "C.m.a" (python-info-current-defun)))
2737 (should (string= "def C.m.a" (python-info-current-defun t)))
2738 (python-indent-dedent-line-backspace 1)
2739 (should (string= "C.m" (python-info-current-defun)))
2740 (should (string= "def C.m" (python-info-current-defun t)))
2741 (python-indent-dedent-line-backspace 1)
2742 (should (string= "C" (python-info-current-defun)))
2743 (should (string= "class C" (python-info-current-defun t)))
2744 (python-tests-look-at "def c(self):")
2745 (should (string= "C.c" (python-info-current-defun)))
2746 (should (string= "def C.c" (python-info-current-defun t)))
2747 (python-tests-look-at "do_c()")
2748 (should (string= "C.c" (python-info-current-defun)))
2749 (should (string= "def C.c" (python-info-current-defun t)))))
2751 (ert-deftest python-info-current-defun-3 ()
2752 (python-tests-with-temp-buffer
2754 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2755 '''print decorated function call data to stdout.
2757 Usage:
2759 @decoratorFunctionWithArguments('arg1', 'arg2')
2760 def func(a, b, c=True):
2761 pass
2764 def wwrap(f):
2765 print 'Inside wwrap()'
2766 def wrapped_f(*args):
2767 print 'Inside wrapped_f()'
2768 print 'Decorator arguments:', arg1, arg2, arg3
2769 f(*args)
2770 print 'After f(*args)'
2771 return wrapped_f
2772 return wwrap
2774 (python-tests-look-at "def wwrap(f):")
2775 (forward-line -1)
2776 (should (not (python-info-current-defun)))
2777 (indent-for-tab-command 1)
2778 (should (string= (python-info-current-defun)
2779 "decoratorFunctionWithArguments"))
2780 (should (string= (python-info-current-defun t)
2781 "def decoratorFunctionWithArguments"))
2782 (python-tests-look-at "def wrapped_f(*args):")
2783 (should (string= (python-info-current-defun)
2784 "decoratorFunctionWithArguments.wwrap.wrapped_f"))
2785 (should (string= (python-info-current-defun t)
2786 "def decoratorFunctionWithArguments.wwrap.wrapped_f"))
2787 (python-tests-look-at "return wrapped_f")
2788 (should (string= (python-info-current-defun)
2789 "decoratorFunctionWithArguments.wwrap"))
2790 (should (string= (python-info-current-defun t)
2791 "def decoratorFunctionWithArguments.wwrap"))
2792 (end-of-line 1)
2793 (python-tests-look-at "return wwrap")
2794 (should (string= (python-info-current-defun)
2795 "decoratorFunctionWithArguments"))
2796 (should (string= (python-info-current-defun t)
2797 "def decoratorFunctionWithArguments"))))
2799 (ert-deftest python-info-current-symbol-1 ()
2800 (python-tests-with-temp-buffer
2802 class C(object):
2804 def m(self):
2805 self.c()
2807 def c(self):
2808 print ('a')
2810 (python-tests-look-at "self.c()")
2811 (should (string= "self.c" (python-info-current-symbol)))
2812 (should (string= "C.c" (python-info-current-symbol t)))))
2814 (ert-deftest python-info-current-symbol-2 ()
2815 (python-tests-with-temp-buffer
2817 class C(object):
2819 class M(object):
2821 def a(self):
2822 self.c()
2824 def c(self):
2825 pass
2827 (python-tests-look-at "self.c()")
2828 (should (string= "self.c" (python-info-current-symbol)))
2829 (should (string= "C.M.c" (python-info-current-symbol t)))))
2831 (ert-deftest python-info-current-symbol-3 ()
2832 "Keywords should not be considered symbols."
2833 :expected-result :failed
2834 (python-tests-with-temp-buffer
2836 class C(object):
2837 pass
2839 ;; FIXME: keywords are not symbols.
2840 (python-tests-look-at "class C")
2841 (should (not (python-info-current-symbol)))
2842 (should (not (python-info-current-symbol t)))
2843 (python-tests-look-at "C(object)")
2844 (should (string= "C" (python-info-current-symbol)))
2845 (should (string= "class C" (python-info-current-symbol t)))))
2847 (ert-deftest python-info-statement-starts-block-p-1 ()
2848 (python-tests-with-temp-buffer
2850 def long_function_name(
2851 var_one, var_two, var_three,
2852 var_four):
2853 print (var_one)
2855 (python-tests-look-at "def long_function_name")
2856 (should (python-info-statement-starts-block-p))
2857 (python-tests-look-at "print (var_one)")
2858 (python-util-forward-comment -1)
2859 (should (python-info-statement-starts-block-p))))
2861 (ert-deftest python-info-statement-starts-block-p-2 ()
2862 (python-tests-with-temp-buffer
2864 if width == 0 and height == 0 and \\\\
2865 color == 'red' and emphasis == 'strong' or \\\\
2866 highlight > 100:
2867 raise ValueError('sorry, you lose')
2869 (python-tests-look-at "if width == 0 and")
2870 (should (python-info-statement-starts-block-p))
2871 (python-tests-look-at "raise ValueError(")
2872 (python-util-forward-comment -1)
2873 (should (python-info-statement-starts-block-p))))
2875 (ert-deftest python-info-statement-ends-block-p-1 ()
2876 (python-tests-with-temp-buffer
2878 def long_function_name(
2879 var_one, var_two, var_three,
2880 var_four):
2881 print (var_one)
2883 (python-tests-look-at "print (var_one)")
2884 (should (python-info-statement-ends-block-p))))
2886 (ert-deftest python-info-statement-ends-block-p-2 ()
2887 (python-tests-with-temp-buffer
2889 if width == 0 and height == 0 and \\\\
2890 color == 'red' and emphasis == 'strong' or \\\\
2891 highlight > 100:
2892 raise ValueError(
2893 'sorry, you lose'
2897 (python-tests-look-at "raise ValueError(")
2898 (should (python-info-statement-ends-block-p))))
2900 (ert-deftest python-info-beginning-of-statement-p-1 ()
2901 (python-tests-with-temp-buffer
2903 def long_function_name(
2904 var_one, var_two, var_three,
2905 var_four):
2906 print (var_one)
2908 (python-tests-look-at "def long_function_name")
2909 (should (python-info-beginning-of-statement-p))
2910 (forward-char 10)
2911 (should (not (python-info-beginning-of-statement-p)))
2912 (python-tests-look-at "print (var_one)")
2913 (should (python-info-beginning-of-statement-p))
2914 (goto-char (line-beginning-position))
2915 (should (not (python-info-beginning-of-statement-p)))))
2917 (ert-deftest python-info-beginning-of-statement-p-2 ()
2918 (python-tests-with-temp-buffer
2920 if width == 0 and height == 0 and \\\\
2921 color == 'red' and emphasis == 'strong' or \\\\
2922 highlight > 100:
2923 raise ValueError(
2924 'sorry, you lose'
2928 (python-tests-look-at "if width == 0 and")
2929 (should (python-info-beginning-of-statement-p))
2930 (forward-char 10)
2931 (should (not (python-info-beginning-of-statement-p)))
2932 (python-tests-look-at "raise ValueError(")
2933 (should (python-info-beginning-of-statement-p))
2934 (goto-char (line-beginning-position))
2935 (should (not (python-info-beginning-of-statement-p)))))
2937 (ert-deftest python-info-end-of-statement-p-1 ()
2938 (python-tests-with-temp-buffer
2940 def long_function_name(
2941 var_one, var_two, var_three,
2942 var_four):
2943 print (var_one)
2945 (python-tests-look-at "def long_function_name")
2946 (should (not (python-info-end-of-statement-p)))
2947 (end-of-line)
2948 (should (not (python-info-end-of-statement-p)))
2949 (python-tests-look-at "print (var_one)")
2950 (python-util-forward-comment -1)
2951 (should (python-info-end-of-statement-p))
2952 (python-tests-look-at "print (var_one)")
2953 (should (not (python-info-end-of-statement-p)))
2954 (end-of-line)
2955 (should (python-info-end-of-statement-p))))
2957 (ert-deftest python-info-end-of-statement-p-2 ()
2958 (python-tests-with-temp-buffer
2960 if width == 0 and height == 0 and \\\\
2961 color == 'red' and emphasis == 'strong' or \\\\
2962 highlight > 100:
2963 raise ValueError(
2964 'sorry, you lose'
2968 (python-tests-look-at "if width == 0 and")
2969 (should (not (python-info-end-of-statement-p)))
2970 (end-of-line)
2971 (should (not (python-info-end-of-statement-p)))
2972 (python-tests-look-at "raise ValueError(")
2973 (python-util-forward-comment -1)
2974 (should (python-info-end-of-statement-p))
2975 (python-tests-look-at "raise ValueError(")
2976 (should (not (python-info-end-of-statement-p)))
2977 (end-of-line)
2978 (should (not (python-info-end-of-statement-p)))
2979 (goto-char (point-max))
2980 (python-util-forward-comment -1)
2981 (should (python-info-end-of-statement-p))))
2983 (ert-deftest python-info-beginning-of-block-p-1 ()
2984 (python-tests-with-temp-buffer
2986 def long_function_name(
2987 var_one, var_two, var_three,
2988 var_four):
2989 print (var_one)
2991 (python-tests-look-at "def long_function_name")
2992 (should (python-info-beginning-of-block-p))
2993 (python-tests-look-at "var_one, var_two, var_three,")
2994 (should (not (python-info-beginning-of-block-p)))
2995 (python-tests-look-at "print (var_one)")
2996 (should (not (python-info-beginning-of-block-p)))))
2998 (ert-deftest python-info-beginning-of-block-p-2 ()
2999 (python-tests-with-temp-buffer
3001 if width == 0 and height == 0 and \\\\
3002 color == 'red' and emphasis == 'strong' or \\\\
3003 highlight > 100:
3004 raise ValueError(
3005 'sorry, you lose'
3009 (python-tests-look-at "if width == 0 and")
3010 (should (python-info-beginning-of-block-p))
3011 (python-tests-look-at "color == 'red' and emphasis")
3012 (should (not (python-info-beginning-of-block-p)))
3013 (python-tests-look-at "raise ValueError(")
3014 (should (not (python-info-beginning-of-block-p)))))
3016 (ert-deftest python-info-end-of-block-p-1 ()
3017 (python-tests-with-temp-buffer
3019 def long_function_name(
3020 var_one, var_two, var_three,
3021 var_four):
3022 print (var_one)
3024 (python-tests-look-at "def long_function_name")
3025 (should (not (python-info-end-of-block-p)))
3026 (python-tests-look-at "var_one, var_two, var_three,")
3027 (should (not (python-info-end-of-block-p)))
3028 (python-tests-look-at "var_four):")
3029 (end-of-line)
3030 (should (not (python-info-end-of-block-p)))
3031 (python-tests-look-at "print (var_one)")
3032 (should (not (python-info-end-of-block-p)))
3033 (end-of-line 1)
3034 (should (python-info-end-of-block-p))))
3036 (ert-deftest python-info-end-of-block-p-2 ()
3037 (python-tests-with-temp-buffer
3039 if width == 0 and height == 0 and \\\\
3040 color == 'red' and emphasis == 'strong' or \\\\
3041 highlight > 100:
3042 raise ValueError(
3043 'sorry, you lose'
3047 (python-tests-look-at "if width == 0 and")
3048 (should (not (python-info-end-of-block-p)))
3049 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3050 (should (not (python-info-end-of-block-p)))
3051 (python-tests-look-at "highlight > 100:")
3052 (end-of-line)
3053 (should (not (python-info-end-of-block-p)))
3054 (python-tests-look-at "raise ValueError(")
3055 (should (not (python-info-end-of-block-p)))
3056 (end-of-line 1)
3057 (should (not (python-info-end-of-block-p)))
3058 (goto-char (point-max))
3059 (python-util-forward-comment -1)
3060 (should (python-info-end-of-block-p))))
3062 (ert-deftest python-info-dedenter-opening-block-position-1 ()
3063 (python-tests-with-temp-buffer
3065 if request.user.is_authenticated():
3066 try:
3067 profile = request.user.get_profile()
3068 except Profile.DoesNotExist:
3069 profile = Profile.objects.create(user=request.user)
3070 else:
3071 if profile.stats:
3072 profile.recalculate_stats()
3073 else:
3074 profile.clear_stats()
3075 finally:
3076 profile.views += 1
3077 profile.save()
3079 (python-tests-look-at "try:")
3080 (should (not (python-info-dedenter-opening-block-position)))
3081 (python-tests-look-at "except Profile.DoesNotExist:")
3082 (should (= (python-tests-look-at "try:" -1 t)
3083 (python-info-dedenter-opening-block-position)))
3084 (python-tests-look-at "else:")
3085 (should (= (python-tests-look-at "except Profile.DoesNotExist:" -1 t)
3086 (python-info-dedenter-opening-block-position)))
3087 (python-tests-look-at "if profile.stats:")
3088 (should (not (python-info-dedenter-opening-block-position)))
3089 (python-tests-look-at "else:")
3090 (should (= (python-tests-look-at "if profile.stats:" -1 t)
3091 (python-info-dedenter-opening-block-position)))
3092 (python-tests-look-at "finally:")
3093 (should (= (python-tests-look-at "else:" -2 t)
3094 (python-info-dedenter-opening-block-position)))))
3096 (ert-deftest python-info-dedenter-opening-block-position-2 ()
3097 (python-tests-with-temp-buffer
3099 if request.user.is_authenticated():
3100 profile = Profile.objects.get_or_create(user=request.user)
3101 if profile.stats:
3102 profile.recalculate_stats()
3104 data = {
3105 'else': 'do it'
3107 'else'
3109 (python-tests-look-at "'else': 'do it'")
3110 (should (not (python-info-dedenter-opening-block-position)))
3111 (python-tests-look-at "'else'")
3112 (should (not (python-info-dedenter-opening-block-position)))))
3114 (ert-deftest python-info-dedenter-opening-block-position-3 ()
3115 (python-tests-with-temp-buffer
3117 if save:
3118 try:
3119 write_to_disk(data)
3120 except IOError:
3121 msg = 'Error saving to disk'
3122 message(msg)
3123 logger.exception(msg)
3124 except Exception:
3125 if hide_details:
3126 logger.exception('Unhandled exception')
3127 else
3128 finally:
3129 data.free()
3131 (python-tests-look-at "try:")
3132 (should (not (python-info-dedenter-opening-block-position)))
3134 (python-tests-look-at "except IOError:")
3135 (should (= (python-tests-look-at "try:" -1 t)
3136 (python-info-dedenter-opening-block-position)))
3138 (python-tests-look-at "except Exception:")
3139 (should (= (python-tests-look-at "except IOError:" -1 t)
3140 (python-info-dedenter-opening-block-position)))
3142 (python-tests-look-at "if hide_details:")
3143 (should (not (python-info-dedenter-opening-block-position)))
3145 ;; check indentation modifies the detected opening block
3146 (python-tests-look-at "else")
3147 (should (= (python-tests-look-at "if hide_details:" -1 t)
3148 (python-info-dedenter-opening-block-position)))
3150 (indent-line-to 8)
3151 (should (= (python-tests-look-at "if hide_details:" -1 t)
3152 (python-info-dedenter-opening-block-position)))
3154 (indent-line-to 4)
3155 (should (= (python-tests-look-at "except Exception:" -1 t)
3156 (python-info-dedenter-opening-block-position)))
3158 (indent-line-to 0)
3159 (should (= (python-tests-look-at "if save:" -1 t)
3160 (python-info-dedenter-opening-block-position)))))
3162 (ert-deftest python-info-dedenter-opening-block-positions-1 ()
3163 (python-tests-with-temp-buffer
3165 if save:
3166 try:
3167 write_to_disk(data)
3168 except IOError:
3169 msg = 'Error saving to disk'
3170 message(msg)
3171 logger.exception(msg)
3172 except Exception:
3173 if hide_details:
3174 logger.exception('Unhandled exception')
3175 else
3176 finally:
3177 data.free()
3179 (python-tests-look-at "try:")
3180 (should (not (python-info-dedenter-opening-block-positions)))
3182 (python-tests-look-at "except IOError:")
3183 (should
3184 (equal (list
3185 (python-tests-look-at "try:" -1 t))
3186 (python-info-dedenter-opening-block-positions)))
3188 (python-tests-look-at "except Exception:")
3189 (should
3190 (equal (list
3191 (python-tests-look-at "except IOError:" -1 t))
3192 (python-info-dedenter-opening-block-positions)))
3194 (python-tests-look-at "if hide_details:")
3195 (should (not (python-info-dedenter-opening-block-positions)))
3197 ;; check indentation does not modify the detected opening blocks
3198 (python-tests-look-at "else")
3199 (should
3200 (equal (list
3201 (python-tests-look-at "if hide_details:" -1 t)
3202 (python-tests-look-at "except Exception:" -1 t)
3203 (python-tests-look-at "if save:" -1 t))
3204 (python-info-dedenter-opening-block-positions)))
3206 (indent-line-to 8)
3207 (should
3208 (equal (list
3209 (python-tests-look-at "if hide_details:" -1 t)
3210 (python-tests-look-at "except Exception:" -1 t)
3211 (python-tests-look-at "if save:" -1 t))
3212 (python-info-dedenter-opening-block-positions)))
3214 (indent-line-to 4)
3215 (should
3216 (equal (list
3217 (python-tests-look-at "if hide_details:" -1 t)
3218 (python-tests-look-at "except Exception:" -1 t)
3219 (python-tests-look-at "if save:" -1 t))
3220 (python-info-dedenter-opening-block-positions)))
3222 (indent-line-to 0)
3223 (should
3224 (equal (list
3225 (python-tests-look-at "if hide_details:" -1 t)
3226 (python-tests-look-at "except Exception:" -1 t)
3227 (python-tests-look-at "if save:" -1 t))
3228 (python-info-dedenter-opening-block-positions)))))
3230 (ert-deftest python-info-dedenter-opening-block-positions-2 ()
3231 "Test detection of opening blocks for elif."
3232 (python-tests-with-temp-buffer
3234 if var:
3235 if var2:
3236 something()
3237 elif var3:
3238 something_else()
3239 elif
3241 (python-tests-look-at "elif var3:")
3242 (should
3243 (equal (list
3244 (python-tests-look-at "if var2:" -1 t)
3245 (python-tests-look-at "if var:" -1 t))
3246 (python-info-dedenter-opening-block-positions)))
3248 (python-tests-look-at "elif\n")
3249 (should
3250 (equal (list
3251 (python-tests-look-at "elif var3:" -1 t)
3252 (python-tests-look-at "if var:" -1 t))
3253 (python-info-dedenter-opening-block-positions)))))
3255 (ert-deftest python-info-dedenter-opening-block-positions-3 ()
3256 "Test detection of opening blocks for else."
3257 (python-tests-with-temp-buffer
3259 try:
3260 something()
3261 except:
3262 if var:
3263 if var2:
3264 something()
3265 elif var3:
3266 something_else()
3267 else
3269 if var4:
3270 while var5:
3271 var4.pop()
3272 else
3274 for value in var6:
3275 if value > 0:
3276 print value
3277 else
3279 (python-tests-look-at "else\n")
3280 (should
3281 (equal (list
3282 (python-tests-look-at "elif var3:" -1 t)
3283 (python-tests-look-at "if var:" -1 t)
3284 (python-tests-look-at "except:" -1 t))
3285 (python-info-dedenter-opening-block-positions)))
3287 (python-tests-look-at "else\n")
3288 (should
3289 (equal (list
3290 (python-tests-look-at "while var5:" -1 t)
3291 (python-tests-look-at "if var4:" -1 t))
3292 (python-info-dedenter-opening-block-positions)))
3294 (python-tests-look-at "else\n")
3295 (should
3296 (equal (list
3297 (python-tests-look-at "if value > 0:" -1 t)
3298 (python-tests-look-at "for value in var6:" -1 t)
3299 (python-tests-look-at "if var4:" -1 t))
3300 (python-info-dedenter-opening-block-positions)))))
3302 (ert-deftest python-info-dedenter-opening-block-positions-4 ()
3303 "Test detection of opening blocks for except."
3304 (python-tests-with-temp-buffer
3306 try:
3307 something()
3308 except ValueError:
3309 something_else()
3310 except
3312 (python-tests-look-at "except ValueError:")
3313 (should
3314 (equal (list (python-tests-look-at "try:" -1 t))
3315 (python-info-dedenter-opening-block-positions)))
3317 (python-tests-look-at "except\n")
3318 (should
3319 (equal (list (python-tests-look-at "except ValueError:" -1 t))
3320 (python-info-dedenter-opening-block-positions)))))
3322 (ert-deftest python-info-dedenter-opening-block-positions-5 ()
3323 "Test detection of opening blocks for finally."
3324 (python-tests-with-temp-buffer
3326 try:
3327 something()
3328 finally
3330 try:
3331 something_else()
3332 except:
3333 logger.exception('something went wrong')
3334 finally
3336 try:
3337 something_else_else()
3338 except Exception:
3339 logger.exception('something else went wrong')
3340 else:
3341 print ('all good')
3342 finally
3344 (python-tests-look-at "finally\n")
3345 (should
3346 (equal (list (python-tests-look-at "try:" -1 t))
3347 (python-info-dedenter-opening-block-positions)))
3349 (python-tests-look-at "finally\n")
3350 (should
3351 (equal (list (python-tests-look-at "except:" -1 t))
3352 (python-info-dedenter-opening-block-positions)))
3354 (python-tests-look-at "finally\n")
3355 (should
3356 (equal (list (python-tests-look-at "else:" -1 t))
3357 (python-info-dedenter-opening-block-positions)))))
3359 (ert-deftest python-info-dedenter-opening-block-message-1 ()
3360 "Test dedenters inside strings are ignored."
3361 (python-tests-with-temp-buffer
3362 "'''
3363 try:
3364 something()
3365 except:
3366 logger.exception('something went wrong')
3369 (python-tests-look-at "except\n")
3370 (should (not (python-info-dedenter-opening-block-message)))))
3372 (ert-deftest python-info-dedenter-opening-block-message-2 ()
3373 "Test except keyword."
3374 (python-tests-with-temp-buffer
3376 try:
3377 something()
3378 except:
3379 logger.exception('something went wrong')
3381 (python-tests-look-at "except:")
3382 (should (string=
3383 "Closes try:"
3384 (substring-no-properties
3385 (python-info-dedenter-opening-block-message))))
3386 (end-of-line)
3387 (should (string=
3388 "Closes try:"
3389 (substring-no-properties
3390 (python-info-dedenter-opening-block-message))))))
3392 (ert-deftest python-info-dedenter-opening-block-message-3 ()
3393 "Test else keyword."
3394 (python-tests-with-temp-buffer
3396 try:
3397 something()
3398 except:
3399 logger.exception('something went wrong')
3400 else:
3401 logger.debug('all good')
3403 (python-tests-look-at "else:")
3404 (should (string=
3405 "Closes except:"
3406 (substring-no-properties
3407 (python-info-dedenter-opening-block-message))))
3408 (end-of-line)
3409 (should (string=
3410 "Closes except:"
3411 (substring-no-properties
3412 (python-info-dedenter-opening-block-message))))))
3414 (ert-deftest python-info-dedenter-opening-block-message-4 ()
3415 "Test finally keyword."
3416 (python-tests-with-temp-buffer
3418 try:
3419 something()
3420 except:
3421 logger.exception('something went wrong')
3422 else:
3423 logger.debug('all good')
3424 finally:
3425 clean()
3427 (python-tests-look-at "finally:")
3428 (should (string=
3429 "Closes else:"
3430 (substring-no-properties
3431 (python-info-dedenter-opening-block-message))))
3432 (end-of-line)
3433 (should (string=
3434 "Closes else:"
3435 (substring-no-properties
3436 (python-info-dedenter-opening-block-message))))))
3438 (ert-deftest python-info-dedenter-opening-block-message-5 ()
3439 "Test elif keyword."
3440 (python-tests-with-temp-buffer
3442 if a:
3443 something()
3444 elif b:
3446 (python-tests-look-at "elif b:")
3447 (should (string=
3448 "Closes if a:"
3449 (substring-no-properties
3450 (python-info-dedenter-opening-block-message))))
3451 (end-of-line)
3452 (should (string=
3453 "Closes if a:"
3454 (substring-no-properties
3455 (python-info-dedenter-opening-block-message))))))
3458 (ert-deftest python-info-dedenter-statement-p-1 ()
3459 "Test dedenters inside strings are ignored."
3460 (python-tests-with-temp-buffer
3461 "'''
3462 try:
3463 something()
3464 except:
3465 logger.exception('something went wrong')
3468 (python-tests-look-at "except\n")
3469 (should (not (python-info-dedenter-statement-p)))))
3471 (ert-deftest python-info-dedenter-statement-p-2 ()
3472 "Test except keyword."
3473 (python-tests-with-temp-buffer
3475 try:
3476 something()
3477 except:
3478 logger.exception('something went wrong')
3480 (python-tests-look-at "except:")
3481 (should (= (point) (python-info-dedenter-statement-p)))
3482 (end-of-line)
3483 (should (= (save-excursion
3484 (back-to-indentation)
3485 (point))
3486 (python-info-dedenter-statement-p)))))
3488 (ert-deftest python-info-dedenter-statement-p-3 ()
3489 "Test else keyword."
3490 (python-tests-with-temp-buffer
3492 try:
3493 something()
3494 except:
3495 logger.exception('something went wrong')
3496 else:
3497 logger.debug('all good')
3499 (python-tests-look-at "else:")
3500 (should (= (point) (python-info-dedenter-statement-p)))
3501 (end-of-line)
3502 (should (= (save-excursion
3503 (back-to-indentation)
3504 (point))
3505 (python-info-dedenter-statement-p)))))
3507 (ert-deftest python-info-dedenter-statement-p-4 ()
3508 "Test finally keyword."
3509 (python-tests-with-temp-buffer
3511 try:
3512 something()
3513 except:
3514 logger.exception('something went wrong')
3515 else:
3516 logger.debug('all good')
3517 finally:
3518 clean()
3520 (python-tests-look-at "finally:")
3521 (should (= (point) (python-info-dedenter-statement-p)))
3522 (end-of-line)
3523 (should (= (save-excursion
3524 (back-to-indentation)
3525 (point))
3526 (python-info-dedenter-statement-p)))))
3528 (ert-deftest python-info-dedenter-statement-p-5 ()
3529 "Test elif keyword."
3530 (python-tests-with-temp-buffer
3532 if a:
3533 something()
3534 elif b:
3536 (python-tests-look-at "elif b:")
3537 (should (= (point) (python-info-dedenter-statement-p)))
3538 (end-of-line)
3539 (should (= (save-excursion
3540 (back-to-indentation)
3541 (point))
3542 (python-info-dedenter-statement-p)))))
3544 (ert-deftest python-info-line-ends-backslash-p-1 ()
3545 (python-tests-with-temp-buffer
3547 objects = Thing.objects.all() \\\\
3548 .filter(
3549 type='toy',
3550 status='bought'
3551 ) \\\\
3552 .aggregate(
3553 Sum('amount')
3554 ) \\\\
3555 .values_list()
3557 (should (python-info-line-ends-backslash-p 2)) ; .filter(...
3558 (should (python-info-line-ends-backslash-p 3))
3559 (should (python-info-line-ends-backslash-p 4))
3560 (should (python-info-line-ends-backslash-p 5))
3561 (should (python-info-line-ends-backslash-p 6)) ; ) \...
3562 (should (python-info-line-ends-backslash-p 7))
3563 (should (python-info-line-ends-backslash-p 8))
3564 (should (python-info-line-ends-backslash-p 9))
3565 (should (not (python-info-line-ends-backslash-p 10))))) ; .values_list()...
3567 (ert-deftest python-info-beginning-of-backslash-1 ()
3568 (python-tests-with-temp-buffer
3570 objects = Thing.objects.all() \\\\
3571 .filter(
3572 type='toy',
3573 status='bought'
3574 ) \\\\
3575 .aggregate(
3576 Sum('amount')
3577 ) \\\\
3578 .values_list()
3580 (let ((first 2)
3581 (second (python-tests-look-at ".filter("))
3582 (third (python-tests-look-at ".aggregate(")))
3583 (should (= first (python-info-beginning-of-backslash 2)))
3584 (should (= second (python-info-beginning-of-backslash 3)))
3585 (should (= second (python-info-beginning-of-backslash 4)))
3586 (should (= second (python-info-beginning-of-backslash 5)))
3587 (should (= second (python-info-beginning-of-backslash 6)))
3588 (should (= third (python-info-beginning-of-backslash 7)))
3589 (should (= third (python-info-beginning-of-backslash 8)))
3590 (should (= third (python-info-beginning-of-backslash 9)))
3591 (should (not (python-info-beginning-of-backslash 10))))))
3593 (ert-deftest python-info-continuation-line-p-1 ()
3594 (python-tests-with-temp-buffer
3596 if width == 0 and height == 0 and \\\\
3597 color == 'red' and emphasis == 'strong' or \\\\
3598 highlight > 100:
3599 raise ValueError(
3600 'sorry, you lose'
3604 (python-tests-look-at "if width == 0 and height == 0 and")
3605 (should (not (python-info-continuation-line-p)))
3606 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3607 (should (python-info-continuation-line-p))
3608 (python-tests-look-at "highlight > 100:")
3609 (should (python-info-continuation-line-p))
3610 (python-tests-look-at "raise ValueError(")
3611 (should (not (python-info-continuation-line-p)))
3612 (python-tests-look-at "'sorry, you lose'")
3613 (should (python-info-continuation-line-p))
3614 (forward-line 1)
3615 (should (python-info-continuation-line-p))
3616 (python-tests-look-at ")")
3617 (should (python-info-continuation-line-p))
3618 (forward-line 1)
3619 (should (not (python-info-continuation-line-p)))))
3621 (ert-deftest python-info-block-continuation-line-p-1 ()
3622 (python-tests-with-temp-buffer
3624 if width == 0 and height == 0 and \\\\
3625 color == 'red' and emphasis == 'strong' or \\\\
3626 highlight > 100:
3627 raise ValueError(
3628 'sorry, you lose'
3632 (python-tests-look-at "if width == 0 and")
3633 (should (not (python-info-block-continuation-line-p)))
3634 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3635 (should (= (python-info-block-continuation-line-p)
3636 (python-tests-look-at "if width == 0 and" -1 t)))
3637 (python-tests-look-at "highlight > 100:")
3638 (should (not (python-info-block-continuation-line-p)))))
3640 (ert-deftest python-info-block-continuation-line-p-2 ()
3641 (python-tests-with-temp-buffer
3643 def foo(a,
3646 pass
3648 (python-tests-look-at "def foo(a,")
3649 (should (not (python-info-block-continuation-line-p)))
3650 (python-tests-look-at "b,")
3651 (should (= (python-info-block-continuation-line-p)
3652 (python-tests-look-at "def foo(a," -1 t)))
3653 (python-tests-look-at "c):")
3654 (should (not (python-info-block-continuation-line-p)))))
3656 (ert-deftest python-info-assignment-continuation-line-p-1 ()
3657 (python-tests-with-temp-buffer
3659 data = foo(), bar() \\\\
3660 baz(), 4 \\\\
3661 5, 6
3663 (python-tests-look-at "data = foo(), bar()")
3664 (should (not (python-info-assignment-continuation-line-p)))
3665 (python-tests-look-at "baz(), 4")
3666 (should (= (python-info-assignment-continuation-line-p)
3667 (python-tests-look-at "foo()," -1 t)))
3668 (python-tests-look-at "5, 6")
3669 (should (not (python-info-assignment-continuation-line-p)))))
3671 (ert-deftest python-info-assignment-continuation-line-p-2 ()
3672 (python-tests-with-temp-buffer
3674 data = (foo(), bar()
3675 baz(), 4
3676 5, 6)
3678 (python-tests-look-at "data = (foo(), bar()")
3679 (should (not (python-info-assignment-continuation-line-p)))
3680 (python-tests-look-at "baz(), 4")
3681 (should (= (python-info-assignment-continuation-line-p)
3682 (python-tests-look-at "(foo()," -1 t)))
3683 (python-tests-look-at "5, 6)")
3684 (should (not (python-info-assignment-continuation-line-p)))))
3686 (ert-deftest python-info-looking-at-beginning-of-defun-1 ()
3687 (python-tests-with-temp-buffer
3689 def decorat0r(deff):
3690 '''decorates stuff.
3692 @decorat0r
3693 def foo(arg):
3696 def wrap():
3697 deff()
3698 return wwrap
3700 (python-tests-look-at "def decorat0r(deff):")
3701 (should (python-info-looking-at-beginning-of-defun))
3702 (python-tests-look-at "def foo(arg):")
3703 (should (not (python-info-looking-at-beginning-of-defun)))
3704 (python-tests-look-at "def wrap():")
3705 (should (python-info-looking-at-beginning-of-defun))
3706 (python-tests-look-at "deff()")
3707 (should (not (python-info-looking-at-beginning-of-defun)))))
3709 (ert-deftest python-info-current-line-comment-p-1 ()
3710 (python-tests-with-temp-buffer
3712 # this is a comment
3713 foo = True # another comment
3714 '#this is a string'
3715 if foo:
3716 # more comments
3717 print ('bar') # print bar
3719 (python-tests-look-at "# this is a comment")
3720 (should (python-info-current-line-comment-p))
3721 (python-tests-look-at "foo = True # another comment")
3722 (should (not (python-info-current-line-comment-p)))
3723 (python-tests-look-at "'#this is a string'")
3724 (should (not (python-info-current-line-comment-p)))
3725 (python-tests-look-at "# more comments")
3726 (should (python-info-current-line-comment-p))
3727 (python-tests-look-at "print ('bar') # print bar")
3728 (should (not (python-info-current-line-comment-p)))))
3730 (ert-deftest python-info-current-line-empty-p ()
3731 (python-tests-with-temp-buffer
3733 # this is a comment
3735 foo = True # another comment
3737 (should (python-info-current-line-empty-p))
3738 (python-tests-look-at "# this is a comment")
3739 (should (not (python-info-current-line-empty-p)))
3740 (forward-line 1)
3741 (should (python-info-current-line-empty-p))))
3744 ;;; Utility functions
3746 (ert-deftest python-util-goto-line-1 ()
3747 (python-tests-with-temp-buffer
3748 (concat
3749 "# a comment
3750 # another comment
3751 def foo(a, b, c):
3752 pass" (make-string 20 ?\n))
3753 (python-util-goto-line 10)
3754 (should (= (line-number-at-pos) 10))
3755 (python-util-goto-line 20)
3756 (should (= (line-number-at-pos) 20))))
3758 (ert-deftest python-util-clone-local-variables-1 ()
3759 (let ((buffer (generate-new-buffer
3760 "python-util-clone-local-variables-1"))
3761 (varcons
3762 '((python-fill-docstring-style . django)
3763 (python-shell-interpreter . "python")
3764 (python-shell-interpreter-args . "manage.py shell")
3765 (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
3766 (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
3767 (python-shell-extra-pythonpaths "/home/user/pylib/")
3768 (python-shell-completion-setup-code
3769 . "from IPython.core.completerlib import module_completion")
3770 (python-shell-completion-string-code
3771 . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
3772 (python-shell-virtualenv-path
3773 . "/home/user/.virtualenvs/project"))))
3774 (with-current-buffer buffer
3775 (kill-all-local-variables)
3776 (dolist (ccons varcons)
3777 (set (make-local-variable (car ccons)) (cdr ccons))))
3778 (python-tests-with-temp-buffer
3780 (python-util-clone-local-variables buffer)
3781 (dolist (ccons varcons)
3782 (should
3783 (equal (symbol-value (car ccons)) (cdr ccons)))))
3784 (kill-buffer buffer)))
3786 (ert-deftest python-util-strip-string-1 ()
3787 (should (string= (python-util-strip-string "\t\r\n str") "str"))
3788 (should (string= (python-util-strip-string "str \n\r") "str"))
3789 (should (string= (python-util-strip-string "\t\r\n str \n\r ") "str"))
3790 (should
3791 (string= (python-util-strip-string "\n str \nin \tg \n\r") "str \nin \tg"))
3792 (should (string= (python-util-strip-string "\n \t \n\r ") ""))
3793 (should (string= (python-util-strip-string "") "")))
3795 (ert-deftest python-util-forward-comment-1 ()
3796 (python-tests-with-temp-buffer
3797 (concat
3798 "# a comment
3799 # another comment
3800 # bad indented comment
3801 # more comments" (make-string 9999 ?\n))
3802 (python-util-forward-comment 1)
3803 (should (= (point) (point-max)))
3804 (python-util-forward-comment -1)
3805 (should (= (point) (point-min)))))
3807 (ert-deftest python-util-valid-regexp-p-1 ()
3808 (should (python-util-valid-regexp-p ""))
3809 (should (python-util-valid-regexp-p python-shell-prompt-regexp))
3810 (should (not (python-util-valid-regexp-p "\\("))))
3813 ;;; Electricity
3815 (ert-deftest python-parens-electric-indent-1 ()
3816 (require 'electric)
3817 (let ((eim electric-indent-mode))
3818 (unwind-protect
3819 (progn
3820 (python-tests-with-temp-buffer
3822 from django.conf.urls import patterns, include, url
3824 from django.contrib import admin
3826 from myapp import views
3829 urlpatterns = patterns('',
3830 url(r'^$', views.index
3833 (electric-indent-mode 1)
3834 (python-tests-look-at "views.index")
3835 (end-of-line)
3837 ;; Inserting commas within the same line should leave
3838 ;; indentation unchanged.
3839 (python-tests-self-insert ",")
3840 (should (= (current-indentation) 4))
3842 ;; As well as any other input happening within the same
3843 ;; set of parens.
3844 (python-tests-self-insert " name='index')")
3845 (should (= (current-indentation) 4))
3847 ;; But a comma outside it, should trigger indentation.
3848 (python-tests-self-insert ",")
3849 (should (= (current-indentation) 23))
3851 ;; Newline indents to the first argument column
3852 (python-tests-self-insert "\n")
3853 (should (= (current-indentation) 23))
3855 ;; All this input must not change indentation
3856 (indent-line-to 4)
3857 (python-tests-self-insert "url(r'^/login$', views.login)")
3858 (should (= (current-indentation) 4))
3860 ;; But this comma does
3861 (python-tests-self-insert ",")
3862 (should (= (current-indentation) 23))))
3863 (or eim (electric-indent-mode -1)))))
3865 (ert-deftest python-triple-quote-pairing ()
3866 (require 'electric)
3867 (let ((epm electric-pair-mode))
3868 (unwind-protect
3869 (progn
3870 (python-tests-with-temp-buffer
3871 "\"\"\n"
3872 (or epm (electric-pair-mode 1))
3873 (goto-char (1- (point-max)))
3874 (python-tests-self-insert ?\")
3875 (should (string= (buffer-string)
3876 "\"\"\"\"\"\"\n"))
3877 (should (= (point) 4)))
3878 (python-tests-with-temp-buffer
3879 "\n"
3880 (python-tests-self-insert (list ?\" ?\" ?\"))
3881 (should (string= (buffer-string)
3882 "\"\"\"\"\"\"\n"))
3883 (should (= (point) 4)))
3884 (python-tests-with-temp-buffer
3885 "\"\n\"\"\n"
3886 (goto-char (1- (point-max)))
3887 (python-tests-self-insert ?\")
3888 (should (= (point) (1- (point-max))))
3889 (should (string= (buffer-string)
3890 "\"\n\"\"\"\n"))))
3891 (or epm (electric-pair-mode -1)))))
3894 (provide 'python-tests)
3896 ;; Local Variables:
3897 ;; coding: utf-8
3898 ;; indent-tabs-mode: nil
3899 ;; End:
3901 ;;; python-tests.el ends here