python.el: Native readline completion.
[emacs.git] / test / automated / python-tests.el
blobca43c45ac5ecb9ca8fdc48a55647bd92650167c1
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-electric-colon-2 ()
744 "Test indentation case for dedenter."
745 (python-tests-with-temp-buffer
747 if do:
748 something()
749 else
751 (python-tests-look-at "else")
752 (goto-char (line-end-position))
753 (python-tests-self-insert ":")
754 (should (= (current-indentation) 0))))
756 (ert-deftest python-indent-electric-colon-3 ()
757 "Test indentation case for multi-line dedenter."
758 (python-tests-with-temp-buffer
760 if do:
761 something()
762 elif (this
764 that)
766 (python-tests-look-at "that)")
767 (goto-char (line-end-position))
768 (python-tests-self-insert ":")
769 (python-tests-look-at "elif" -1)
770 (should (= (current-indentation) 0))
771 (python-tests-look-at "and")
772 (should (= (current-indentation) 6))
773 (python-tests-look-at "that)")
774 (should (= (current-indentation) 6))))
776 (ert-deftest python-indent-region-1 ()
777 "Test indentation case from Bug#18843."
778 (let ((contents "
779 def foo ():
780 try:
781 pass
782 except:
783 pass
785 (python-tests-with-temp-buffer
786 contents
787 (python-indent-region (point-min) (point-max))
788 (should (string= (buffer-substring-no-properties (point-min) (point-max))
789 contents)))))
791 (ert-deftest python-indent-region-2 ()
792 "Test region indentation on comments."
793 (let ((contents "
794 def f():
795 if True:
796 pass
798 # This is
799 # some multiline
800 # comment
802 (python-tests-with-temp-buffer
803 contents
804 (python-indent-region (point-min) (point-max))
805 (should (string= (buffer-substring-no-properties (point-min) (point-max))
806 contents)))))
808 (ert-deftest python-indent-region-3 ()
809 "Test region indentation on comments."
810 (let ((contents "
811 def f():
812 if True:
813 pass
814 # This is
815 # some multiline
816 # comment
818 (expected "
819 def f():
820 if True:
821 pass
822 # This is
823 # some multiline
824 # comment
826 (python-tests-with-temp-buffer
827 contents
828 (python-indent-region (point-min) (point-max))
829 (should (string= (buffer-substring-no-properties (point-min) (point-max))
830 expected)))))
832 (ert-deftest python-indent-region-4 ()
833 "Test region indentation block starts, dedenters and enders."
834 (let ((contents "
835 def f():
836 if True:
837 a = 5
838 else:
839 a = 10
840 return a
842 (expected "
843 def f():
844 if True:
845 a = 5
846 else:
847 a = 10
848 return a
850 (python-tests-with-temp-buffer
851 contents
852 (python-indent-region (point-min) (point-max))
853 (should (string= (buffer-substring-no-properties (point-min) (point-max))
854 expected)))))
856 (ert-deftest python-indent-region-5 ()
857 "Test region indentation leaves strings untouched (start delimiter)."
858 (let ((contents "
859 def f():
861 this is
862 a multiline
863 string
866 (expected "
867 def f():
869 this is
870 a multiline
871 string
874 (python-tests-with-temp-buffer
875 contents
876 (python-indent-region (point-min) (point-max))
877 (should (string= (buffer-substring-no-properties (point-min) (point-max))
878 expected)))))
881 ;;; Navigation
883 (ert-deftest python-nav-beginning-of-defun-1 ()
884 (python-tests-with-temp-buffer
886 def decoratorFunctionWithArguments(arg1, arg2, arg3):
887 '''print decorated function call data to stdout.
889 Usage:
891 @decoratorFunctionWithArguments('arg1', 'arg2')
892 def func(a, b, c=True):
893 pass
896 def wwrap(f):
897 print 'Inside wwrap()'
898 def wrapped_f(*args):
899 print 'Inside wrapped_f()'
900 print 'Decorator arguments:', arg1, arg2, arg3
901 f(*args)
902 print 'After f(*args)'
903 return wrapped_f
904 return wwrap
906 (python-tests-look-at "return wrap")
907 (should (= (save-excursion
908 (python-nav-beginning-of-defun)
909 (point))
910 (save-excursion
911 (python-tests-look-at "def wrapped_f(*args):" -1)
912 (beginning-of-line)
913 (point))))
914 (python-tests-look-at "def wrapped_f(*args):" -1)
915 (should (= (save-excursion
916 (python-nav-beginning-of-defun)
917 (point))
918 (save-excursion
919 (python-tests-look-at "def wwrap(f):" -1)
920 (beginning-of-line)
921 (point))))
922 (python-tests-look-at "def wwrap(f):" -1)
923 (should (= (save-excursion
924 (python-nav-beginning-of-defun)
925 (point))
926 (save-excursion
927 (python-tests-look-at "def decoratorFunctionWithArguments" -1)
928 (beginning-of-line)
929 (point))))))
931 (ert-deftest python-nav-beginning-of-defun-2 ()
932 (python-tests-with-temp-buffer
934 class C(object):
936 def m(self):
937 self.c()
939 def b():
940 pass
942 def a():
943 pass
945 def c(self):
946 pass
948 ;; Nested defuns, are handled with care.
949 (python-tests-look-at "def c(self):")
950 (should (= (save-excursion
951 (python-nav-beginning-of-defun)
952 (point))
953 (save-excursion
954 (python-tests-look-at "def m(self):" -1)
955 (beginning-of-line)
956 (point))))
957 ;; Defuns on same levels should be respected.
958 (python-tests-look-at "def a():" -1)
959 (should (= (save-excursion
960 (python-nav-beginning-of-defun)
961 (point))
962 (save-excursion
963 (python-tests-look-at "def b():" -1)
964 (beginning-of-line)
965 (point))))
966 ;; Jump to a top level defun.
967 (python-tests-look-at "def b():" -1)
968 (should (= (save-excursion
969 (python-nav-beginning-of-defun)
970 (point))
971 (save-excursion
972 (python-tests-look-at "def m(self):" -1)
973 (beginning-of-line)
974 (point))))
975 ;; Jump to a top level defun again.
976 (python-tests-look-at "def m(self):" -1)
977 (should (= (save-excursion
978 (python-nav-beginning-of-defun)
979 (point))
980 (save-excursion
981 (python-tests-look-at "class C(object):" -1)
982 (beginning-of-line)
983 (point))))))
985 (ert-deftest python-nav-end-of-defun-1 ()
986 (python-tests-with-temp-buffer
988 class C(object):
990 def m(self):
991 self.c()
993 def b():
994 pass
996 def a():
997 pass
999 def c(self):
1000 pass
1002 (should (= (save-excursion
1003 (python-tests-look-at "class C(object):")
1004 (python-nav-end-of-defun)
1005 (point))
1006 (save-excursion
1007 (point-max))))
1008 (should (= (save-excursion
1009 (python-tests-look-at "def m(self):")
1010 (python-nav-end-of-defun)
1011 (point))
1012 (save-excursion
1013 (python-tests-look-at "def c(self):")
1014 (forward-line -1)
1015 (point))))
1016 (should (= (save-excursion
1017 (python-tests-look-at "def b():")
1018 (python-nav-end-of-defun)
1019 (point))
1020 (save-excursion
1021 (python-tests-look-at "def b():")
1022 (forward-line 2)
1023 (point))))
1024 (should (= (save-excursion
1025 (python-tests-look-at "def c(self):")
1026 (python-nav-end-of-defun)
1027 (point))
1028 (save-excursion
1029 (point-max))))))
1031 (ert-deftest python-nav-end-of-defun-2 ()
1032 (python-tests-with-temp-buffer
1034 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1035 '''print decorated function call data to stdout.
1037 Usage:
1039 @decoratorFunctionWithArguments('arg1', 'arg2')
1040 def func(a, b, c=True):
1041 pass
1044 def wwrap(f):
1045 print 'Inside wwrap()'
1046 def wrapped_f(*args):
1047 print 'Inside wrapped_f()'
1048 print 'Decorator arguments:', arg1, arg2, arg3
1049 f(*args)
1050 print 'After f(*args)'
1051 return wrapped_f
1052 return wwrap
1054 (should (= (save-excursion
1055 (python-tests-look-at "def decoratorFunctionWithArguments")
1056 (python-nav-end-of-defun)
1057 (point))
1058 (save-excursion
1059 (point-max))))
1060 (should (= (save-excursion
1061 (python-tests-look-at "@decoratorFunctionWithArguments")
1062 (python-nav-end-of-defun)
1063 (point))
1064 (save-excursion
1065 (point-max))))
1066 (should (= (save-excursion
1067 (python-tests-look-at "def wwrap(f):")
1068 (python-nav-end-of-defun)
1069 (point))
1070 (save-excursion
1071 (python-tests-look-at "return wwrap")
1072 (line-beginning-position))))
1073 (should (= (save-excursion
1074 (python-tests-look-at "def wrapped_f(*args):")
1075 (python-nav-end-of-defun)
1076 (point))
1077 (save-excursion
1078 (python-tests-look-at "return wrapped_f")
1079 (line-beginning-position))))
1080 (should (= (save-excursion
1081 (python-tests-look-at "f(*args)")
1082 (python-nav-end-of-defun)
1083 (point))
1084 (save-excursion
1085 (python-tests-look-at "return wrapped_f")
1086 (line-beginning-position))))))
1088 (ert-deftest python-nav-backward-defun-1 ()
1089 (python-tests-with-temp-buffer
1091 class A(object): # A
1093 def a(self): # a
1094 pass
1096 def b(self): # b
1097 pass
1099 class B(object): # B
1101 class C(object): # C
1103 def d(self): # d
1104 pass
1106 # def e(self): # e
1107 # pass
1109 def c(self): # c
1110 pass
1112 # def d(self): # d
1113 # pass
1115 (goto-char (point-max))
1116 (should (= (save-excursion (python-nav-backward-defun))
1117 (python-tests-look-at " def c(self): # c" -1)))
1118 (should (= (save-excursion (python-nav-backward-defun))
1119 (python-tests-look-at " def d(self): # d" -1)))
1120 (should (= (save-excursion (python-nav-backward-defun))
1121 (python-tests-look-at " class C(object): # C" -1)))
1122 (should (= (save-excursion (python-nav-backward-defun))
1123 (python-tests-look-at " class B(object): # B" -1)))
1124 (should (= (save-excursion (python-nav-backward-defun))
1125 (python-tests-look-at " def b(self): # b" -1)))
1126 (should (= (save-excursion (python-nav-backward-defun))
1127 (python-tests-look-at " def a(self): # a" -1)))
1128 (should (= (save-excursion (python-nav-backward-defun))
1129 (python-tests-look-at "class A(object): # A" -1)))
1130 (should (not (python-nav-backward-defun)))))
1132 (ert-deftest python-nav-backward-defun-2 ()
1133 (python-tests-with-temp-buffer
1135 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1136 '''print decorated function call data to stdout.
1138 Usage:
1140 @decoratorFunctionWithArguments('arg1', 'arg2')
1141 def func(a, b, c=True):
1142 pass
1145 def wwrap(f):
1146 print 'Inside wwrap()'
1147 def wrapped_f(*args):
1148 print 'Inside wrapped_f()'
1149 print 'Decorator arguments:', arg1, arg2, arg3
1150 f(*args)
1151 print 'After f(*args)'
1152 return wrapped_f
1153 return wwrap
1155 (goto-char (point-max))
1156 (should (= (save-excursion (python-nav-backward-defun))
1157 (python-tests-look-at " def wrapped_f(*args):" -1)))
1158 (should (= (save-excursion (python-nav-backward-defun))
1159 (python-tests-look-at " def wwrap(f):" -1)))
1160 (should (= (save-excursion (python-nav-backward-defun))
1161 (python-tests-look-at "def decoratorFunctionWithArguments(arg1, arg2, arg3):" -1)))
1162 (should (not (python-nav-backward-defun)))))
1164 (ert-deftest python-nav-backward-defun-3 ()
1165 (python-tests-with-temp-buffer
1168 def u(self):
1169 pass
1171 def v(self):
1172 pass
1174 def w(self):
1175 pass
1178 class A(object):
1179 pass
1181 (goto-char (point-min))
1182 (let ((point (python-tests-look-at "class A(object):")))
1183 (should (not (python-nav-backward-defun)))
1184 (should (= point (point))))))
1186 (ert-deftest python-nav-forward-defun-1 ()
1187 (python-tests-with-temp-buffer
1189 class A(object): # A
1191 def a(self): # a
1192 pass
1194 def b(self): # b
1195 pass
1197 class B(object): # B
1199 class C(object): # C
1201 def d(self): # d
1202 pass
1204 # def e(self): # e
1205 # pass
1207 def c(self): # c
1208 pass
1210 # def d(self): # d
1211 # pass
1213 (goto-char (point-min))
1214 (should (= (save-excursion (python-nav-forward-defun))
1215 (python-tests-look-at "(object): # A")))
1216 (should (= (save-excursion (python-nav-forward-defun))
1217 (python-tests-look-at "(self): # a")))
1218 (should (= (save-excursion (python-nav-forward-defun))
1219 (python-tests-look-at "(self): # b")))
1220 (should (= (save-excursion (python-nav-forward-defun))
1221 (python-tests-look-at "(object): # B")))
1222 (should (= (save-excursion (python-nav-forward-defun))
1223 (python-tests-look-at "(object): # C")))
1224 (should (= (save-excursion (python-nav-forward-defun))
1225 (python-tests-look-at "(self): # d")))
1226 (should (= (save-excursion (python-nav-forward-defun))
1227 (python-tests-look-at "(self): # c")))
1228 (should (not (python-nav-forward-defun)))))
1230 (ert-deftest python-nav-forward-defun-2 ()
1231 (python-tests-with-temp-buffer
1233 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1234 '''print decorated function call data to stdout.
1236 Usage:
1238 @decoratorFunctionWithArguments('arg1', 'arg2')
1239 def func(a, b, c=True):
1240 pass
1243 def wwrap(f):
1244 print 'Inside wwrap()'
1245 def wrapped_f(*args):
1246 print 'Inside wrapped_f()'
1247 print 'Decorator arguments:', arg1, arg2, arg3
1248 f(*args)
1249 print 'After f(*args)'
1250 return wrapped_f
1251 return wwrap
1253 (goto-char (point-min))
1254 (should (= (save-excursion (python-nav-forward-defun))
1255 (python-tests-look-at "(arg1, arg2, arg3):")))
1256 (should (= (save-excursion (python-nav-forward-defun))
1257 (python-tests-look-at "(f):")))
1258 (should (= (save-excursion (python-nav-forward-defun))
1259 (python-tests-look-at "(*args):")))
1260 (should (not (python-nav-forward-defun)))))
1262 (ert-deftest python-nav-forward-defun-3 ()
1263 (python-tests-with-temp-buffer
1265 class A(object):
1266 pass
1269 def u(self):
1270 pass
1272 def v(self):
1273 pass
1275 def w(self):
1276 pass
1279 (goto-char (point-min))
1280 (let ((point (python-tests-look-at "(object):")))
1281 (should (not (python-nav-forward-defun)))
1282 (should (= point (point))))))
1284 (ert-deftest python-nav-beginning-of-statement-1 ()
1285 (python-tests-with-temp-buffer
1287 v1 = 123 + \
1288 456 + \
1290 v2 = (value1,
1291 value2,
1293 value3,
1294 value4)
1295 v3 = ('this is a string'
1297 'that is continued'
1298 'between lines'
1299 'within a paren',
1300 # this is a comment, yo
1301 'continue previous line')
1302 v4 = '''
1303 a very long
1304 string
1307 (python-tests-look-at "v2 =")
1308 (python-util-forward-comment -1)
1309 (should (= (save-excursion
1310 (python-nav-beginning-of-statement)
1311 (point))
1312 (python-tests-look-at "v1 =" -1 t)))
1313 (python-tests-look-at "v3 =")
1314 (python-util-forward-comment -1)
1315 (should (= (save-excursion
1316 (python-nav-beginning-of-statement)
1317 (point))
1318 (python-tests-look-at "v2 =" -1 t)))
1319 (python-tests-look-at "v4 =")
1320 (python-util-forward-comment -1)
1321 (should (= (save-excursion
1322 (python-nav-beginning-of-statement)
1323 (point))
1324 (python-tests-look-at "v3 =" -1 t)))
1325 (goto-char (point-max))
1326 (python-util-forward-comment -1)
1327 (should (= (save-excursion
1328 (python-nav-beginning-of-statement)
1329 (point))
1330 (python-tests-look-at "v4 =" -1 t)))))
1332 (ert-deftest python-nav-end-of-statement-1 ()
1333 (python-tests-with-temp-buffer
1335 v1 = 123 + \
1336 456 + \
1338 v2 = (value1,
1339 value2,
1341 value3,
1342 value4)
1343 v3 = ('this is a string'
1345 'that is continued'
1346 'between lines'
1347 'within a paren',
1348 # this is a comment, yo
1349 'continue previous line')
1350 v4 = '''
1351 a very long
1352 string
1355 (python-tests-look-at "v1 =")
1356 (should (= (save-excursion
1357 (python-nav-end-of-statement)
1358 (point))
1359 (save-excursion
1360 (python-tests-look-at "789")
1361 (line-end-position))))
1362 (python-tests-look-at "v2 =")
1363 (should (= (save-excursion
1364 (python-nav-end-of-statement)
1365 (point))
1366 (save-excursion
1367 (python-tests-look-at "value4)")
1368 (line-end-position))))
1369 (python-tests-look-at "v3 =")
1370 (should (= (save-excursion
1371 (python-nav-end-of-statement)
1372 (point))
1373 (save-excursion
1374 (python-tests-look-at
1375 "'continue previous line')")
1376 (line-end-position))))
1377 (python-tests-look-at "v4 =")
1378 (should (= (save-excursion
1379 (python-nav-end-of-statement)
1380 (point))
1381 (save-excursion
1382 (goto-char (point-max))
1383 (python-util-forward-comment -1)
1384 (point))))))
1386 (ert-deftest python-nav-forward-statement-1 ()
1387 (python-tests-with-temp-buffer
1389 v1 = 123 + \
1390 456 + \
1392 v2 = (value1,
1393 value2,
1395 value3,
1396 value4)
1397 v3 = ('this is a string'
1399 'that is continued'
1400 'between lines'
1401 'within a paren',
1402 # this is a comment, yo
1403 'continue previous line')
1404 v4 = '''
1405 a very long
1406 string
1409 (python-tests-look-at "v1 =")
1410 (should (= (save-excursion
1411 (python-nav-forward-statement)
1412 (point))
1413 (python-tests-look-at "v2 =")))
1414 (should (= (save-excursion
1415 (python-nav-forward-statement)
1416 (point))
1417 (python-tests-look-at "v3 =")))
1418 (should (= (save-excursion
1419 (python-nav-forward-statement)
1420 (point))
1421 (python-tests-look-at "v4 =")))
1422 (should (= (save-excursion
1423 (python-nav-forward-statement)
1424 (point))
1425 (point-max)))))
1427 (ert-deftest python-nav-backward-statement-1 ()
1428 (python-tests-with-temp-buffer
1430 v1 = 123 + \
1431 456 + \
1433 v2 = (value1,
1434 value2,
1436 value3,
1437 value4)
1438 v3 = ('this is a string'
1440 'that is continued'
1441 'between lines'
1442 'within a paren',
1443 # this is a comment, yo
1444 'continue previous line')
1445 v4 = '''
1446 a very long
1447 string
1450 (goto-char (point-max))
1451 (should (= (save-excursion
1452 (python-nav-backward-statement)
1453 (point))
1454 (python-tests-look-at "v4 =" -1)))
1455 (should (= (save-excursion
1456 (python-nav-backward-statement)
1457 (point))
1458 (python-tests-look-at "v3 =" -1)))
1459 (should (= (save-excursion
1460 (python-nav-backward-statement)
1461 (point))
1462 (python-tests-look-at "v2 =" -1)))
1463 (should (= (save-excursion
1464 (python-nav-backward-statement)
1465 (point))
1466 (python-tests-look-at "v1 =" -1)))))
1468 (ert-deftest python-nav-backward-statement-2 ()
1469 :expected-result :failed
1470 (python-tests-with-temp-buffer
1472 v1 = 123 + \
1473 456 + \
1475 v2 = (value1,
1476 value2,
1478 value3,
1479 value4)
1481 ;; FIXME: For some reason `python-nav-backward-statement' is moving
1482 ;; back two sentences when starting from 'value4)'.
1483 (goto-char (point-max))
1484 (python-util-forward-comment -1)
1485 (should (= (save-excursion
1486 (python-nav-backward-statement)
1487 (point))
1488 (python-tests-look-at "v2 =" -1 t)))))
1490 (ert-deftest python-nav-beginning-of-block-1 ()
1491 (python-tests-with-temp-buffer
1493 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1494 '''print decorated function call data to stdout.
1496 Usage:
1498 @decoratorFunctionWithArguments('arg1', 'arg2')
1499 def func(a, b, c=True):
1500 pass
1503 def wwrap(f):
1504 print 'Inside wwrap()'
1505 def wrapped_f(*args):
1506 print 'Inside wrapped_f()'
1507 print 'Decorator arguments:', arg1, arg2, arg3
1508 f(*args)
1509 print 'After f(*args)'
1510 return wrapped_f
1511 return wwrap
1513 (python-tests-look-at "return wwrap")
1514 (should (= (save-excursion
1515 (python-nav-beginning-of-block)
1516 (point))
1517 (python-tests-look-at "def decoratorFunctionWithArguments" -1)))
1518 (python-tests-look-at "print 'Inside wwrap()'")
1519 (should (= (save-excursion
1520 (python-nav-beginning-of-block)
1521 (point))
1522 (python-tests-look-at "def wwrap(f):" -1)))
1523 (python-tests-look-at "print 'After f(*args)'")
1524 (end-of-line)
1525 (should (= (save-excursion
1526 (python-nav-beginning-of-block)
1527 (point))
1528 (python-tests-look-at "def wrapped_f(*args):" -1)))
1529 (python-tests-look-at "return wrapped_f")
1530 (should (= (save-excursion
1531 (python-nav-beginning-of-block)
1532 (point))
1533 (python-tests-look-at "def wwrap(f):" -1)))))
1535 (ert-deftest python-nav-end-of-block-1 ()
1536 (python-tests-with-temp-buffer
1538 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1539 '''print decorated function call data to stdout.
1541 Usage:
1543 @decoratorFunctionWithArguments('arg1', 'arg2')
1544 def func(a, b, c=True):
1545 pass
1548 def wwrap(f):
1549 print 'Inside wwrap()'
1550 def wrapped_f(*args):
1551 print 'Inside wrapped_f()'
1552 print 'Decorator arguments:', arg1, arg2, arg3
1553 f(*args)
1554 print 'After f(*args)'
1555 return wrapped_f
1556 return wwrap
1558 (python-tests-look-at "def decoratorFunctionWithArguments")
1559 (should (= (save-excursion
1560 (python-nav-end-of-block)
1561 (point))
1562 (save-excursion
1563 (goto-char (point-max))
1564 (python-util-forward-comment -1)
1565 (point))))
1566 (python-tests-look-at "def wwrap(f):")
1567 (should (= (save-excursion
1568 (python-nav-end-of-block)
1569 (point))
1570 (save-excursion
1571 (python-tests-look-at "return wrapped_f")
1572 (line-end-position))))
1573 (end-of-line)
1574 (should (= (save-excursion
1575 (python-nav-end-of-block)
1576 (point))
1577 (save-excursion
1578 (python-tests-look-at "return wrapped_f")
1579 (line-end-position))))
1580 (python-tests-look-at "f(*args)")
1581 (should (= (save-excursion
1582 (python-nav-end-of-block)
1583 (point))
1584 (save-excursion
1585 (python-tests-look-at "print 'After f(*args)'")
1586 (line-end-position))))))
1588 (ert-deftest python-nav-forward-block-1 ()
1589 "This also accounts as a test for `python-nav-backward-block'."
1590 (python-tests-with-temp-buffer
1592 if request.user.is_authenticated():
1593 # def block():
1594 # pass
1595 try:
1596 profile = request.user.get_profile()
1597 except Profile.DoesNotExist:
1598 profile = Profile.objects.create(user=request.user)
1599 else:
1600 if profile.stats:
1601 profile.recalculate_stats()
1602 else:
1603 profile.clear_stats()
1604 finally:
1605 profile.views += 1
1606 profile.save()
1608 (should (= (save-excursion (python-nav-forward-block))
1609 (python-tests-look-at "if request.user.is_authenticated():")))
1610 (should (= (save-excursion (python-nav-forward-block))
1611 (python-tests-look-at "try:")))
1612 (should (= (save-excursion (python-nav-forward-block))
1613 (python-tests-look-at "except Profile.DoesNotExist:")))
1614 (should (= (save-excursion (python-nav-forward-block))
1615 (python-tests-look-at "else:")))
1616 (should (= (save-excursion (python-nav-forward-block))
1617 (python-tests-look-at "if profile.stats:")))
1618 (should (= (save-excursion (python-nav-forward-block))
1619 (python-tests-look-at "else:")))
1620 (should (= (save-excursion (python-nav-forward-block))
1621 (python-tests-look-at "finally:")))
1622 ;; When point is at the last block, leave it there and return nil
1623 (should (not (save-excursion (python-nav-forward-block))))
1624 ;; Move backwards, and even if the number of moves is less than the
1625 ;; provided argument return the point.
1626 (should (= (save-excursion (python-nav-forward-block -10))
1627 (python-tests-look-at
1628 "if request.user.is_authenticated():" -1)))))
1630 (ert-deftest python-nav-forward-sexp-1 ()
1631 (python-tests-with-temp-buffer
1637 (python-tests-look-at "a()")
1638 (python-nav-forward-sexp)
1639 (should (looking-at "$"))
1640 (should (save-excursion
1641 (beginning-of-line)
1642 (looking-at "a()")))
1643 (python-nav-forward-sexp)
1644 (should (looking-at "$"))
1645 (should (save-excursion
1646 (beginning-of-line)
1647 (looking-at "b()")))
1648 (python-nav-forward-sexp)
1649 (should (looking-at "$"))
1650 (should (save-excursion
1651 (beginning-of-line)
1652 (looking-at "c()")))
1653 ;; Movement next to a paren should do what lisp does and
1654 ;; unfortunately It can't change, because otherwise
1655 ;; `blink-matching-open' breaks.
1656 (python-nav-forward-sexp -1)
1657 (should (looking-at "()"))
1658 (should (save-excursion
1659 (beginning-of-line)
1660 (looking-at "c()")))
1661 (python-nav-forward-sexp -1)
1662 (should (looking-at "c()"))
1663 (python-nav-forward-sexp -1)
1664 (should (looking-at "b()"))
1665 (python-nav-forward-sexp -1)
1666 (should (looking-at "a()"))))
1668 (ert-deftest python-nav-forward-sexp-2 ()
1669 (python-tests-with-temp-buffer
1671 def func():
1672 if True:
1673 aaa = bbb
1674 ccc = ddd
1675 eee = fff
1676 return ggg
1678 (python-tests-look-at "aa =")
1679 (python-nav-forward-sexp)
1680 (should (looking-at " = bbb"))
1681 (python-nav-forward-sexp)
1682 (should (looking-at "$"))
1683 (should (save-excursion
1684 (back-to-indentation)
1685 (looking-at "aaa = bbb")))
1686 (python-nav-forward-sexp)
1687 (should (looking-at "$"))
1688 (should (save-excursion
1689 (back-to-indentation)
1690 (looking-at "ccc = ddd")))
1691 (python-nav-forward-sexp)
1692 (should (looking-at "$"))
1693 (should (save-excursion
1694 (back-to-indentation)
1695 (looking-at "eee = fff")))
1696 (python-nav-forward-sexp)
1697 (should (looking-at "$"))
1698 (should (save-excursion
1699 (back-to-indentation)
1700 (looking-at "return ggg")))
1701 (python-nav-forward-sexp -1)
1702 (should (looking-at "def func():"))))
1704 (ert-deftest python-nav-forward-sexp-3 ()
1705 (python-tests-with-temp-buffer
1707 from some_module import some_sub_module
1708 from another_module import another_sub_module
1710 def another_statement():
1711 pass
1713 (python-tests-look-at "some_module")
1714 (python-nav-forward-sexp)
1715 (should (looking-at " import"))
1716 (python-nav-forward-sexp)
1717 (should (looking-at " some_sub_module"))
1718 (python-nav-forward-sexp)
1719 (should (looking-at "$"))
1720 (should
1721 (save-excursion
1722 (back-to-indentation)
1723 (looking-at
1724 "from some_module import some_sub_module")))
1725 (python-nav-forward-sexp)
1726 (should (looking-at "$"))
1727 (should
1728 (save-excursion
1729 (back-to-indentation)
1730 (looking-at
1731 "from another_module import another_sub_module")))
1732 (python-nav-forward-sexp)
1733 (should (looking-at "$"))
1734 (should
1735 (save-excursion
1736 (back-to-indentation)
1737 (looking-at
1738 "pass")))
1739 (python-nav-forward-sexp -1)
1740 (should (looking-at "def another_statement():"))
1741 (python-nav-forward-sexp -1)
1742 (should (looking-at "from another_module import another_sub_module"))
1743 (python-nav-forward-sexp -1)
1744 (should (looking-at "from some_module import some_sub_module"))))
1746 (ert-deftest python-nav-forward-sexp-safe-1 ()
1747 (python-tests-with-temp-buffer
1749 profile = Profile.objects.create(user=request.user)
1750 profile.notify()
1752 (python-tests-look-at "profile =")
1753 (python-nav-forward-sexp-safe 1)
1754 (should (looking-at "$"))
1755 (beginning-of-line 1)
1756 (python-tests-look-at "user=request.user")
1757 (python-nav-forward-sexp-safe -1)
1758 (should (looking-at "(user=request.user)"))
1759 (python-nav-forward-sexp-safe -4)
1760 (should (looking-at "profile ="))
1761 (python-tests-look-at "user=request.user")
1762 (python-nav-forward-sexp-safe 3)
1763 (should (looking-at ")"))
1764 (python-nav-forward-sexp-safe 1)
1765 (should (looking-at "$"))
1766 (python-nav-forward-sexp-safe 1)
1767 (should (looking-at "$"))))
1769 (ert-deftest python-nav-up-list-1 ()
1770 (python-tests-with-temp-buffer
1772 def f():
1773 if True:
1774 return [i for i in range(3)]
1776 (python-tests-look-at "3)]")
1777 (python-nav-up-list)
1778 (should (looking-at "]"))
1779 (python-nav-up-list)
1780 (should (looking-at "$"))))
1782 (ert-deftest python-nav-backward-up-list-1 ()
1783 :expected-result :failed
1784 (python-tests-with-temp-buffer
1786 def f():
1787 if True:
1788 return [i for i in range(3)]
1790 (python-tests-look-at "3)]")
1791 (python-nav-backward-up-list)
1792 (should (looking-at "(3)\\]"))
1793 (python-nav-backward-up-list)
1794 (should (looking-at
1795 "\\[i for i in range(3)\\]"))
1796 ;; FIXME: Need to move to beginning-of-statement.
1797 (python-nav-backward-up-list)
1798 (should (looking-at
1799 "return \\[i for i in range(3)\\]"))
1800 (python-nav-backward-up-list)
1801 (should (looking-at "if True:"))
1802 (python-nav-backward-up-list)
1803 (should (looking-at "def f():"))))
1806 ;;; Shell integration
1808 (defvar python-tests-shell-interpreter "python")
1810 (ert-deftest python-shell-get-process-name-1 ()
1811 "Check process name calculation sans `buffer-file-name'."
1812 (python-tests-with-temp-buffer
1814 (should (string= (python-shell-get-process-name nil)
1815 python-shell-buffer-name))
1816 (should (string= (python-shell-get-process-name t)
1817 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
1819 (ert-deftest python-shell-get-process-name-2 ()
1820 "Check process name calculation with `buffer-file-name'."
1821 (python-tests-with-temp-file
1823 ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
1824 ;; should be respected.
1825 (should (string= (python-shell-get-process-name nil)
1826 python-shell-buffer-name))
1827 (should (string=
1828 (python-shell-get-process-name t)
1829 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
1831 (ert-deftest python-shell-internal-get-process-name-1 ()
1832 "Check the internal process name is buffer-unique sans `buffer-file-name'."
1833 (python-tests-with-temp-buffer
1835 (should (string= (python-shell-internal-get-process-name)
1836 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
1838 (ert-deftest python-shell-internal-get-process-name-2 ()
1839 "Check the internal process name is buffer-unique with `buffer-file-name'."
1840 (python-tests-with-temp-file
1842 (should (string= (python-shell-internal-get-process-name)
1843 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
1845 (ert-deftest python-shell-calculate-command-1 ()
1846 "Check the command to execute is calculated correctly.
1847 Using `python-shell-interpreter' and
1848 `python-shell-interpreter-args'."
1849 (skip-unless (executable-find python-tests-shell-interpreter))
1850 (let ((python-shell-interpreter (executable-find
1851 python-tests-shell-interpreter))
1852 (python-shell-interpreter-args "-B"))
1853 (should (string=
1854 (format "%s %s"
1855 python-shell-interpreter
1856 python-shell-interpreter-args)
1857 (python-shell-calculate-command)))))
1859 (ert-deftest python-shell-calculate-process-environment-1 ()
1860 "Test `python-shell-process-environment' modification."
1861 (let* ((python-shell-process-environment
1862 '("TESTVAR1=value1" "TESTVAR2=value2"))
1863 (process-environment
1864 (python-shell-calculate-process-environment)))
1865 (should (equal (getenv "TESTVAR1") "value1"))
1866 (should (equal (getenv "TESTVAR2") "value2"))))
1868 (ert-deftest python-shell-calculate-process-environment-2 ()
1869 "Test `python-shell-extra-pythonpaths' modification."
1870 (let* ((process-environment process-environment)
1871 (original-pythonpath (setenv "PYTHONPATH" "path3"))
1872 (paths '("path1" "path2"))
1873 (python-shell-extra-pythonpaths paths)
1874 (process-environment
1875 (python-shell-calculate-process-environment)))
1876 (should (equal (getenv "PYTHONPATH")
1877 (concat
1878 (mapconcat 'identity paths path-separator)
1879 path-separator original-pythonpath)))))
1881 (ert-deftest python-shell-calculate-process-environment-3 ()
1882 "Test `python-shell-virtualenv-root' modification."
1883 (let* ((original-path (or (getenv "PATH") ""))
1884 (python-shell-virtualenv-root
1885 (directory-file-name user-emacs-directory))
1886 (process-environment
1887 (python-shell-calculate-process-environment)))
1888 (should (not (getenv "PYTHONHOME")))
1889 (should (string= (getenv "VIRTUAL_ENV") python-shell-virtualenv-root))
1890 (should (equal (getenv "PATH")
1891 (format "%s/bin%s%s"
1892 python-shell-virtualenv-root
1893 path-separator original-path)))))
1895 (ert-deftest python-shell-calculate-process-environment-4 ()
1896 "Test `python-shell-unbuffered' modification."
1897 (setenv "PYTHONUNBUFFERED")
1898 (let* ((process-environment
1899 (python-shell-calculate-process-environment)))
1900 ;; Defaults to t
1901 (should python-shell-unbuffered)
1902 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
1904 (ert-deftest python-shell-calculate-process-environment-5 ()
1905 (setenv "PYTHONUNBUFFERED")
1906 "Test `python-shell-unbuffered' modification."
1907 (let* ((python-shell-unbuffered nil)
1908 (process-environment
1909 (python-shell-calculate-process-environment)))
1910 (should (not (getenv "PYTHONUNBUFFERED")))))
1912 (ert-deftest python-shell-calculate-exec-path-1 ()
1913 "Test `python-shell-exec-path' modification."
1914 (let* ((original-exec-path exec-path)
1915 (python-shell-exec-path '("path1" "path2"))
1916 (exec-path (python-shell-calculate-exec-path)))
1917 (should (equal
1918 exec-path
1919 (append python-shell-exec-path
1920 original-exec-path)))))
1922 (ert-deftest python-shell-calculate-exec-path-2 ()
1923 "Test `python-shell-exec-path' modification."
1924 (let* ((original-exec-path exec-path)
1925 (python-shell-virtualenv-root
1926 (directory-file-name (expand-file-name user-emacs-directory)))
1927 (exec-path (python-shell-calculate-exec-path)))
1928 (should (equal
1929 exec-path
1930 (append (cons
1931 (format "%s/bin" python-shell-virtualenv-root)
1932 original-exec-path))))))
1934 (ert-deftest python-shell-make-comint-1 ()
1935 "Check comint creation for global shell buffer."
1936 (skip-unless (executable-find python-tests-shell-interpreter))
1937 ;; The interpreter can get killed too quickly to allow it to clean
1938 ;; up the tempfiles that the default python-shell-setup-codes create,
1939 ;; so it leaves tempfiles behind, which is a minor irritation.
1940 (let* ((python-shell-setup-codes nil)
1941 (python-shell-interpreter
1942 (executable-find python-tests-shell-interpreter))
1943 (proc-name (python-shell-get-process-name nil))
1944 (shell-buffer
1945 (python-tests-with-temp-buffer
1946 "" (python-shell-make-comint
1947 (python-shell-calculate-command) proc-name)))
1948 (process (get-buffer-process shell-buffer)))
1949 (unwind-protect
1950 (progn
1951 (set-process-query-on-exit-flag process nil)
1952 (should (process-live-p process))
1953 (with-current-buffer shell-buffer
1954 (should (eq major-mode 'inferior-python-mode))
1955 (should (string= (buffer-name) (format "*%s*" proc-name)))))
1956 (kill-buffer shell-buffer))))
1958 (ert-deftest python-shell-make-comint-2 ()
1959 "Check comint creation for internal shell buffer."
1960 (skip-unless (executable-find python-tests-shell-interpreter))
1961 (let* ((python-shell-setup-codes nil)
1962 (python-shell-interpreter
1963 (executable-find python-tests-shell-interpreter))
1964 (proc-name (python-shell-internal-get-process-name))
1965 (shell-buffer
1966 (python-tests-with-temp-buffer
1967 "" (python-shell-make-comint
1968 (python-shell-calculate-command) proc-name nil t)))
1969 (process (get-buffer-process shell-buffer)))
1970 (unwind-protect
1971 (progn
1972 (set-process-query-on-exit-flag process nil)
1973 (should (process-live-p process))
1974 (with-current-buffer shell-buffer
1975 (should (eq major-mode 'inferior-python-mode))
1976 (should (string= (buffer-name) (format " *%s*" proc-name)))))
1977 (kill-buffer shell-buffer))))
1979 (ert-deftest python-shell-make-comint-3 ()
1980 "Check comint creation with overridden python interpreter and args.
1981 The command passed to `python-shell-make-comint' as argument must
1982 locally override global values set in `python-shell-interpreter'
1983 and `python-shell-interpreter-args' in the new shell buffer."
1984 (skip-unless (executable-find python-tests-shell-interpreter))
1985 (let* ((python-shell-setup-codes nil)
1986 (python-shell-interpreter "interpreter")
1987 (python-shell-interpreter-args "--some-args")
1988 (proc-name (python-shell-get-process-name nil))
1989 (interpreter-override
1990 (concat (executable-find python-tests-shell-interpreter) " " "-i"))
1991 (shell-buffer
1992 (python-tests-with-temp-buffer
1993 "" (python-shell-make-comint interpreter-override proc-name nil)))
1994 (process (get-buffer-process shell-buffer)))
1995 (unwind-protect
1996 (progn
1997 (set-process-query-on-exit-flag process nil)
1998 (should (process-live-p process))
1999 (with-current-buffer shell-buffer
2000 (should (eq major-mode 'inferior-python-mode))
2001 (should (file-equal-p
2002 python-shell-interpreter
2003 (executable-find python-tests-shell-interpreter)))
2004 (should (string= python-shell-interpreter-args "-i"))))
2005 (kill-buffer shell-buffer))))
2007 (ert-deftest python-shell-make-comint-4 ()
2008 "Check shell calculated prompts regexps are set."
2009 (skip-unless (executable-find python-tests-shell-interpreter))
2010 (let* ((process-environment process-environment)
2011 (python-shell-setup-codes nil)
2012 (python-shell-interpreter
2013 (executable-find python-tests-shell-interpreter))
2014 (python-shell-interpreter-args "-i")
2015 (python-shell--prompt-calculated-input-regexp nil)
2016 (python-shell--prompt-calculated-output-regexp nil)
2017 (python-shell-prompt-detect-enabled t)
2018 (python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2019 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2020 (python-shell-prompt-regexp "in")
2021 (python-shell-prompt-block-regexp "block")
2022 (python-shell-prompt-pdb-regexp "pdf")
2023 (python-shell-prompt-output-regexp "output")
2024 (startup-code (concat "import sys\n"
2025 "sys.ps1 = 'py> '\n"
2026 "sys.ps2 = '..> '\n"
2027 "sys.ps3 = 'out '\n"))
2028 (startup-file (python-shell--save-temp-file startup-code))
2029 (proc-name (python-shell-get-process-name nil))
2030 (shell-buffer
2031 (progn
2032 (setenv "PYTHONSTARTUP" startup-file)
2033 (python-tests-with-temp-buffer
2034 "" (python-shell-make-comint
2035 (python-shell-calculate-command) proc-name nil))))
2036 (process (get-buffer-process shell-buffer)))
2037 (unwind-protect
2038 (progn
2039 (set-process-query-on-exit-flag process nil)
2040 (should (process-live-p process))
2041 (with-current-buffer shell-buffer
2042 (should (eq major-mode 'inferior-python-mode))
2043 (should (string=
2044 python-shell--prompt-calculated-input-regexp
2045 (concat "^\\(extralargeinputprompt\\|\\.\\.> \\|"
2046 "block\\|py> \\|pdf\\|sml\\|in\\)")))
2047 (should (string=
2048 python-shell--prompt-calculated-output-regexp
2049 "^\\(extralargeoutputprompt\\|output\\|out \\|sml\\)"))))
2050 (delete-file startup-file)
2051 (kill-buffer shell-buffer))))
2053 (ert-deftest python-shell-get-process-1 ()
2054 "Check dedicated shell process preference over global."
2055 (skip-unless (executable-find python-tests-shell-interpreter))
2056 (python-tests-with-temp-file
2058 (let* ((python-shell-setup-codes nil)
2059 (python-shell-interpreter
2060 (executable-find python-tests-shell-interpreter))
2061 (global-proc-name (python-shell-get-process-name nil))
2062 (dedicated-proc-name (python-shell-get-process-name t))
2063 (global-shell-buffer
2064 (python-shell-make-comint
2065 (python-shell-calculate-command) global-proc-name))
2066 (dedicated-shell-buffer
2067 (python-shell-make-comint
2068 (python-shell-calculate-command) dedicated-proc-name))
2069 (global-process (get-buffer-process global-shell-buffer))
2070 (dedicated-process (get-buffer-process dedicated-shell-buffer)))
2071 (unwind-protect
2072 (progn
2073 (set-process-query-on-exit-flag global-process nil)
2074 (set-process-query-on-exit-flag dedicated-process nil)
2075 ;; Prefer dedicated if global also exists.
2076 (should (equal (python-shell-get-process) dedicated-process))
2077 (kill-buffer dedicated-shell-buffer)
2078 ;; If there's only global, use it.
2079 (should (equal (python-shell-get-process) global-process))
2080 (kill-buffer global-shell-buffer)
2081 ;; No buffer available.
2082 (should (not (python-shell-get-process))))
2083 (ignore-errors (kill-buffer global-shell-buffer))
2084 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2086 (ert-deftest python-shell-internal-get-or-create-process-1 ()
2087 "Check internal shell process creation fallback."
2088 (skip-unless (executable-find python-tests-shell-interpreter))
2089 (python-tests-with-temp-file
2091 (should (not (process-live-p (python-shell-internal-get-process-name))))
2092 (let* ((python-shell-interpreter
2093 (executable-find python-tests-shell-interpreter))
2094 (internal-process-name (python-shell-internal-get-process-name))
2095 (internal-process (python-shell-internal-get-or-create-process))
2096 (internal-shell-buffer (process-buffer internal-process)))
2097 (unwind-protect
2098 (progn
2099 (set-process-query-on-exit-flag internal-process nil)
2100 (should (equal (process-name internal-process)
2101 internal-process-name))
2102 (should (equal internal-process
2103 (python-shell-internal-get-or-create-process)))
2104 ;; Assert the internal process is not a user process
2105 (should (not (python-shell-get-process)))
2106 (kill-buffer internal-shell-buffer))
2107 (ignore-errors (kill-buffer internal-shell-buffer))))))
2109 (ert-deftest python-shell-prompt-detect-1 ()
2110 "Check prompt autodetection."
2111 (skip-unless (executable-find python-tests-shell-interpreter))
2112 (let ((process-environment process-environment))
2113 ;; Ensure no startup file is enabled
2114 (setenv "PYTHONSTARTUP" "")
2115 (should python-shell-prompt-detect-enabled)
2116 (should (equal (python-shell-prompt-detect) '(">>> " "... " "")))))
2118 (ert-deftest python-shell-prompt-detect-2 ()
2119 "Check prompt autodetection with startup file. Bug#17370."
2120 (skip-unless (executable-find python-tests-shell-interpreter))
2121 (let* ((process-environment process-environment)
2122 (startup-code (concat "import sys\n"
2123 "sys.ps1 = 'py> '\n"
2124 "sys.ps2 = '..> '\n"
2125 "sys.ps3 = 'out '\n"))
2126 (startup-file (python-shell--save-temp-file startup-code)))
2127 (unwind-protect
2128 (progn
2129 ;; Ensure startup file is enabled
2130 (setenv "PYTHONSTARTUP" startup-file)
2131 (should python-shell-prompt-detect-enabled)
2132 (should (equal (python-shell-prompt-detect) '("py> " "..> " "out "))))
2133 (ignore-errors (delete-file startup-file)))))
2135 (ert-deftest python-shell-prompt-detect-3 ()
2136 "Check prompts are not autodetected when feature is disabled."
2137 (skip-unless (executable-find python-tests-shell-interpreter))
2138 (let ((process-environment process-environment)
2139 (python-shell-prompt-detect-enabled nil))
2140 ;; Ensure no startup file is enabled
2141 (should (not python-shell-prompt-detect-enabled))
2142 (should (not (python-shell-prompt-detect)))))
2144 (ert-deftest python-shell-prompt-detect-4 ()
2145 "Check warning is shown when detection fails."
2146 (skip-unless (executable-find python-tests-shell-interpreter))
2147 (let* ((process-environment process-environment)
2148 ;; Trigger failure by removing prompts in the startup file
2149 (startup-code (concat "import sys\n"
2150 "sys.ps1 = ''\n"
2151 "sys.ps2 = ''\n"
2152 "sys.ps3 = ''\n"))
2153 (startup-file (python-shell--save-temp-file startup-code)))
2154 (unwind-protect
2155 (progn
2156 (kill-buffer (get-buffer-create "*Warnings*"))
2157 (should (not (get-buffer "*Warnings*")))
2158 (setenv "PYTHONSTARTUP" startup-file)
2159 (should python-shell-prompt-detect-failure-warning)
2160 (should python-shell-prompt-detect-enabled)
2161 (should (not (python-shell-prompt-detect)))
2162 (should (get-buffer "*Warnings*")))
2163 (ignore-errors (delete-file startup-file)))))
2165 (ert-deftest python-shell-prompt-detect-5 ()
2166 "Check disabled warnings are not shown when detection fails."
2167 (skip-unless (executable-find python-tests-shell-interpreter))
2168 (let* ((process-environment process-environment)
2169 (startup-code (concat "import sys\n"
2170 "sys.ps1 = ''\n"
2171 "sys.ps2 = ''\n"
2172 "sys.ps3 = ''\n"))
2173 (startup-file (python-shell--save-temp-file startup-code))
2174 (python-shell-prompt-detect-failure-warning nil))
2175 (unwind-protect
2176 (progn
2177 (kill-buffer (get-buffer-create "*Warnings*"))
2178 (should (not (get-buffer "*Warnings*")))
2179 (setenv "PYTHONSTARTUP" startup-file)
2180 (should (not python-shell-prompt-detect-failure-warning))
2181 (should python-shell-prompt-detect-enabled)
2182 (should (not (python-shell-prompt-detect)))
2183 (should (not (get-buffer "*Warnings*"))))
2184 (ignore-errors (delete-file startup-file)))))
2186 (ert-deftest python-shell-prompt-detect-6 ()
2187 "Warnings are not shown when detection is disabled."
2188 (skip-unless (executable-find python-tests-shell-interpreter))
2189 (let* ((process-environment process-environment)
2190 (startup-code (concat "import sys\n"
2191 "sys.ps1 = ''\n"
2192 "sys.ps2 = ''\n"
2193 "sys.ps3 = ''\n"))
2194 (startup-file (python-shell--save-temp-file startup-code))
2195 (python-shell-prompt-detect-failure-warning t)
2196 (python-shell-prompt-detect-enabled nil))
2197 (unwind-protect
2198 (progn
2199 (kill-buffer (get-buffer-create "*Warnings*"))
2200 (should (not (get-buffer "*Warnings*")))
2201 (setenv "PYTHONSTARTUP" startup-file)
2202 (should python-shell-prompt-detect-failure-warning)
2203 (should (not python-shell-prompt-detect-enabled))
2204 (should (not (python-shell-prompt-detect)))
2205 (should (not (get-buffer "*Warnings*"))))
2206 (ignore-errors (delete-file startup-file)))))
2208 (ert-deftest python-shell-prompt-validate-regexps-1 ()
2209 "Check `python-shell-prompt-input-regexps' are validated."
2210 (let* ((python-shell-prompt-input-regexps '("\\("))
2211 (error-data (should-error (python-shell-prompt-validate-regexps)
2212 :type 'user-error)))
2213 (should
2214 (string= (cadr error-data)
2215 "Invalid regexp \\( in `python-shell-prompt-input-regexps'"))))
2217 (ert-deftest python-shell-prompt-validate-regexps-2 ()
2218 "Check `python-shell-prompt-output-regexps' are validated."
2219 (let* ((python-shell-prompt-output-regexps '("\\("))
2220 (error-data (should-error (python-shell-prompt-validate-regexps)
2221 :type 'user-error)))
2222 (should
2223 (string= (cadr error-data)
2224 "Invalid regexp \\( in `python-shell-prompt-output-regexps'"))))
2226 (ert-deftest python-shell-prompt-validate-regexps-3 ()
2227 "Check `python-shell-prompt-regexp' is validated."
2228 (let* ((python-shell-prompt-regexp "\\(")
2229 (error-data (should-error (python-shell-prompt-validate-regexps)
2230 :type 'user-error)))
2231 (should
2232 (string= (cadr error-data)
2233 "Invalid regexp \\( in `python-shell-prompt-regexp'"))))
2235 (ert-deftest python-shell-prompt-validate-regexps-4 ()
2236 "Check `python-shell-prompt-block-regexp' is validated."
2237 (let* ((python-shell-prompt-block-regexp "\\(")
2238 (error-data (should-error (python-shell-prompt-validate-regexps)
2239 :type 'user-error)))
2240 (should
2241 (string= (cadr error-data)
2242 "Invalid regexp \\( in `python-shell-prompt-block-regexp'"))))
2244 (ert-deftest python-shell-prompt-validate-regexps-5 ()
2245 "Check `python-shell-prompt-pdb-regexp' is validated."
2246 (let* ((python-shell-prompt-pdb-regexp "\\(")
2247 (error-data (should-error (python-shell-prompt-validate-regexps)
2248 :type 'user-error)))
2249 (should
2250 (string= (cadr error-data)
2251 "Invalid regexp \\( in `python-shell-prompt-pdb-regexp'"))))
2253 (ert-deftest python-shell-prompt-validate-regexps-6 ()
2254 "Check `python-shell-prompt-output-regexp' is validated."
2255 (let* ((python-shell-prompt-output-regexp "\\(")
2256 (error-data (should-error (python-shell-prompt-validate-regexps)
2257 :type 'user-error)))
2258 (should
2259 (string= (cadr error-data)
2260 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2262 (ert-deftest python-shell-prompt-validate-regexps-7 ()
2263 "Check default regexps are valid."
2264 ;; should not signal error
2265 (python-shell-prompt-validate-regexps))
2267 (ert-deftest python-shell-prompt-set-calculated-regexps-1 ()
2268 "Check regexps are validated."
2269 (let* ((python-shell-prompt-output-regexp '("\\("))
2270 (python-shell--prompt-calculated-input-regexp nil)
2271 (python-shell--prompt-calculated-output-regexp nil)
2272 (python-shell-prompt-detect-enabled nil)
2273 (error-data (should-error (python-shell-prompt-set-calculated-regexps)
2274 :type 'user-error)))
2275 (should
2276 (string= (cadr error-data)
2277 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2279 (ert-deftest python-shell-prompt-set-calculated-regexps-2 ()
2280 "Check `python-shell-prompt-input-regexps' are set."
2281 (let* ((python-shell-prompt-input-regexps '("my" "prompt"))
2282 (python-shell-prompt-output-regexps '(""))
2283 (python-shell-prompt-regexp "")
2284 (python-shell-prompt-block-regexp "")
2285 (python-shell-prompt-pdb-regexp "")
2286 (python-shell-prompt-output-regexp "")
2287 (python-shell--prompt-calculated-input-regexp nil)
2288 (python-shell--prompt-calculated-output-regexp nil)
2289 (python-shell-prompt-detect-enabled nil))
2290 (python-shell-prompt-set-calculated-regexps)
2291 (should (string= python-shell--prompt-calculated-input-regexp
2292 "^\\(prompt\\|my\\|\\)"))))
2294 (ert-deftest python-shell-prompt-set-calculated-regexps-3 ()
2295 "Check `python-shell-prompt-output-regexps' are set."
2296 (let* ((python-shell-prompt-input-regexps '(""))
2297 (python-shell-prompt-output-regexps '("my" "prompt"))
2298 (python-shell-prompt-regexp "")
2299 (python-shell-prompt-block-regexp "")
2300 (python-shell-prompt-pdb-regexp "")
2301 (python-shell-prompt-output-regexp "")
2302 (python-shell--prompt-calculated-input-regexp nil)
2303 (python-shell--prompt-calculated-output-regexp nil)
2304 (python-shell-prompt-detect-enabled nil))
2305 (python-shell-prompt-set-calculated-regexps)
2306 (should (string= python-shell--prompt-calculated-output-regexp
2307 "^\\(prompt\\|my\\|\\)"))))
2309 (ert-deftest python-shell-prompt-set-calculated-regexps-4 ()
2310 "Check user defined prompts are set."
2311 (let* ((python-shell-prompt-input-regexps '(""))
2312 (python-shell-prompt-output-regexps '(""))
2313 (python-shell-prompt-regexp "prompt")
2314 (python-shell-prompt-block-regexp "block")
2315 (python-shell-prompt-pdb-regexp "pdb")
2316 (python-shell-prompt-output-regexp "output")
2317 (python-shell--prompt-calculated-input-regexp nil)
2318 (python-shell--prompt-calculated-output-regexp nil)
2319 (python-shell-prompt-detect-enabled nil))
2320 (python-shell-prompt-set-calculated-regexps)
2321 (should (string= python-shell--prompt-calculated-input-regexp
2322 "^\\(prompt\\|block\\|pdb\\|\\)"))
2323 (should (string= python-shell--prompt-calculated-output-regexp
2324 "^\\(output\\|\\)"))))
2326 (ert-deftest python-shell-prompt-set-calculated-regexps-5 ()
2327 "Check order of regexps (larger first)."
2328 (let* ((python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2329 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2330 (python-shell-prompt-regexp "in")
2331 (python-shell-prompt-block-regexp "block")
2332 (python-shell-prompt-pdb-regexp "pdf")
2333 (python-shell-prompt-output-regexp "output")
2334 (python-shell--prompt-calculated-input-regexp nil)
2335 (python-shell--prompt-calculated-output-regexp nil)
2336 (python-shell-prompt-detect-enabled nil))
2337 (python-shell-prompt-set-calculated-regexps)
2338 (should (string= python-shell--prompt-calculated-input-regexp
2339 "^\\(extralargeinputprompt\\|block\\|pdf\\|sml\\|in\\)"))
2340 (should (string= python-shell--prompt-calculated-output-regexp
2341 "^\\(extralargeoutputprompt\\|output\\|sml\\)"))))
2343 (ert-deftest python-shell-prompt-set-calculated-regexps-6 ()
2344 "Check detected prompts are included `regexp-quote'd."
2345 (skip-unless (executable-find python-tests-shell-interpreter))
2346 (let* ((python-shell-prompt-input-regexps '(""))
2347 (python-shell-prompt-output-regexps '(""))
2348 (python-shell-prompt-regexp "")
2349 (python-shell-prompt-block-regexp "")
2350 (python-shell-prompt-pdb-regexp "")
2351 (python-shell-prompt-output-regexp "")
2352 (python-shell--prompt-calculated-input-regexp nil)
2353 (python-shell--prompt-calculated-output-regexp nil)
2354 (python-shell-prompt-detect-enabled t)
2355 (process-environment process-environment)
2356 (startup-code (concat "import sys\n"
2357 "sys.ps1 = 'p.> '\n"
2358 "sys.ps2 = '..> '\n"
2359 "sys.ps3 = 'o.t '\n"))
2360 (startup-file (python-shell--save-temp-file startup-code)))
2361 (unwind-protect
2362 (progn
2363 (setenv "PYTHONSTARTUP" startup-file)
2364 (python-shell-prompt-set-calculated-regexps)
2365 (should (string= python-shell--prompt-calculated-input-regexp
2366 "^\\(\\.\\.> \\|p\\.> \\|\\)"))
2367 (should (string= python-shell--prompt-calculated-output-regexp
2368 "^\\(o\\.t \\|\\)")))
2369 (ignore-errors (delete-file startup-file)))))
2371 (ert-deftest python-shell-buffer-substring-1 ()
2372 "Selecting a substring of the whole buffer must match its contents."
2373 (python-tests-with-temp-buffer
2375 class Foo(models.Model):
2376 pass
2379 class Bar(models.Model):
2380 pass
2382 (should (string= (buffer-string)
2383 (python-shell-buffer-substring (point-min) (point-max))))))
2385 (ert-deftest python-shell-buffer-substring-2 ()
2386 "Main block should be removed if NOMAIN is non-nil."
2387 (python-tests-with-temp-buffer
2389 class Foo(models.Model):
2390 pass
2392 class Bar(models.Model):
2393 pass
2395 if __name__ == \"__main__\":
2396 foo = Foo()
2397 print (foo)
2399 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
2401 class Foo(models.Model):
2402 pass
2404 class Bar(models.Model):
2405 pass
2410 "))))
2412 (ert-deftest python-shell-buffer-substring-3 ()
2413 "Main block should be removed if NOMAIN is non-nil."
2414 (python-tests-with-temp-buffer
2416 class Foo(models.Model):
2417 pass
2419 if __name__ == \"__main__\":
2420 foo = Foo()
2421 print (foo)
2423 class Bar(models.Model):
2424 pass
2426 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
2428 class Foo(models.Model):
2429 pass
2435 class Bar(models.Model):
2436 pass
2437 "))))
2439 (ert-deftest python-shell-buffer-substring-4 ()
2440 "Coding cookie should be added for substrings."
2441 (python-tests-with-temp-buffer
2442 "# coding: latin-1
2444 class Foo(models.Model):
2445 pass
2447 if __name__ == \"__main__\":
2448 foo = Foo()
2449 print (foo)
2451 class Bar(models.Model):
2452 pass
2454 (should (string= (python-shell-buffer-substring
2455 (python-tests-look-at "class Foo(models.Model):")
2456 (progn (python-nav-forward-sexp) (point)))
2457 "# -*- coding: latin-1 -*-
2459 class Foo(models.Model):
2460 pass"))))
2462 (ert-deftest python-shell-buffer-substring-5 ()
2463 "The proper amount of blank lines is added for a substring."
2464 (python-tests-with-temp-buffer
2465 "# coding: latin-1
2467 class Foo(models.Model):
2468 pass
2470 if __name__ == \"__main__\":
2471 foo = Foo()
2472 print (foo)
2474 class Bar(models.Model):
2475 pass
2477 (should (string= (python-shell-buffer-substring
2478 (python-tests-look-at "class Bar(models.Model):")
2479 (progn (python-nav-forward-sexp) (point)))
2480 "# -*- coding: latin-1 -*-
2489 class Bar(models.Model):
2490 pass"))))
2492 (ert-deftest python-shell-buffer-substring-6 ()
2493 "Handle substring with coding cookie in the second line."
2494 (python-tests-with-temp-buffer
2496 # coding: latin-1
2498 class Foo(models.Model):
2499 pass
2501 if __name__ == \"__main__\":
2502 foo = Foo()
2503 print (foo)
2505 class Bar(models.Model):
2506 pass
2508 (should (string= (python-shell-buffer-substring
2509 (python-tests-look-at "# coding: latin-1")
2510 (python-tests-look-at "if __name__ == \"__main__\":"))
2511 "# -*- coding: latin-1 -*-
2514 class Foo(models.Model):
2515 pass
2517 "))))
2519 (ert-deftest python-shell-buffer-substring-7 ()
2520 "Ensure first coding cookie gets precedence."
2521 (python-tests-with-temp-buffer
2522 "# coding: utf-8
2523 # coding: latin-1
2525 class Foo(models.Model):
2526 pass
2528 if __name__ == \"__main__\":
2529 foo = Foo()
2530 print (foo)
2532 class Bar(models.Model):
2533 pass
2535 (should (string= (python-shell-buffer-substring
2536 (python-tests-look-at "# coding: latin-1")
2537 (python-tests-look-at "if __name__ == \"__main__\":"))
2538 "# -*- coding: utf-8 -*-
2541 class Foo(models.Model):
2542 pass
2544 "))))
2546 (ert-deftest python-shell-buffer-substring-8 ()
2547 "Ensure first coding cookie gets precedence when sending whole buffer."
2548 (python-tests-with-temp-buffer
2549 "# coding: utf-8
2550 # coding: latin-1
2552 class Foo(models.Model):
2553 pass
2555 (should (string= (python-shell-buffer-substring (point-min) (point-max))
2556 "# coding: utf-8
2559 class Foo(models.Model):
2560 pass
2561 "))))
2563 (ert-deftest python-shell-buffer-substring-9 ()
2564 "Check substring starting from `point-min'."
2565 (python-tests-with-temp-buffer
2566 "# coding: utf-8
2568 class Foo(models.Model):
2569 pass
2571 class Bar(models.Model):
2572 pass
2574 (should (string= (python-shell-buffer-substring
2575 (point-min)
2576 (python-tests-look-at "class Bar(models.Model):"))
2577 "# coding: utf-8
2579 class Foo(models.Model):
2580 pass
2582 "))))
2585 ;;; Shell completion
2587 (ert-deftest python-shell-completion-native-interpreter-disabled-p-1 ()
2588 (let* ((python-shell-completion-native-disabled-interpreters (list "pypy"))
2589 (python-shell-interpreter "/some/path/to/bin/pypy"))
2590 (should (python-shell-completion-native-interpreter-disabled-p))))
2595 ;;; PDB Track integration
2598 ;;; Symbol completion
2601 ;;; Fill paragraph
2604 ;;; Skeletons
2607 ;;; FFAP
2610 ;;; Code check
2613 ;;; Eldoc
2616 ;;; Imenu
2618 (ert-deftest python-imenu-create-index-1 ()
2619 (python-tests-with-temp-buffer
2621 class Foo(models.Model):
2622 pass
2625 class Bar(models.Model):
2626 pass
2629 def decorator(arg1, arg2, arg3):
2630 '''print decorated function call data to stdout.
2632 Usage:
2634 @decorator('arg1', 'arg2')
2635 def func(a, b, c=True):
2636 pass
2639 def wrap(f):
2640 print ('wrap')
2641 def wrapped_f(*args):
2642 print ('wrapped_f')
2643 print ('Decorator arguments:', arg1, arg2, arg3)
2644 f(*args)
2645 print ('called f(*args)')
2646 return wrapped_f
2647 return wrap
2650 class Baz(object):
2652 def a(self):
2653 pass
2655 def b(self):
2656 pass
2658 class Frob(object):
2660 def c(self):
2661 pass
2663 (goto-char (point-max))
2664 (should (equal
2665 (list
2666 (cons "Foo (class)" (copy-marker 2))
2667 (cons "Bar (class)" (copy-marker 38))
2668 (list
2669 "decorator (def)"
2670 (cons "*function definition*" (copy-marker 74))
2671 (list
2672 "wrap (def)"
2673 (cons "*function definition*" (copy-marker 254))
2674 (cons "wrapped_f (def)" (copy-marker 294))))
2675 (list
2676 "Baz (class)"
2677 (cons "*class definition*" (copy-marker 519))
2678 (cons "a (def)" (copy-marker 539))
2679 (cons "b (def)" (copy-marker 570))
2680 (list
2681 "Frob (class)"
2682 (cons "*class definition*" (copy-marker 601))
2683 (cons "c (def)" (copy-marker 626)))))
2684 (python-imenu-create-index)))))
2686 (ert-deftest python-imenu-create-index-2 ()
2687 (python-tests-with-temp-buffer
2689 class Foo(object):
2690 def foo(self):
2691 def foo1():
2692 pass
2694 def foobar(self):
2695 pass
2697 (goto-char (point-max))
2698 (should (equal
2699 (list
2700 (list
2701 "Foo (class)"
2702 (cons "*class definition*" (copy-marker 2))
2703 (list
2704 "foo (def)"
2705 (cons "*function definition*" (copy-marker 21))
2706 (cons "foo1 (def)" (copy-marker 40)))
2707 (cons "foobar (def)" (copy-marker 78))))
2708 (python-imenu-create-index)))))
2710 (ert-deftest python-imenu-create-index-3 ()
2711 (python-tests-with-temp-buffer
2713 class Foo(object):
2714 def foo(self):
2715 def foo1():
2716 pass
2717 def foo2():
2718 pass
2720 (goto-char (point-max))
2721 (should (equal
2722 (list
2723 (list
2724 "Foo (class)"
2725 (cons "*class definition*" (copy-marker 2))
2726 (list
2727 "foo (def)"
2728 (cons "*function definition*" (copy-marker 21))
2729 (cons "foo1 (def)" (copy-marker 40))
2730 (cons "foo2 (def)" (copy-marker 77)))))
2731 (python-imenu-create-index)))))
2733 (ert-deftest python-imenu-create-index-4 ()
2734 (python-tests-with-temp-buffer
2736 class Foo(object):
2737 class Bar(object):
2738 def __init__(self):
2739 pass
2741 def __str__(self):
2742 pass
2744 def __init__(self):
2745 pass
2747 (goto-char (point-max))
2748 (should (equal
2749 (list
2750 (list
2751 "Foo (class)"
2752 (cons "*class definition*" (copy-marker 2))
2753 (list
2754 "Bar (class)"
2755 (cons "*class definition*" (copy-marker 21))
2756 (cons "__init__ (def)" (copy-marker 44))
2757 (cons "__str__ (def)" (copy-marker 90)))
2758 (cons "__init__ (def)" (copy-marker 135))))
2759 (python-imenu-create-index)))))
2761 (ert-deftest python-imenu-create-flat-index-1 ()
2762 (python-tests-with-temp-buffer
2764 class Foo(models.Model):
2765 pass
2768 class Bar(models.Model):
2769 pass
2772 def decorator(arg1, arg2, arg3):
2773 '''print decorated function call data to stdout.
2775 Usage:
2777 @decorator('arg1', 'arg2')
2778 def func(a, b, c=True):
2779 pass
2782 def wrap(f):
2783 print ('wrap')
2784 def wrapped_f(*args):
2785 print ('wrapped_f')
2786 print ('Decorator arguments:', arg1, arg2, arg3)
2787 f(*args)
2788 print ('called f(*args)')
2789 return wrapped_f
2790 return wrap
2793 class Baz(object):
2795 def a(self):
2796 pass
2798 def b(self):
2799 pass
2801 class Frob(object):
2803 def c(self):
2804 pass
2806 (goto-char (point-max))
2807 (should (equal
2808 (list (cons "Foo" (copy-marker 2))
2809 (cons "Bar" (copy-marker 38))
2810 (cons "decorator" (copy-marker 74))
2811 (cons "decorator.wrap" (copy-marker 254))
2812 (cons "decorator.wrap.wrapped_f" (copy-marker 294))
2813 (cons "Baz" (copy-marker 519))
2814 (cons "Baz.a" (copy-marker 539))
2815 (cons "Baz.b" (copy-marker 570))
2816 (cons "Baz.Frob" (copy-marker 601))
2817 (cons "Baz.Frob.c" (copy-marker 626)))
2818 (python-imenu-create-flat-index)))))
2820 (ert-deftest python-imenu-create-flat-index-2 ()
2821 (python-tests-with-temp-buffer
2823 class Foo(object):
2824 class Bar(object):
2825 def __init__(self):
2826 pass
2828 def __str__(self):
2829 pass
2831 def __init__(self):
2832 pass
2834 (goto-char (point-max))
2835 (should (equal
2836 (list
2837 (cons "Foo" (copy-marker 2))
2838 (cons "Foo.Bar" (copy-marker 21))
2839 (cons "Foo.Bar.__init__" (copy-marker 44))
2840 (cons "Foo.Bar.__str__" (copy-marker 90))
2841 (cons "Foo.__init__" (copy-marker 135)))
2842 (python-imenu-create-flat-index)))))
2845 ;;; Misc helpers
2847 (ert-deftest python-info-current-defun-1 ()
2848 (python-tests-with-temp-buffer
2850 def foo(a, b):
2852 (forward-line 1)
2853 (should (string= "foo" (python-info-current-defun)))
2854 (should (string= "def foo" (python-info-current-defun t)))
2855 (forward-line 1)
2856 (should (not (python-info-current-defun)))
2857 (indent-for-tab-command)
2858 (should (string= "foo" (python-info-current-defun)))
2859 (should (string= "def foo" (python-info-current-defun t)))))
2861 (ert-deftest python-info-current-defun-2 ()
2862 (python-tests-with-temp-buffer
2864 class C(object):
2866 def m(self):
2867 if True:
2868 return [i for i in range(3)]
2869 else:
2870 return []
2872 def b():
2873 do_b()
2875 def a():
2876 do_a()
2878 def c(self):
2879 do_c()
2881 (forward-line 1)
2882 (should (string= "C" (python-info-current-defun)))
2883 (should (string= "class C" (python-info-current-defun t)))
2884 (python-tests-look-at "return [i for ")
2885 (should (string= "C.m" (python-info-current-defun)))
2886 (should (string= "def C.m" (python-info-current-defun t)))
2887 (python-tests-look-at "def b():")
2888 (should (string= "C.m.b" (python-info-current-defun)))
2889 (should (string= "def C.m.b" (python-info-current-defun t)))
2890 (forward-line 2)
2891 (indent-for-tab-command)
2892 (python-indent-dedent-line-backspace 1)
2893 (should (string= "C.m" (python-info-current-defun)))
2894 (should (string= "def C.m" (python-info-current-defun t)))
2895 (python-tests-look-at "def c(self):")
2896 (forward-line -1)
2897 (indent-for-tab-command)
2898 (should (string= "C.m.a" (python-info-current-defun)))
2899 (should (string= "def C.m.a" (python-info-current-defun t)))
2900 (python-indent-dedent-line-backspace 1)
2901 (should (string= "C.m" (python-info-current-defun)))
2902 (should (string= "def C.m" (python-info-current-defun t)))
2903 (python-indent-dedent-line-backspace 1)
2904 (should (string= "C" (python-info-current-defun)))
2905 (should (string= "class C" (python-info-current-defun t)))
2906 (python-tests-look-at "def c(self):")
2907 (should (string= "C.c" (python-info-current-defun)))
2908 (should (string= "def C.c" (python-info-current-defun t)))
2909 (python-tests-look-at "do_c()")
2910 (should (string= "C.c" (python-info-current-defun)))
2911 (should (string= "def C.c" (python-info-current-defun t)))))
2913 (ert-deftest python-info-current-defun-3 ()
2914 (python-tests-with-temp-buffer
2916 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2917 '''print decorated function call data to stdout.
2919 Usage:
2921 @decoratorFunctionWithArguments('arg1', 'arg2')
2922 def func(a, b, c=True):
2923 pass
2926 def wwrap(f):
2927 print 'Inside wwrap()'
2928 def wrapped_f(*args):
2929 print 'Inside wrapped_f()'
2930 print 'Decorator arguments:', arg1, arg2, arg3
2931 f(*args)
2932 print 'After f(*args)'
2933 return wrapped_f
2934 return wwrap
2936 (python-tests-look-at "def wwrap(f):")
2937 (forward-line -1)
2938 (should (not (python-info-current-defun)))
2939 (indent-for-tab-command 1)
2940 (should (string= (python-info-current-defun)
2941 "decoratorFunctionWithArguments"))
2942 (should (string= (python-info-current-defun t)
2943 "def decoratorFunctionWithArguments"))
2944 (python-tests-look-at "def wrapped_f(*args):")
2945 (should (string= (python-info-current-defun)
2946 "decoratorFunctionWithArguments.wwrap.wrapped_f"))
2947 (should (string= (python-info-current-defun t)
2948 "def decoratorFunctionWithArguments.wwrap.wrapped_f"))
2949 (python-tests-look-at "return wrapped_f")
2950 (should (string= (python-info-current-defun)
2951 "decoratorFunctionWithArguments.wwrap"))
2952 (should (string= (python-info-current-defun t)
2953 "def decoratorFunctionWithArguments.wwrap"))
2954 (end-of-line 1)
2955 (python-tests-look-at "return wwrap")
2956 (should (string= (python-info-current-defun)
2957 "decoratorFunctionWithArguments"))
2958 (should (string= (python-info-current-defun t)
2959 "def decoratorFunctionWithArguments"))))
2961 (ert-deftest python-info-current-symbol-1 ()
2962 (python-tests-with-temp-buffer
2964 class C(object):
2966 def m(self):
2967 self.c()
2969 def c(self):
2970 print ('a')
2972 (python-tests-look-at "self.c()")
2973 (should (string= "self.c" (python-info-current-symbol)))
2974 (should (string= "C.c" (python-info-current-symbol t)))))
2976 (ert-deftest python-info-current-symbol-2 ()
2977 (python-tests-with-temp-buffer
2979 class C(object):
2981 class M(object):
2983 def a(self):
2984 self.c()
2986 def c(self):
2987 pass
2989 (python-tests-look-at "self.c()")
2990 (should (string= "self.c" (python-info-current-symbol)))
2991 (should (string= "C.M.c" (python-info-current-symbol t)))))
2993 (ert-deftest python-info-current-symbol-3 ()
2994 "Keywords should not be considered symbols."
2995 :expected-result :failed
2996 (python-tests-with-temp-buffer
2998 class C(object):
2999 pass
3001 ;; FIXME: keywords are not symbols.
3002 (python-tests-look-at "class C")
3003 (should (not (python-info-current-symbol)))
3004 (should (not (python-info-current-symbol t)))
3005 (python-tests-look-at "C(object)")
3006 (should (string= "C" (python-info-current-symbol)))
3007 (should (string= "class C" (python-info-current-symbol t)))))
3009 (ert-deftest python-info-statement-starts-block-p-1 ()
3010 (python-tests-with-temp-buffer
3012 def long_function_name(
3013 var_one, var_two, var_three,
3014 var_four):
3015 print (var_one)
3017 (python-tests-look-at "def long_function_name")
3018 (should (python-info-statement-starts-block-p))
3019 (python-tests-look-at "print (var_one)")
3020 (python-util-forward-comment -1)
3021 (should (python-info-statement-starts-block-p))))
3023 (ert-deftest python-info-statement-starts-block-p-2 ()
3024 (python-tests-with-temp-buffer
3026 if width == 0 and height == 0 and \\\\
3027 color == 'red' and emphasis == 'strong' or \\\\
3028 highlight > 100:
3029 raise ValueError('sorry, you lose')
3031 (python-tests-look-at "if width == 0 and")
3032 (should (python-info-statement-starts-block-p))
3033 (python-tests-look-at "raise ValueError(")
3034 (python-util-forward-comment -1)
3035 (should (python-info-statement-starts-block-p))))
3037 (ert-deftest python-info-statement-ends-block-p-1 ()
3038 (python-tests-with-temp-buffer
3040 def long_function_name(
3041 var_one, var_two, var_three,
3042 var_four):
3043 print (var_one)
3045 (python-tests-look-at "print (var_one)")
3046 (should (python-info-statement-ends-block-p))))
3048 (ert-deftest python-info-statement-ends-block-p-2 ()
3049 (python-tests-with-temp-buffer
3051 if width == 0 and height == 0 and \\\\
3052 color == 'red' and emphasis == 'strong' or \\\\
3053 highlight > 100:
3054 raise ValueError(
3055 'sorry, you lose'
3059 (python-tests-look-at "raise ValueError(")
3060 (should (python-info-statement-ends-block-p))))
3062 (ert-deftest python-info-beginning-of-statement-p-1 ()
3063 (python-tests-with-temp-buffer
3065 def long_function_name(
3066 var_one, var_two, var_three,
3067 var_four):
3068 print (var_one)
3070 (python-tests-look-at "def long_function_name")
3071 (should (python-info-beginning-of-statement-p))
3072 (forward-char 10)
3073 (should (not (python-info-beginning-of-statement-p)))
3074 (python-tests-look-at "print (var_one)")
3075 (should (python-info-beginning-of-statement-p))
3076 (goto-char (line-beginning-position))
3077 (should (not (python-info-beginning-of-statement-p)))))
3079 (ert-deftest python-info-beginning-of-statement-p-2 ()
3080 (python-tests-with-temp-buffer
3082 if width == 0 and height == 0 and \\\\
3083 color == 'red' and emphasis == 'strong' or \\\\
3084 highlight > 100:
3085 raise ValueError(
3086 'sorry, you lose'
3090 (python-tests-look-at "if width == 0 and")
3091 (should (python-info-beginning-of-statement-p))
3092 (forward-char 10)
3093 (should (not (python-info-beginning-of-statement-p)))
3094 (python-tests-look-at "raise ValueError(")
3095 (should (python-info-beginning-of-statement-p))
3096 (goto-char (line-beginning-position))
3097 (should (not (python-info-beginning-of-statement-p)))))
3099 (ert-deftest python-info-end-of-statement-p-1 ()
3100 (python-tests-with-temp-buffer
3102 def long_function_name(
3103 var_one, var_two, var_three,
3104 var_four):
3105 print (var_one)
3107 (python-tests-look-at "def long_function_name")
3108 (should (not (python-info-end-of-statement-p)))
3109 (end-of-line)
3110 (should (not (python-info-end-of-statement-p)))
3111 (python-tests-look-at "print (var_one)")
3112 (python-util-forward-comment -1)
3113 (should (python-info-end-of-statement-p))
3114 (python-tests-look-at "print (var_one)")
3115 (should (not (python-info-end-of-statement-p)))
3116 (end-of-line)
3117 (should (python-info-end-of-statement-p))))
3119 (ert-deftest python-info-end-of-statement-p-2 ()
3120 (python-tests-with-temp-buffer
3122 if width == 0 and height == 0 and \\\\
3123 color == 'red' and emphasis == 'strong' or \\\\
3124 highlight > 100:
3125 raise ValueError(
3126 'sorry, you lose'
3130 (python-tests-look-at "if width == 0 and")
3131 (should (not (python-info-end-of-statement-p)))
3132 (end-of-line)
3133 (should (not (python-info-end-of-statement-p)))
3134 (python-tests-look-at "raise ValueError(")
3135 (python-util-forward-comment -1)
3136 (should (python-info-end-of-statement-p))
3137 (python-tests-look-at "raise ValueError(")
3138 (should (not (python-info-end-of-statement-p)))
3139 (end-of-line)
3140 (should (not (python-info-end-of-statement-p)))
3141 (goto-char (point-max))
3142 (python-util-forward-comment -1)
3143 (should (python-info-end-of-statement-p))))
3145 (ert-deftest python-info-beginning-of-block-p-1 ()
3146 (python-tests-with-temp-buffer
3148 def long_function_name(
3149 var_one, var_two, var_three,
3150 var_four):
3151 print (var_one)
3153 (python-tests-look-at "def long_function_name")
3154 (should (python-info-beginning-of-block-p))
3155 (python-tests-look-at "var_one, var_two, var_three,")
3156 (should (not (python-info-beginning-of-block-p)))
3157 (python-tests-look-at "print (var_one)")
3158 (should (not (python-info-beginning-of-block-p)))))
3160 (ert-deftest python-info-beginning-of-block-p-2 ()
3161 (python-tests-with-temp-buffer
3163 if width == 0 and height == 0 and \\\\
3164 color == 'red' and emphasis == 'strong' or \\\\
3165 highlight > 100:
3166 raise ValueError(
3167 'sorry, you lose'
3171 (python-tests-look-at "if width == 0 and")
3172 (should (python-info-beginning-of-block-p))
3173 (python-tests-look-at "color == 'red' and emphasis")
3174 (should (not (python-info-beginning-of-block-p)))
3175 (python-tests-look-at "raise ValueError(")
3176 (should (not (python-info-beginning-of-block-p)))))
3178 (ert-deftest python-info-end-of-block-p-1 ()
3179 (python-tests-with-temp-buffer
3181 def long_function_name(
3182 var_one, var_two, var_three,
3183 var_four):
3184 print (var_one)
3186 (python-tests-look-at "def long_function_name")
3187 (should (not (python-info-end-of-block-p)))
3188 (python-tests-look-at "var_one, var_two, var_three,")
3189 (should (not (python-info-end-of-block-p)))
3190 (python-tests-look-at "var_four):")
3191 (end-of-line)
3192 (should (not (python-info-end-of-block-p)))
3193 (python-tests-look-at "print (var_one)")
3194 (should (not (python-info-end-of-block-p)))
3195 (end-of-line 1)
3196 (should (python-info-end-of-block-p))))
3198 (ert-deftest python-info-end-of-block-p-2 ()
3199 (python-tests-with-temp-buffer
3201 if width == 0 and height == 0 and \\\\
3202 color == 'red' and emphasis == 'strong' or \\\\
3203 highlight > 100:
3204 raise ValueError(
3205 'sorry, you lose'
3209 (python-tests-look-at "if width == 0 and")
3210 (should (not (python-info-end-of-block-p)))
3211 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3212 (should (not (python-info-end-of-block-p)))
3213 (python-tests-look-at "highlight > 100:")
3214 (end-of-line)
3215 (should (not (python-info-end-of-block-p)))
3216 (python-tests-look-at "raise ValueError(")
3217 (should (not (python-info-end-of-block-p)))
3218 (end-of-line 1)
3219 (should (not (python-info-end-of-block-p)))
3220 (goto-char (point-max))
3221 (python-util-forward-comment -1)
3222 (should (python-info-end-of-block-p))))
3224 (ert-deftest python-info-dedenter-opening-block-position-1 ()
3225 (python-tests-with-temp-buffer
3227 if request.user.is_authenticated():
3228 try:
3229 profile = request.user.get_profile()
3230 except Profile.DoesNotExist:
3231 profile = Profile.objects.create(user=request.user)
3232 else:
3233 if profile.stats:
3234 profile.recalculate_stats()
3235 else:
3236 profile.clear_stats()
3237 finally:
3238 profile.views += 1
3239 profile.save()
3241 (python-tests-look-at "try:")
3242 (should (not (python-info-dedenter-opening-block-position)))
3243 (python-tests-look-at "except Profile.DoesNotExist:")
3244 (should (= (python-tests-look-at "try:" -1 t)
3245 (python-info-dedenter-opening-block-position)))
3246 (python-tests-look-at "else:")
3247 (should (= (python-tests-look-at "except Profile.DoesNotExist:" -1 t)
3248 (python-info-dedenter-opening-block-position)))
3249 (python-tests-look-at "if profile.stats:")
3250 (should (not (python-info-dedenter-opening-block-position)))
3251 (python-tests-look-at "else:")
3252 (should (= (python-tests-look-at "if profile.stats:" -1 t)
3253 (python-info-dedenter-opening-block-position)))
3254 (python-tests-look-at "finally:")
3255 (should (= (python-tests-look-at "else:" -2 t)
3256 (python-info-dedenter-opening-block-position)))))
3258 (ert-deftest python-info-dedenter-opening-block-position-2 ()
3259 (python-tests-with-temp-buffer
3261 if request.user.is_authenticated():
3262 profile = Profile.objects.get_or_create(user=request.user)
3263 if profile.stats:
3264 profile.recalculate_stats()
3266 data = {
3267 'else': 'do it'
3269 'else'
3271 (python-tests-look-at "'else': 'do it'")
3272 (should (not (python-info-dedenter-opening-block-position)))
3273 (python-tests-look-at "'else'")
3274 (should (not (python-info-dedenter-opening-block-position)))))
3276 (ert-deftest python-info-dedenter-opening-block-position-3 ()
3277 (python-tests-with-temp-buffer
3279 if save:
3280 try:
3281 write_to_disk(data)
3282 except IOError:
3283 msg = 'Error saving to disk'
3284 message(msg)
3285 logger.exception(msg)
3286 except Exception:
3287 if hide_details:
3288 logger.exception('Unhandled exception')
3289 else
3290 finally:
3291 data.free()
3293 (python-tests-look-at "try:")
3294 (should (not (python-info-dedenter-opening-block-position)))
3296 (python-tests-look-at "except IOError:")
3297 (should (= (python-tests-look-at "try:" -1 t)
3298 (python-info-dedenter-opening-block-position)))
3300 (python-tests-look-at "except Exception:")
3301 (should (= (python-tests-look-at "except IOError:" -1 t)
3302 (python-info-dedenter-opening-block-position)))
3304 (python-tests-look-at "if hide_details:")
3305 (should (not (python-info-dedenter-opening-block-position)))
3307 ;; check indentation modifies the detected opening block
3308 (python-tests-look-at "else")
3309 (should (= (python-tests-look-at "if hide_details:" -1 t)
3310 (python-info-dedenter-opening-block-position)))
3312 (indent-line-to 8)
3313 (should (= (python-tests-look-at "if hide_details:" -1 t)
3314 (python-info-dedenter-opening-block-position)))
3316 (indent-line-to 4)
3317 (should (= (python-tests-look-at "except Exception:" -1 t)
3318 (python-info-dedenter-opening-block-position)))
3320 (indent-line-to 0)
3321 (should (= (python-tests-look-at "if save:" -1 t)
3322 (python-info-dedenter-opening-block-position)))))
3324 (ert-deftest python-info-dedenter-opening-block-positions-1 ()
3325 (python-tests-with-temp-buffer
3327 if save:
3328 try:
3329 write_to_disk(data)
3330 except IOError:
3331 msg = 'Error saving to disk'
3332 message(msg)
3333 logger.exception(msg)
3334 except Exception:
3335 if hide_details:
3336 logger.exception('Unhandled exception')
3337 else
3338 finally:
3339 data.free()
3341 (python-tests-look-at "try:")
3342 (should (not (python-info-dedenter-opening-block-positions)))
3344 (python-tests-look-at "except IOError:")
3345 (should
3346 (equal (list
3347 (python-tests-look-at "try:" -1 t))
3348 (python-info-dedenter-opening-block-positions)))
3350 (python-tests-look-at "except Exception:")
3351 (should
3352 (equal (list
3353 (python-tests-look-at "except IOError:" -1 t))
3354 (python-info-dedenter-opening-block-positions)))
3356 (python-tests-look-at "if hide_details:")
3357 (should (not (python-info-dedenter-opening-block-positions)))
3359 ;; check indentation does not modify the detected opening blocks
3360 (python-tests-look-at "else")
3361 (should
3362 (equal (list
3363 (python-tests-look-at "if hide_details:" -1 t)
3364 (python-tests-look-at "except Exception:" -1 t)
3365 (python-tests-look-at "if save:" -1 t))
3366 (python-info-dedenter-opening-block-positions)))
3368 (indent-line-to 8)
3369 (should
3370 (equal (list
3371 (python-tests-look-at "if hide_details:" -1 t)
3372 (python-tests-look-at "except Exception:" -1 t)
3373 (python-tests-look-at "if save:" -1 t))
3374 (python-info-dedenter-opening-block-positions)))
3376 (indent-line-to 4)
3377 (should
3378 (equal (list
3379 (python-tests-look-at "if hide_details:" -1 t)
3380 (python-tests-look-at "except Exception:" -1 t)
3381 (python-tests-look-at "if save:" -1 t))
3382 (python-info-dedenter-opening-block-positions)))
3384 (indent-line-to 0)
3385 (should
3386 (equal (list
3387 (python-tests-look-at "if hide_details:" -1 t)
3388 (python-tests-look-at "except Exception:" -1 t)
3389 (python-tests-look-at "if save:" -1 t))
3390 (python-info-dedenter-opening-block-positions)))))
3392 (ert-deftest python-info-dedenter-opening-block-positions-2 ()
3393 "Test detection of opening blocks for elif."
3394 (python-tests-with-temp-buffer
3396 if var:
3397 if var2:
3398 something()
3399 elif var3:
3400 something_else()
3401 elif
3403 (python-tests-look-at "elif var3:")
3404 (should
3405 (equal (list
3406 (python-tests-look-at "if var2:" -1 t)
3407 (python-tests-look-at "if var:" -1 t))
3408 (python-info-dedenter-opening-block-positions)))
3410 (python-tests-look-at "elif\n")
3411 (should
3412 (equal (list
3413 (python-tests-look-at "elif var3:" -1 t)
3414 (python-tests-look-at "if var:" -1 t))
3415 (python-info-dedenter-opening-block-positions)))))
3417 (ert-deftest python-info-dedenter-opening-block-positions-3 ()
3418 "Test detection of opening blocks for else."
3419 (python-tests-with-temp-buffer
3421 try:
3422 something()
3423 except:
3424 if var:
3425 if var2:
3426 something()
3427 elif var3:
3428 something_else()
3429 else
3431 if var4:
3432 while var5:
3433 var4.pop()
3434 else
3436 for value in var6:
3437 if value > 0:
3438 print value
3439 else
3441 (python-tests-look-at "else\n")
3442 (should
3443 (equal (list
3444 (python-tests-look-at "elif var3:" -1 t)
3445 (python-tests-look-at "if var:" -1 t)
3446 (python-tests-look-at "except:" -1 t))
3447 (python-info-dedenter-opening-block-positions)))
3449 (python-tests-look-at "else\n")
3450 (should
3451 (equal (list
3452 (python-tests-look-at "while var5:" -1 t)
3453 (python-tests-look-at "if var4:" -1 t))
3454 (python-info-dedenter-opening-block-positions)))
3456 (python-tests-look-at "else\n")
3457 (should
3458 (equal (list
3459 (python-tests-look-at "if value > 0:" -1 t)
3460 (python-tests-look-at "for value in var6:" -1 t)
3461 (python-tests-look-at "if var4:" -1 t))
3462 (python-info-dedenter-opening-block-positions)))))
3464 (ert-deftest python-info-dedenter-opening-block-positions-4 ()
3465 "Test detection of opening blocks for except."
3466 (python-tests-with-temp-buffer
3468 try:
3469 something()
3470 except ValueError:
3471 something_else()
3472 except
3474 (python-tests-look-at "except ValueError:")
3475 (should
3476 (equal (list (python-tests-look-at "try:" -1 t))
3477 (python-info-dedenter-opening-block-positions)))
3479 (python-tests-look-at "except\n")
3480 (should
3481 (equal (list (python-tests-look-at "except ValueError:" -1 t))
3482 (python-info-dedenter-opening-block-positions)))))
3484 (ert-deftest python-info-dedenter-opening-block-positions-5 ()
3485 "Test detection of opening blocks for finally."
3486 (python-tests-with-temp-buffer
3488 try:
3489 something()
3490 finally
3492 try:
3493 something_else()
3494 except:
3495 logger.exception('something went wrong')
3496 finally
3498 try:
3499 something_else_else()
3500 except Exception:
3501 logger.exception('something else went wrong')
3502 else:
3503 print ('all good')
3504 finally
3506 (python-tests-look-at "finally\n")
3507 (should
3508 (equal (list (python-tests-look-at "try:" -1 t))
3509 (python-info-dedenter-opening-block-positions)))
3511 (python-tests-look-at "finally\n")
3512 (should
3513 (equal (list (python-tests-look-at "except:" -1 t))
3514 (python-info-dedenter-opening-block-positions)))
3516 (python-tests-look-at "finally\n")
3517 (should
3518 (equal (list (python-tests-look-at "else:" -1 t))
3519 (python-info-dedenter-opening-block-positions)))))
3521 (ert-deftest python-info-dedenter-opening-block-message-1 ()
3522 "Test dedenters inside strings are ignored."
3523 (python-tests-with-temp-buffer
3524 "'''
3525 try:
3526 something()
3527 except:
3528 logger.exception('something went wrong')
3531 (python-tests-look-at "except\n")
3532 (should (not (python-info-dedenter-opening-block-message)))))
3534 (ert-deftest python-info-dedenter-opening-block-message-2 ()
3535 "Test except keyword."
3536 (python-tests-with-temp-buffer
3538 try:
3539 something()
3540 except:
3541 logger.exception('something went wrong')
3543 (python-tests-look-at "except:")
3544 (should (string=
3545 "Closes try:"
3546 (substring-no-properties
3547 (python-info-dedenter-opening-block-message))))
3548 (end-of-line)
3549 (should (string=
3550 "Closes try:"
3551 (substring-no-properties
3552 (python-info-dedenter-opening-block-message))))))
3554 (ert-deftest python-info-dedenter-opening-block-message-3 ()
3555 "Test else keyword."
3556 (python-tests-with-temp-buffer
3558 try:
3559 something()
3560 except:
3561 logger.exception('something went wrong')
3562 else:
3563 logger.debug('all good')
3565 (python-tests-look-at "else:")
3566 (should (string=
3567 "Closes except:"
3568 (substring-no-properties
3569 (python-info-dedenter-opening-block-message))))
3570 (end-of-line)
3571 (should (string=
3572 "Closes except:"
3573 (substring-no-properties
3574 (python-info-dedenter-opening-block-message))))))
3576 (ert-deftest python-info-dedenter-opening-block-message-4 ()
3577 "Test finally keyword."
3578 (python-tests-with-temp-buffer
3580 try:
3581 something()
3582 except:
3583 logger.exception('something went wrong')
3584 else:
3585 logger.debug('all good')
3586 finally:
3587 clean()
3589 (python-tests-look-at "finally:")
3590 (should (string=
3591 "Closes else:"
3592 (substring-no-properties
3593 (python-info-dedenter-opening-block-message))))
3594 (end-of-line)
3595 (should (string=
3596 "Closes else:"
3597 (substring-no-properties
3598 (python-info-dedenter-opening-block-message))))))
3600 (ert-deftest python-info-dedenter-opening-block-message-5 ()
3601 "Test elif keyword."
3602 (python-tests-with-temp-buffer
3604 if a:
3605 something()
3606 elif b:
3608 (python-tests-look-at "elif b:")
3609 (should (string=
3610 "Closes if a:"
3611 (substring-no-properties
3612 (python-info-dedenter-opening-block-message))))
3613 (end-of-line)
3614 (should (string=
3615 "Closes if a:"
3616 (substring-no-properties
3617 (python-info-dedenter-opening-block-message))))))
3620 (ert-deftest python-info-dedenter-statement-p-1 ()
3621 "Test dedenters inside strings are ignored."
3622 (python-tests-with-temp-buffer
3623 "'''
3624 try:
3625 something()
3626 except:
3627 logger.exception('something went wrong')
3630 (python-tests-look-at "except\n")
3631 (should (not (python-info-dedenter-statement-p)))))
3633 (ert-deftest python-info-dedenter-statement-p-2 ()
3634 "Test except keyword."
3635 (python-tests-with-temp-buffer
3637 try:
3638 something()
3639 except:
3640 logger.exception('something went wrong')
3642 (python-tests-look-at "except:")
3643 (should (= (point) (python-info-dedenter-statement-p)))
3644 (end-of-line)
3645 (should (= (save-excursion
3646 (back-to-indentation)
3647 (point))
3648 (python-info-dedenter-statement-p)))))
3650 (ert-deftest python-info-dedenter-statement-p-3 ()
3651 "Test else keyword."
3652 (python-tests-with-temp-buffer
3654 try:
3655 something()
3656 except:
3657 logger.exception('something went wrong')
3658 else:
3659 logger.debug('all good')
3661 (python-tests-look-at "else:")
3662 (should (= (point) (python-info-dedenter-statement-p)))
3663 (end-of-line)
3664 (should (= (save-excursion
3665 (back-to-indentation)
3666 (point))
3667 (python-info-dedenter-statement-p)))))
3669 (ert-deftest python-info-dedenter-statement-p-4 ()
3670 "Test finally keyword."
3671 (python-tests-with-temp-buffer
3673 try:
3674 something()
3675 except:
3676 logger.exception('something went wrong')
3677 else:
3678 logger.debug('all good')
3679 finally:
3680 clean()
3682 (python-tests-look-at "finally:")
3683 (should (= (point) (python-info-dedenter-statement-p)))
3684 (end-of-line)
3685 (should (= (save-excursion
3686 (back-to-indentation)
3687 (point))
3688 (python-info-dedenter-statement-p)))))
3690 (ert-deftest python-info-dedenter-statement-p-5 ()
3691 "Test elif keyword."
3692 (python-tests-with-temp-buffer
3694 if a:
3695 something()
3696 elif b:
3698 (python-tests-look-at "elif b:")
3699 (should (= (point) (python-info-dedenter-statement-p)))
3700 (end-of-line)
3701 (should (= (save-excursion
3702 (back-to-indentation)
3703 (point))
3704 (python-info-dedenter-statement-p)))))
3706 (ert-deftest python-info-line-ends-backslash-p-1 ()
3707 (python-tests-with-temp-buffer
3709 objects = Thing.objects.all() \\\\
3710 .filter(
3711 type='toy',
3712 status='bought'
3713 ) \\\\
3714 .aggregate(
3715 Sum('amount')
3716 ) \\\\
3717 .values_list()
3719 (should (python-info-line-ends-backslash-p 2)) ; .filter(...
3720 (should (python-info-line-ends-backslash-p 3))
3721 (should (python-info-line-ends-backslash-p 4))
3722 (should (python-info-line-ends-backslash-p 5))
3723 (should (python-info-line-ends-backslash-p 6)) ; ) \...
3724 (should (python-info-line-ends-backslash-p 7))
3725 (should (python-info-line-ends-backslash-p 8))
3726 (should (python-info-line-ends-backslash-p 9))
3727 (should (not (python-info-line-ends-backslash-p 10))))) ; .values_list()...
3729 (ert-deftest python-info-beginning-of-backslash-1 ()
3730 (python-tests-with-temp-buffer
3732 objects = Thing.objects.all() \\\\
3733 .filter(
3734 type='toy',
3735 status='bought'
3736 ) \\\\
3737 .aggregate(
3738 Sum('amount')
3739 ) \\\\
3740 .values_list()
3742 (let ((first 2)
3743 (second (python-tests-look-at ".filter("))
3744 (third (python-tests-look-at ".aggregate(")))
3745 (should (= first (python-info-beginning-of-backslash 2)))
3746 (should (= second (python-info-beginning-of-backslash 3)))
3747 (should (= second (python-info-beginning-of-backslash 4)))
3748 (should (= second (python-info-beginning-of-backslash 5)))
3749 (should (= second (python-info-beginning-of-backslash 6)))
3750 (should (= third (python-info-beginning-of-backslash 7)))
3751 (should (= third (python-info-beginning-of-backslash 8)))
3752 (should (= third (python-info-beginning-of-backslash 9)))
3753 (should (not (python-info-beginning-of-backslash 10))))))
3755 (ert-deftest python-info-continuation-line-p-1 ()
3756 (python-tests-with-temp-buffer
3758 if width == 0 and height == 0 and \\\\
3759 color == 'red' and emphasis == 'strong' or \\\\
3760 highlight > 100:
3761 raise ValueError(
3762 'sorry, you lose'
3766 (python-tests-look-at "if width == 0 and height == 0 and")
3767 (should (not (python-info-continuation-line-p)))
3768 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3769 (should (python-info-continuation-line-p))
3770 (python-tests-look-at "highlight > 100:")
3771 (should (python-info-continuation-line-p))
3772 (python-tests-look-at "raise ValueError(")
3773 (should (not (python-info-continuation-line-p)))
3774 (python-tests-look-at "'sorry, you lose'")
3775 (should (python-info-continuation-line-p))
3776 (forward-line 1)
3777 (should (python-info-continuation-line-p))
3778 (python-tests-look-at ")")
3779 (should (python-info-continuation-line-p))
3780 (forward-line 1)
3781 (should (not (python-info-continuation-line-p)))))
3783 (ert-deftest python-info-block-continuation-line-p-1 ()
3784 (python-tests-with-temp-buffer
3786 if width == 0 and height == 0 and \\\\
3787 color == 'red' and emphasis == 'strong' or \\\\
3788 highlight > 100:
3789 raise ValueError(
3790 'sorry, you lose'
3794 (python-tests-look-at "if width == 0 and")
3795 (should (not (python-info-block-continuation-line-p)))
3796 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3797 (should (= (python-info-block-continuation-line-p)
3798 (python-tests-look-at "if width == 0 and" -1 t)))
3799 (python-tests-look-at "highlight > 100:")
3800 (should (not (python-info-block-continuation-line-p)))))
3802 (ert-deftest python-info-block-continuation-line-p-2 ()
3803 (python-tests-with-temp-buffer
3805 def foo(a,
3808 pass
3810 (python-tests-look-at "def foo(a,")
3811 (should (not (python-info-block-continuation-line-p)))
3812 (python-tests-look-at "b,")
3813 (should (= (python-info-block-continuation-line-p)
3814 (python-tests-look-at "def foo(a," -1 t)))
3815 (python-tests-look-at "c):")
3816 (should (not (python-info-block-continuation-line-p)))))
3818 (ert-deftest python-info-assignment-continuation-line-p-1 ()
3819 (python-tests-with-temp-buffer
3821 data = foo(), bar() \\\\
3822 baz(), 4 \\\\
3823 5, 6
3825 (python-tests-look-at "data = foo(), bar()")
3826 (should (not (python-info-assignment-continuation-line-p)))
3827 (python-tests-look-at "baz(), 4")
3828 (should (= (python-info-assignment-continuation-line-p)
3829 (python-tests-look-at "foo()," -1 t)))
3830 (python-tests-look-at "5, 6")
3831 (should (not (python-info-assignment-continuation-line-p)))))
3833 (ert-deftest python-info-assignment-continuation-line-p-2 ()
3834 (python-tests-with-temp-buffer
3836 data = (foo(), bar()
3837 baz(), 4
3838 5, 6)
3840 (python-tests-look-at "data = (foo(), bar()")
3841 (should (not (python-info-assignment-continuation-line-p)))
3842 (python-tests-look-at "baz(), 4")
3843 (should (= (python-info-assignment-continuation-line-p)
3844 (python-tests-look-at "(foo()," -1 t)))
3845 (python-tests-look-at "5, 6)")
3846 (should (not (python-info-assignment-continuation-line-p)))))
3848 (ert-deftest python-info-looking-at-beginning-of-defun-1 ()
3849 (python-tests-with-temp-buffer
3851 def decorat0r(deff):
3852 '''decorates stuff.
3854 @decorat0r
3855 def foo(arg):
3858 def wrap():
3859 deff()
3860 return wwrap
3862 (python-tests-look-at "def decorat0r(deff):")
3863 (should (python-info-looking-at-beginning-of-defun))
3864 (python-tests-look-at "def foo(arg):")
3865 (should (not (python-info-looking-at-beginning-of-defun)))
3866 (python-tests-look-at "def wrap():")
3867 (should (python-info-looking-at-beginning-of-defun))
3868 (python-tests-look-at "deff()")
3869 (should (not (python-info-looking-at-beginning-of-defun)))))
3871 (ert-deftest python-info-current-line-comment-p-1 ()
3872 (python-tests-with-temp-buffer
3874 # this is a comment
3875 foo = True # another comment
3876 '#this is a string'
3877 if foo:
3878 # more comments
3879 print ('bar') # print bar
3881 (python-tests-look-at "# this is a comment")
3882 (should (python-info-current-line-comment-p))
3883 (python-tests-look-at "foo = True # another comment")
3884 (should (not (python-info-current-line-comment-p)))
3885 (python-tests-look-at "'#this is a string'")
3886 (should (not (python-info-current-line-comment-p)))
3887 (python-tests-look-at "# more comments")
3888 (should (python-info-current-line-comment-p))
3889 (python-tests-look-at "print ('bar') # print bar")
3890 (should (not (python-info-current-line-comment-p)))))
3892 (ert-deftest python-info-current-line-empty-p ()
3893 (python-tests-with-temp-buffer
3895 # this is a comment
3897 foo = True # another comment
3899 (should (python-info-current-line-empty-p))
3900 (python-tests-look-at "# this is a comment")
3901 (should (not (python-info-current-line-empty-p)))
3902 (forward-line 1)
3903 (should (python-info-current-line-empty-p))))
3905 (ert-deftest python-info-encoding-from-cookie-1 ()
3906 "Should detect it on first line."
3907 (python-tests-with-temp-buffer
3908 "# coding=latin-1
3910 foo = True # another comment
3912 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
3914 (ert-deftest python-info-encoding-from-cookie-2 ()
3915 "Should detect it on second line."
3916 (python-tests-with-temp-buffer
3918 # coding=latin-1
3920 foo = True # another comment
3922 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
3924 (ert-deftest python-info-encoding-from-cookie-3 ()
3925 "Should not be detected on third line (and following ones)."
3926 (python-tests-with-temp-buffer
3929 # coding=latin-1
3930 foo = True # another comment
3932 (should (not (python-info-encoding-from-cookie)))))
3934 (ert-deftest python-info-encoding-from-cookie-4 ()
3935 "Should detect Emacs style."
3936 (python-tests-with-temp-buffer
3937 "# -*- coding: latin-1 -*-
3939 foo = True # another comment"
3940 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
3942 (ert-deftest python-info-encoding-from-cookie-5 ()
3943 "Should detect Vim style."
3944 (python-tests-with-temp-buffer
3945 "# vim: set fileencoding=latin-1 :
3947 foo = True # another comment"
3948 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
3950 (ert-deftest python-info-encoding-from-cookie-6 ()
3951 "First cookie wins."
3952 (python-tests-with-temp-buffer
3953 "# -*- coding: iso-8859-1 -*-
3954 # vim: set fileencoding=latin-1 :
3956 foo = True # another comment"
3957 (should (eq (python-info-encoding-from-cookie) 'iso-8859-1))))
3959 (ert-deftest python-info-encoding-from-cookie-7 ()
3960 "First cookie wins."
3961 (python-tests-with-temp-buffer
3962 "# vim: set fileencoding=latin-1 :
3963 # -*- coding: iso-8859-1 -*-
3965 foo = True # another comment"
3966 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
3968 (ert-deftest python-info-encoding-1 ()
3969 "Should return the detected encoding from cookie."
3970 (python-tests-with-temp-buffer
3971 "# vim: set fileencoding=latin-1 :
3973 foo = True # another comment"
3974 (should (eq (python-info-encoding) 'latin-1))))
3976 (ert-deftest python-info-encoding-2 ()
3977 "Should default to utf-8."
3978 (python-tests-with-temp-buffer
3979 "# No encoding for you
3981 foo = True # another comment"
3982 (should (eq (python-info-encoding) 'utf-8))))
3985 ;;; Utility functions
3987 (ert-deftest python-util-goto-line-1 ()
3988 (python-tests-with-temp-buffer
3989 (concat
3990 "# a comment
3991 # another comment
3992 def foo(a, b, c):
3993 pass" (make-string 20 ?\n))
3994 (python-util-goto-line 10)
3995 (should (= (line-number-at-pos) 10))
3996 (python-util-goto-line 20)
3997 (should (= (line-number-at-pos) 20))))
3999 (ert-deftest python-util-clone-local-variables-1 ()
4000 (let ((buffer (generate-new-buffer
4001 "python-util-clone-local-variables-1"))
4002 (varcons
4003 '((python-fill-docstring-style . django)
4004 (python-shell-interpreter . "python")
4005 (python-shell-interpreter-args . "manage.py shell")
4006 (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
4007 (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
4008 (python-shell-extra-pythonpaths "/home/user/pylib/")
4009 (python-shell-completion-setup-code
4010 . "from IPython.core.completerlib import module_completion")
4011 (python-shell-completion-string-code
4012 . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
4013 (python-shell-virtualenv-root
4014 . "/home/user/.virtualenvs/project"))))
4015 (with-current-buffer buffer
4016 (kill-all-local-variables)
4017 (dolist (ccons varcons)
4018 (set (make-local-variable (car ccons)) (cdr ccons))))
4019 (python-tests-with-temp-buffer
4021 (python-util-clone-local-variables buffer)
4022 (dolist (ccons varcons)
4023 (should
4024 (equal (symbol-value (car ccons)) (cdr ccons)))))
4025 (kill-buffer buffer)))
4027 (ert-deftest python-util-strip-string-1 ()
4028 (should (string= (python-util-strip-string "\t\r\n str") "str"))
4029 (should (string= (python-util-strip-string "str \n\r") "str"))
4030 (should (string= (python-util-strip-string "\t\r\n str \n\r ") "str"))
4031 (should
4032 (string= (python-util-strip-string "\n str \nin \tg \n\r") "str \nin \tg"))
4033 (should (string= (python-util-strip-string "\n \t \n\r ") ""))
4034 (should (string= (python-util-strip-string "") "")))
4036 (ert-deftest python-util-forward-comment-1 ()
4037 (python-tests-with-temp-buffer
4038 (concat
4039 "# a comment
4040 # another comment
4041 # bad indented comment
4042 # more comments" (make-string 9999 ?\n))
4043 (python-util-forward-comment 1)
4044 (should (= (point) (point-max)))
4045 (python-util-forward-comment -1)
4046 (should (= (point) (point-min)))))
4048 (ert-deftest python-util-valid-regexp-p-1 ()
4049 (should (python-util-valid-regexp-p ""))
4050 (should (python-util-valid-regexp-p python-shell-prompt-regexp))
4051 (should (not (python-util-valid-regexp-p "\\("))))
4054 ;;; Electricity
4056 (ert-deftest python-parens-electric-indent-1 ()
4057 (require 'electric)
4058 (let ((eim electric-indent-mode))
4059 (unwind-protect
4060 (progn
4061 (python-tests-with-temp-buffer
4063 from django.conf.urls import patterns, include, url
4065 from django.contrib import admin
4067 from myapp import views
4070 urlpatterns = patterns('',
4071 url(r'^$', views.index
4074 (electric-indent-mode 1)
4075 (python-tests-look-at "views.index")
4076 (end-of-line)
4078 ;; Inserting commas within the same line should leave
4079 ;; indentation unchanged.
4080 (python-tests-self-insert ",")
4081 (should (= (current-indentation) 4))
4083 ;; As well as any other input happening within the same
4084 ;; set of parens.
4085 (python-tests-self-insert " name='index')")
4086 (should (= (current-indentation) 4))
4088 ;; But a comma outside it, should trigger indentation.
4089 (python-tests-self-insert ",")
4090 (should (= (current-indentation) 23))
4092 ;; Newline indents to the first argument column
4093 (python-tests-self-insert "\n")
4094 (should (= (current-indentation) 23))
4096 ;; All this input must not change indentation
4097 (indent-line-to 4)
4098 (python-tests-self-insert "url(r'^/login$', views.login)")
4099 (should (= (current-indentation) 4))
4101 ;; But this comma does
4102 (python-tests-self-insert ",")
4103 (should (= (current-indentation) 23))))
4104 (or eim (electric-indent-mode -1)))))
4106 (ert-deftest python-triple-quote-pairing ()
4107 (require 'electric)
4108 (let ((epm electric-pair-mode))
4109 (unwind-protect
4110 (progn
4111 (python-tests-with-temp-buffer
4112 "\"\"\n"
4113 (or epm (electric-pair-mode 1))
4114 (goto-char (1- (point-max)))
4115 (python-tests-self-insert ?\")
4116 (should (string= (buffer-string)
4117 "\"\"\"\"\"\"\n"))
4118 (should (= (point) 4)))
4119 (python-tests-with-temp-buffer
4120 "\n"
4121 (python-tests-self-insert (list ?\" ?\" ?\"))
4122 (should (string= (buffer-string)
4123 "\"\"\"\"\"\"\n"))
4124 (should (= (point) 4)))
4125 (python-tests-with-temp-buffer
4126 "\"\n\"\"\n"
4127 (goto-char (1- (point-max)))
4128 (python-tests-self-insert ?\")
4129 (should (= (point) (1- (point-max))))
4130 (should (string= (buffer-string)
4131 "\"\n\"\"\"\n"))))
4132 (or epm (electric-pair-mode -1)))))
4135 (provide 'python-tests)
4137 ;; Local Variables:
4138 ;; coding: utf-8
4139 ;; indent-tabs-mode: nil
4140 ;; End:
4142 ;;; python-tests.el ends here