]> code.delx.au - gnu-emacs/blob - test/automated/python-tests.el
* lisp/progmodes/python.el (python-indent-post-self-insert-function):
[gnu-emacs] / test / automated / python-tests.el
1 ;;; python-tests.el --- Test suite for python.el
2
3 ;; Copyright (C) 2013-2014 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
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.
11
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.
16
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/>.
19
20 ;;; Commentary:
21
22 ;;; Code:
23
24 (require 'ert)
25 (require 'python)
26
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))
37
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))))
54
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)))))
88
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)))
106
107 \f
108 ;;; Tests for your tests, so you can test while you test.
109
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)))))
129
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)))))
145
146 \f
147 ;;; Bindings
148
149 \f
150 ;;; Python specialized rx
151
152 \f
153 ;;; Font-lock and syntax
154
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))))))
164
165 \f
166 ;;; Indentation
167
168 ;; See: http://www.python.org/dev/peps/pep-0008/#indentation
169
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)
176 "
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))))
185
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)
194 "
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))))
209
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)
217 "
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))))
229
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.
241 "
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))))
262
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.
272
273 now_we_do_mess_cause_this_is_not_a_comment = 1
274
275 # yeah, that.
276 "
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))))
306
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
310 "
311 data = {
312 'key':
313 {
314 'objlist': [
315 {
316 'pk': 1,
317 'name': 'first',
318 },
319 {
320 'pk': 2,
321 'name': 'second',
322 }
323 ]
324 }
325 }
326 "
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))))
372
373 (ert-deftest python-indent-inside-paren-2 ()
374 "Another more compact paren group style."
375 (python-tests-with-temp-buffer
376 "
377 data = {'key': {
378 'objlist': [
379 {'pk': 1,
380 'name': 'first'},
381 {'pk': 2,
382 'name': 'second'}
383 ]
384 }}
385 "
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))))
413
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
417 "
418 def foo(a, b, c=True):
419 "
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))))
425
426 (ert-deftest python-indent-after-block-2 ()
427 "A weird (malformed) multiline block statement."
428 (python-tests-with-temp-buffer
429 "
430 def foo(a, b, c={
431 'a':
432 }):
433 "
434 (goto-char (point-max))
435 (should (eq (car (python-indent-context)) 'after-beginning-of-block))
436 (should (= (python-indent-calculate-indentation) 4))))
437
438 (ert-deftest python-indent-after-backslash-1 ()
439 "The most common case."
440 (python-tests-with-temp-buffer
441 "
442 from foo.bar.baz import something, something_1 \\\\
443 something_2 something_3, \\\\
444 something_4, something_5
445 "
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))))
458
459 (ert-deftest python-indent-after-backslash-2 ()
460 "A pretty extreme complicated case."
461 (python-tests-with-temp-buffer
462 "
463 objects = Thing.objects.all() \\\\
464 .filter(
465 type='toy',
466 status='bought'
467 ) \\\\
468 .aggregate(
469 Sum('amount')
470 ) \\\\
471 .values_list()
472 "
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))))
503
504 (ert-deftest python-indent-block-enders-1 ()
505 "Test de-indentation for pass keyword."
506 (python-tests-with-temp-buffer
507 "
508 Class foo(object):
509
510 def bar(self):
511 if self.baz:
512 return (1,
513 2,
514 3)
515
516 else:
517 pass
518 "
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))))
525
526 (ert-deftest python-indent-block-enders-2 ()
527 "Test de-indentation for return keyword."
528 (python-tests-with-temp-buffer
529 "
530 Class foo(object):
531 '''raise lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
532
533 eiusmod tempor incididunt ut labore et dolore magna aliqua.
534 '''
535 def bar(self):
536 \"return (1, 2, 3).\"
537 if self.baz:
538 return (1,
539 2,
540 3)
541 "
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))))
550
551 (ert-deftest python-indent-block-enders-3 ()
552 "Test de-indentation for continue keyword."
553 (python-tests-with-temp-buffer
554 "
555 for element in lst:
556 if element is None:
557 continue
558 "
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))))
565
566 (ert-deftest python-indent-block-enders-4 ()
567 "Test de-indentation for break keyword."
568 (python-tests-with-temp-buffer
569 "
570 for element in lst:
571 if element is None:
572 break
573 "
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))))
580
581 (ert-deftest python-indent-block-enders-5 ()
582 "Test de-indentation for raise keyword."
583 (python-tests-with-temp-buffer
584 "
585 for element in lst:
586 if element is None:
587 raise ValueError('Element cannot be None')
588 "
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))))
595
596 (ert-deftest python-indent-dedenters-1 ()
597 "Test de-indentation for the elif keyword."
598 (python-tests-with-temp-buffer
599 "
600 if save:
601 try:
602 write_to_disk(data)
603 finally:
604 cleanup()
605 elif
606 "
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)))))
611
612 (ert-deftest python-indent-dedenters-2 ()
613 "Test de-indentation for the else keyword."
614 (python-tests-with-temp-buffer
615 "
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()
629 "
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)))))
634
635 (ert-deftest python-indent-dedenters-3 ()
636 "Test de-indentation for the except keyword."
637 (python-tests-with-temp-buffer
638 "
639 if save:
640 try:
641 write_to_disk(data)
642 except
643 "
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)))))
648
649 (ert-deftest python-indent-dedenters-4 ()
650 "Test de-indentation for the finally keyword."
651 (python-tests-with-temp-buffer
652 "
653 if save:
654 try:
655 write_to_disk(data)
656 finally
657 "
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)))))
662
663 (ert-deftest python-indent-dedenters-5 ()
664 "Test invalid levels are skipped in a complex example."
665 (python-tests-with-temp-buffer
666 "
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
678 "
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)))))
683
684 (ert-deftest python-indent-dedenters-6 ()
685 "Test indentation is zero when no opening block for dedenter."
686 (python-tests-with-temp-buffer
687 "
688 try:
689 # if save:
690 write_to_disk(data)
691 else
692 "
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)))))
697
698 (ert-deftest python-indent-dedenters-7 ()
699 "Test indentation case from Bug#15163."
700 (python-tests-with-temp-buffer
701 "
702 if a:
703 if b:
704 pass
705 else:
706 pass
707 else:
708 "
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)))))
713
714 (ert-deftest python-indent-electric-colon-1 ()
715 "Test indentation case from Bug#18228."
716 (python-tests-with-temp-buffer
717 "
718 def a():
719 pass
720
721 def b()
722 "
723 (python-tests-look-at "def b()")
724 (goto-char (line-end-position))
725 (python-tests-self-insert ":")
726 (should (= (current-indentation) 0))))
727
728 \f
729 ;;; Navigation
730
731 (ert-deftest python-nav-beginning-of-defun-1 ()
732 (python-tests-with-temp-buffer
733 "
734 def decoratorFunctionWithArguments(arg1, arg2, arg3):
735 '''print decorated function call data to stdout.
736
737 Usage:
738
739 @decoratorFunctionWithArguments('arg1', 'arg2')
740 def func(a, b, c=True):
741 pass
742 '''
743
744 def wwrap(f):
745 print 'Inside wwrap()'
746 def wrapped_f(*args):
747 print 'Inside wrapped_f()'
748 print 'Decorator arguments:', arg1, arg2, arg3
749 f(*args)
750 print 'After f(*args)'
751 return wrapped_f
752 return wwrap
753 "
754 (python-tests-look-at "return wrap")
755 (should (= (save-excursion
756 (python-nav-beginning-of-defun)
757 (point))
758 (save-excursion
759 (python-tests-look-at "def wrapped_f(*args):" -1)
760 (beginning-of-line)
761 (point))))
762 (python-tests-look-at "def wrapped_f(*args):" -1)
763 (should (= (save-excursion
764 (python-nav-beginning-of-defun)
765 (point))
766 (save-excursion
767 (python-tests-look-at "def wwrap(f):" -1)
768 (beginning-of-line)
769 (point))))
770 (python-tests-look-at "def wwrap(f):" -1)
771 (should (= (save-excursion
772 (python-nav-beginning-of-defun)
773 (point))
774 (save-excursion
775 (python-tests-look-at "def decoratorFunctionWithArguments" -1)
776 (beginning-of-line)
777 (point))))))
778
779 (ert-deftest python-nav-beginning-of-defun-2 ()
780 (python-tests-with-temp-buffer
781 "
782 class C(object):
783
784 def m(self):
785 self.c()
786
787 def b():
788 pass
789
790 def a():
791 pass
792
793 def c(self):
794 pass
795 "
796 ;; Nested defuns, are handled with care.
797 (python-tests-look-at "def c(self):")
798 (should (= (save-excursion
799 (python-nav-beginning-of-defun)
800 (point))
801 (save-excursion
802 (python-tests-look-at "def m(self):" -1)
803 (beginning-of-line)
804 (point))))
805 ;; Defuns on same levels should be respected.
806 (python-tests-look-at "def a():" -1)
807 (should (= (save-excursion
808 (python-nav-beginning-of-defun)
809 (point))
810 (save-excursion
811 (python-tests-look-at "def b():" -1)
812 (beginning-of-line)
813 (point))))
814 ;; Jump to a top level defun.
815 (python-tests-look-at "def b():" -1)
816 (should (= (save-excursion
817 (python-nav-beginning-of-defun)
818 (point))
819 (save-excursion
820 (python-tests-look-at "def m(self):" -1)
821 (beginning-of-line)
822 (point))))
823 ;; Jump to a top level defun again.
824 (python-tests-look-at "def m(self):" -1)
825 (should (= (save-excursion
826 (python-nav-beginning-of-defun)
827 (point))
828 (save-excursion
829 (python-tests-look-at "class C(object):" -1)
830 (beginning-of-line)
831 (point))))))
832
833 (ert-deftest python-nav-end-of-defun-1 ()
834 (python-tests-with-temp-buffer
835 "
836 class C(object):
837
838 def m(self):
839 self.c()
840
841 def b():
842 pass
843
844 def a():
845 pass
846
847 def c(self):
848 pass
849 "
850 (should (= (save-excursion
851 (python-tests-look-at "class C(object):")
852 (python-nav-end-of-defun)
853 (point))
854 (save-excursion
855 (point-max))))
856 (should (= (save-excursion
857 (python-tests-look-at "def m(self):")
858 (python-nav-end-of-defun)
859 (point))
860 (save-excursion
861 (python-tests-look-at "def c(self):")
862 (forward-line -1)
863 (point))))
864 (should (= (save-excursion
865 (python-tests-look-at "def b():")
866 (python-nav-end-of-defun)
867 (point))
868 (save-excursion
869 (python-tests-look-at "def b():")
870 (forward-line 2)
871 (point))))
872 (should (= (save-excursion
873 (python-tests-look-at "def c(self):")
874 (python-nav-end-of-defun)
875 (point))
876 (save-excursion
877 (point-max))))))
878
879 (ert-deftest python-nav-end-of-defun-2 ()
880 (python-tests-with-temp-buffer
881 "
882 def decoratorFunctionWithArguments(arg1, arg2, arg3):
883 '''print decorated function call data to stdout.
884
885 Usage:
886
887 @decoratorFunctionWithArguments('arg1', 'arg2')
888 def func(a, b, c=True):
889 pass
890 '''
891
892 def wwrap(f):
893 print 'Inside wwrap()'
894 def wrapped_f(*args):
895 print 'Inside wrapped_f()'
896 print 'Decorator arguments:', arg1, arg2, arg3
897 f(*args)
898 print 'After f(*args)'
899 return wrapped_f
900 return wwrap
901 "
902 (should (= (save-excursion
903 (python-tests-look-at "def decoratorFunctionWithArguments")
904 (python-nav-end-of-defun)
905 (point))
906 (save-excursion
907 (point-max))))
908 (should (= (save-excursion
909 (python-tests-look-at "@decoratorFunctionWithArguments")
910 (python-nav-end-of-defun)
911 (point))
912 (save-excursion
913 (point-max))))
914 (should (= (save-excursion
915 (python-tests-look-at "def wwrap(f):")
916 (python-nav-end-of-defun)
917 (point))
918 (save-excursion
919 (python-tests-look-at "return wwrap")
920 (line-beginning-position))))
921 (should (= (save-excursion
922 (python-tests-look-at "def wrapped_f(*args):")
923 (python-nav-end-of-defun)
924 (point))
925 (save-excursion
926 (python-tests-look-at "return wrapped_f")
927 (line-beginning-position))))
928 (should (= (save-excursion
929 (python-tests-look-at "f(*args)")
930 (python-nav-end-of-defun)
931 (point))
932 (save-excursion
933 (python-tests-look-at "return wrapped_f")
934 (line-beginning-position))))))
935
936 (ert-deftest python-nav-backward-defun-1 ()
937 (python-tests-with-temp-buffer
938 "
939 class A(object): # A
940
941 def a(self): # a
942 pass
943
944 def b(self): # b
945 pass
946
947 class B(object): # B
948
949 class C(object): # C
950
951 def d(self): # d
952 pass
953
954 # def e(self): # e
955 # pass
956
957 def c(self): # c
958 pass
959
960 # def d(self): # d
961 # pass
962 "
963 (goto-char (point-max))
964 (should (= (save-excursion (python-nav-backward-defun))
965 (python-tests-look-at " def c(self): # c" -1)))
966 (should (= (save-excursion (python-nav-backward-defun))
967 (python-tests-look-at " def d(self): # d" -1)))
968 (should (= (save-excursion (python-nav-backward-defun))
969 (python-tests-look-at " class C(object): # C" -1)))
970 (should (= (save-excursion (python-nav-backward-defun))
971 (python-tests-look-at " class B(object): # B" -1)))
972 (should (= (save-excursion (python-nav-backward-defun))
973 (python-tests-look-at " def b(self): # b" -1)))
974 (should (= (save-excursion (python-nav-backward-defun))
975 (python-tests-look-at " def a(self): # a" -1)))
976 (should (= (save-excursion (python-nav-backward-defun))
977 (python-tests-look-at "class A(object): # A" -1)))
978 (should (not (python-nav-backward-defun)))))
979
980 (ert-deftest python-nav-backward-defun-2 ()
981 (python-tests-with-temp-buffer
982 "
983 def decoratorFunctionWithArguments(arg1, arg2, arg3):
984 '''print decorated function call data to stdout.
985
986 Usage:
987
988 @decoratorFunctionWithArguments('arg1', 'arg2')
989 def func(a, b, c=True):
990 pass
991 '''
992
993 def wwrap(f):
994 print 'Inside wwrap()'
995 def wrapped_f(*args):
996 print 'Inside wrapped_f()'
997 print 'Decorator arguments:', arg1, arg2, arg3
998 f(*args)
999 print 'After f(*args)'
1000 return wrapped_f
1001 return wwrap
1002 "
1003 (goto-char (point-max))
1004 (should (= (save-excursion (python-nav-backward-defun))
1005 (python-tests-look-at " def wrapped_f(*args):" -1)))
1006 (should (= (save-excursion (python-nav-backward-defun))
1007 (python-tests-look-at " def wwrap(f):" -1)))
1008 (should (= (save-excursion (python-nav-backward-defun))
1009 (python-tests-look-at "def decoratorFunctionWithArguments(arg1, arg2, arg3):" -1)))
1010 (should (not (python-nav-backward-defun)))))
1011
1012 (ert-deftest python-nav-backward-defun-3 ()
1013 (python-tests-with-temp-buffer
1014 "
1015 '''
1016 def u(self):
1017 pass
1018
1019 def v(self):
1020 pass
1021
1022 def w(self):
1023 pass
1024 '''
1025
1026 class A(object):
1027 pass
1028 "
1029 (goto-char (point-min))
1030 (let ((point (python-tests-look-at "class A(object):")))
1031 (should (not (python-nav-backward-defun)))
1032 (should (= point (point))))))
1033
1034 (ert-deftest python-nav-forward-defun-1 ()
1035 (python-tests-with-temp-buffer
1036 "
1037 class A(object): # A
1038
1039 def a(self): # a
1040 pass
1041
1042 def b(self): # b
1043 pass
1044
1045 class B(object): # B
1046
1047 class C(object): # C
1048
1049 def d(self): # d
1050 pass
1051
1052 # def e(self): # e
1053 # pass
1054
1055 def c(self): # c
1056 pass
1057
1058 # def d(self): # d
1059 # pass
1060 "
1061 (goto-char (point-min))
1062 (should (= (save-excursion (python-nav-forward-defun))
1063 (python-tests-look-at "(object): # A")))
1064 (should (= (save-excursion (python-nav-forward-defun))
1065 (python-tests-look-at "(self): # a")))
1066 (should (= (save-excursion (python-nav-forward-defun))
1067 (python-tests-look-at "(self): # b")))
1068 (should (= (save-excursion (python-nav-forward-defun))
1069 (python-tests-look-at "(object): # B")))
1070 (should (= (save-excursion (python-nav-forward-defun))
1071 (python-tests-look-at "(object): # C")))
1072 (should (= (save-excursion (python-nav-forward-defun))
1073 (python-tests-look-at "(self): # d")))
1074 (should (= (save-excursion (python-nav-forward-defun))
1075 (python-tests-look-at "(self): # c")))
1076 (should (not (python-nav-forward-defun)))))
1077
1078 (ert-deftest python-nav-forward-defun-2 ()
1079 (python-tests-with-temp-buffer
1080 "
1081 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1082 '''print decorated function call data to stdout.
1083
1084 Usage:
1085
1086 @decoratorFunctionWithArguments('arg1', 'arg2')
1087 def func(a, b, c=True):
1088 pass
1089 '''
1090
1091 def wwrap(f):
1092 print 'Inside wwrap()'
1093 def wrapped_f(*args):
1094 print 'Inside wrapped_f()'
1095 print 'Decorator arguments:', arg1, arg2, arg3
1096 f(*args)
1097 print 'After f(*args)'
1098 return wrapped_f
1099 return wwrap
1100 "
1101 (goto-char (point-min))
1102 (should (= (save-excursion (python-nav-forward-defun))
1103 (python-tests-look-at "(arg1, arg2, arg3):")))
1104 (should (= (save-excursion (python-nav-forward-defun))
1105 (python-tests-look-at "(f):")))
1106 (should (= (save-excursion (python-nav-forward-defun))
1107 (python-tests-look-at "(*args):")))
1108 (should (not (python-nav-forward-defun)))))
1109
1110 (ert-deftest python-nav-forward-defun-3 ()
1111 (python-tests-with-temp-buffer
1112 "
1113 class A(object):
1114 pass
1115
1116 '''
1117 def u(self):
1118 pass
1119
1120 def v(self):
1121 pass
1122
1123 def w(self):
1124 pass
1125 '''
1126 "
1127 (goto-char (point-min))
1128 (let ((point (python-tests-look-at "(object):")))
1129 (should (not (python-nav-forward-defun)))
1130 (should (= point (point))))))
1131
1132 (ert-deftest python-nav-beginning-of-statement-1 ()
1133 (python-tests-with-temp-buffer
1134 "
1135 v1 = 123 + \
1136 456 + \
1137 789
1138 v2 = (value1,
1139 value2,
1140
1141 value3,
1142 value4)
1143 v3 = ('this is a string'
1144
1145 'that is continued'
1146 'between lines'
1147 'within a paren',
1148 # this is a comment, yo
1149 'continue previous line')
1150 v4 = '''
1151 a very long
1152 string
1153 '''
1154 "
1155 (python-tests-look-at "v2 =")
1156 (python-util-forward-comment -1)
1157 (should (= (save-excursion
1158 (python-nav-beginning-of-statement)
1159 (point))
1160 (python-tests-look-at "v1 =" -1 t)))
1161 (python-tests-look-at "v3 =")
1162 (python-util-forward-comment -1)
1163 (should (= (save-excursion
1164 (python-nav-beginning-of-statement)
1165 (point))
1166 (python-tests-look-at "v2 =" -1 t)))
1167 (python-tests-look-at "v4 =")
1168 (python-util-forward-comment -1)
1169 (should (= (save-excursion
1170 (python-nav-beginning-of-statement)
1171 (point))
1172 (python-tests-look-at "v3 =" -1 t)))
1173 (goto-char (point-max))
1174 (python-util-forward-comment -1)
1175 (should (= (save-excursion
1176 (python-nav-beginning-of-statement)
1177 (point))
1178 (python-tests-look-at "v4 =" -1 t)))))
1179
1180 (ert-deftest python-nav-end-of-statement-1 ()
1181 (python-tests-with-temp-buffer
1182 "
1183 v1 = 123 + \
1184 456 + \
1185 789
1186 v2 = (value1,
1187 value2,
1188
1189 value3,
1190 value4)
1191 v3 = ('this is a string'
1192
1193 'that is continued'
1194 'between lines'
1195 'within a paren',
1196 # this is a comment, yo
1197 'continue previous line')
1198 v4 = '''
1199 a very long
1200 string
1201 '''
1202 "
1203 (python-tests-look-at "v1 =")
1204 (should (= (save-excursion
1205 (python-nav-end-of-statement)
1206 (point))
1207 (save-excursion
1208 (python-tests-look-at "789")
1209 (line-end-position))))
1210 (python-tests-look-at "v2 =")
1211 (should (= (save-excursion
1212 (python-nav-end-of-statement)
1213 (point))
1214 (save-excursion
1215 (python-tests-look-at "value4)")
1216 (line-end-position))))
1217 (python-tests-look-at "v3 =")
1218 (should (= (save-excursion
1219 (python-nav-end-of-statement)
1220 (point))
1221 (save-excursion
1222 (python-tests-look-at
1223 "'continue previous line')")
1224 (line-end-position))))
1225 (python-tests-look-at "v4 =")
1226 (should (= (save-excursion
1227 (python-nav-end-of-statement)
1228 (point))
1229 (save-excursion
1230 (goto-char (point-max))
1231 (python-util-forward-comment -1)
1232 (point))))))
1233
1234 (ert-deftest python-nav-forward-statement-1 ()
1235 (python-tests-with-temp-buffer
1236 "
1237 v1 = 123 + \
1238 456 + \
1239 789
1240 v2 = (value1,
1241 value2,
1242
1243 value3,
1244 value4)
1245 v3 = ('this is a string'
1246
1247 'that is continued'
1248 'between lines'
1249 'within a paren',
1250 # this is a comment, yo
1251 'continue previous line')
1252 v4 = '''
1253 a very long
1254 string
1255 '''
1256 "
1257 (python-tests-look-at "v1 =")
1258 (should (= (save-excursion
1259 (python-nav-forward-statement)
1260 (point))
1261 (python-tests-look-at "v2 =")))
1262 (should (= (save-excursion
1263 (python-nav-forward-statement)
1264 (point))
1265 (python-tests-look-at "v3 =")))
1266 (should (= (save-excursion
1267 (python-nav-forward-statement)
1268 (point))
1269 (python-tests-look-at "v4 =")))
1270 (should (= (save-excursion
1271 (python-nav-forward-statement)
1272 (point))
1273 (point-max)))))
1274
1275 (ert-deftest python-nav-backward-statement-1 ()
1276 (python-tests-with-temp-buffer
1277 "
1278 v1 = 123 + \
1279 456 + \
1280 789
1281 v2 = (value1,
1282 value2,
1283
1284 value3,
1285 value4)
1286 v3 = ('this is a string'
1287
1288 'that is continued'
1289 'between lines'
1290 'within a paren',
1291 # this is a comment, yo
1292 'continue previous line')
1293 v4 = '''
1294 a very long
1295 string
1296 '''
1297 "
1298 (goto-char (point-max))
1299 (should (= (save-excursion
1300 (python-nav-backward-statement)
1301 (point))
1302 (python-tests-look-at "v4 =" -1)))
1303 (should (= (save-excursion
1304 (python-nav-backward-statement)
1305 (point))
1306 (python-tests-look-at "v3 =" -1)))
1307 (should (= (save-excursion
1308 (python-nav-backward-statement)
1309 (point))
1310 (python-tests-look-at "v2 =" -1)))
1311 (should (= (save-excursion
1312 (python-nav-backward-statement)
1313 (point))
1314 (python-tests-look-at "v1 =" -1)))))
1315
1316 (ert-deftest python-nav-backward-statement-2 ()
1317 :expected-result :failed
1318 (python-tests-with-temp-buffer
1319 "
1320 v1 = 123 + \
1321 456 + \
1322 789
1323 v2 = (value1,
1324 value2,
1325
1326 value3,
1327 value4)
1328 "
1329 ;; FIXME: For some reason `python-nav-backward-statement' is moving
1330 ;; back two sentences when starting from 'value4)'.
1331 (goto-char (point-max))
1332 (python-util-forward-comment -1)
1333 (should (= (save-excursion
1334 (python-nav-backward-statement)
1335 (point))
1336 (python-tests-look-at "v2 =" -1 t)))))
1337
1338 (ert-deftest python-nav-beginning-of-block-1 ()
1339 (python-tests-with-temp-buffer
1340 "
1341 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1342 '''print decorated function call data to stdout.
1343
1344 Usage:
1345
1346 @decoratorFunctionWithArguments('arg1', 'arg2')
1347 def func(a, b, c=True):
1348 pass
1349 '''
1350
1351 def wwrap(f):
1352 print 'Inside wwrap()'
1353 def wrapped_f(*args):
1354 print 'Inside wrapped_f()'
1355 print 'Decorator arguments:', arg1, arg2, arg3
1356 f(*args)
1357 print 'After f(*args)'
1358 return wrapped_f
1359 return wwrap
1360 "
1361 (python-tests-look-at "return wwrap")
1362 (should (= (save-excursion
1363 (python-nav-beginning-of-block)
1364 (point))
1365 (python-tests-look-at "def decoratorFunctionWithArguments" -1)))
1366 (python-tests-look-at "print 'Inside wwrap()'")
1367 (should (= (save-excursion
1368 (python-nav-beginning-of-block)
1369 (point))
1370 (python-tests-look-at "def wwrap(f):" -1)))
1371 (python-tests-look-at "print 'After f(*args)'")
1372 (end-of-line)
1373 (should (= (save-excursion
1374 (python-nav-beginning-of-block)
1375 (point))
1376 (python-tests-look-at "def wrapped_f(*args):" -1)))
1377 (python-tests-look-at "return wrapped_f")
1378 (should (= (save-excursion
1379 (python-nav-beginning-of-block)
1380 (point))
1381 (python-tests-look-at "def wwrap(f):" -1)))))
1382
1383 (ert-deftest python-nav-end-of-block-1 ()
1384 (python-tests-with-temp-buffer
1385 "
1386 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1387 '''print decorated function call data to stdout.
1388
1389 Usage:
1390
1391 @decoratorFunctionWithArguments('arg1', 'arg2')
1392 def func(a, b, c=True):
1393 pass
1394 '''
1395
1396 def wwrap(f):
1397 print 'Inside wwrap()'
1398 def wrapped_f(*args):
1399 print 'Inside wrapped_f()'
1400 print 'Decorator arguments:', arg1, arg2, arg3
1401 f(*args)
1402 print 'After f(*args)'
1403 return wrapped_f
1404 return wwrap
1405 "
1406 (python-tests-look-at "def decoratorFunctionWithArguments")
1407 (should (= (save-excursion
1408 (python-nav-end-of-block)
1409 (point))
1410 (save-excursion
1411 (goto-char (point-max))
1412 (python-util-forward-comment -1)
1413 (point))))
1414 (python-tests-look-at "def wwrap(f):")
1415 (should (= (save-excursion
1416 (python-nav-end-of-block)
1417 (point))
1418 (save-excursion
1419 (python-tests-look-at "return wrapped_f")
1420 (line-end-position))))
1421 (end-of-line)
1422 (should (= (save-excursion
1423 (python-nav-end-of-block)
1424 (point))
1425 (save-excursion
1426 (python-tests-look-at "return wrapped_f")
1427 (line-end-position))))
1428 (python-tests-look-at "f(*args)")
1429 (should (= (save-excursion
1430 (python-nav-end-of-block)
1431 (point))
1432 (save-excursion
1433 (python-tests-look-at "print 'After f(*args)'")
1434 (line-end-position))))))
1435
1436 (ert-deftest python-nav-forward-block-1 ()
1437 "This also accounts as a test for `python-nav-backward-block'."
1438 (python-tests-with-temp-buffer
1439 "
1440 if request.user.is_authenticated():
1441 # def block():
1442 # pass
1443 try:
1444 profile = request.user.get_profile()
1445 except Profile.DoesNotExist:
1446 profile = Profile.objects.create(user=request.user)
1447 else:
1448 if profile.stats:
1449 profile.recalculate_stats()
1450 else:
1451 profile.clear_stats()
1452 finally:
1453 profile.views += 1
1454 profile.save()
1455 "
1456 (should (= (save-excursion (python-nav-forward-block))
1457 (python-tests-look-at "if request.user.is_authenticated():")))
1458 (should (= (save-excursion (python-nav-forward-block))
1459 (python-tests-look-at "try:")))
1460 (should (= (save-excursion (python-nav-forward-block))
1461 (python-tests-look-at "except Profile.DoesNotExist:")))
1462 (should (= (save-excursion (python-nav-forward-block))
1463 (python-tests-look-at "else:")))
1464 (should (= (save-excursion (python-nav-forward-block))
1465 (python-tests-look-at "if profile.stats:")))
1466 (should (= (save-excursion (python-nav-forward-block))
1467 (python-tests-look-at "else:")))
1468 (should (= (save-excursion (python-nav-forward-block))
1469 (python-tests-look-at "finally:")))
1470 ;; When point is at the last block, leave it there and return nil
1471 (should (not (save-excursion (python-nav-forward-block))))
1472 ;; Move backwards, and even if the number of moves is less than the
1473 ;; provided argument return the point.
1474 (should (= (save-excursion (python-nav-forward-block -10))
1475 (python-tests-look-at
1476 "if request.user.is_authenticated():" -1)))))
1477
1478 (ert-deftest python-nav-forward-sexp-1 ()
1479 (python-tests-with-temp-buffer
1480 "
1481 a()
1482 b()
1483 c()
1484 "
1485 (python-tests-look-at "a()")
1486 (python-nav-forward-sexp)
1487 (should (looking-at "$"))
1488 (should (save-excursion
1489 (beginning-of-line)
1490 (looking-at "a()")))
1491 (python-nav-forward-sexp)
1492 (should (looking-at "$"))
1493 (should (save-excursion
1494 (beginning-of-line)
1495 (looking-at "b()")))
1496 (python-nav-forward-sexp)
1497 (should (looking-at "$"))
1498 (should (save-excursion
1499 (beginning-of-line)
1500 (looking-at "c()")))
1501 ;; Movement next to a paren should do what lisp does and
1502 ;; unfortunately It can't change, because otherwise
1503 ;; `blink-matching-open' breaks.
1504 (python-nav-forward-sexp -1)
1505 (should (looking-at "()"))
1506 (should (save-excursion
1507 (beginning-of-line)
1508 (looking-at "c()")))
1509 (python-nav-forward-sexp -1)
1510 (should (looking-at "c()"))
1511 (python-nav-forward-sexp -1)
1512 (should (looking-at "b()"))
1513 (python-nav-forward-sexp -1)
1514 (should (looking-at "a()"))))
1515
1516 (ert-deftest python-nav-forward-sexp-2 ()
1517 (python-tests-with-temp-buffer
1518 "
1519 def func():
1520 if True:
1521 aaa = bbb
1522 ccc = ddd
1523 eee = fff
1524 return ggg
1525 "
1526 (python-tests-look-at "aa =")
1527 (python-nav-forward-sexp)
1528 (should (looking-at " = bbb"))
1529 (python-nav-forward-sexp)
1530 (should (looking-at "$"))
1531 (should (save-excursion
1532 (back-to-indentation)
1533 (looking-at "aaa = bbb")))
1534 (python-nav-forward-sexp)
1535 (should (looking-at "$"))
1536 (should (save-excursion
1537 (back-to-indentation)
1538 (looking-at "ccc = ddd")))
1539 (python-nav-forward-sexp)
1540 (should (looking-at "$"))
1541 (should (save-excursion
1542 (back-to-indentation)
1543 (looking-at "eee = fff")))
1544 (python-nav-forward-sexp)
1545 (should (looking-at "$"))
1546 (should (save-excursion
1547 (back-to-indentation)
1548 (looking-at "return ggg")))
1549 (python-nav-forward-sexp -1)
1550 (should (looking-at "def func():"))))
1551
1552 (ert-deftest python-nav-forward-sexp-3 ()
1553 (python-tests-with-temp-buffer
1554 "
1555 from some_module import some_sub_module
1556 from another_module import another_sub_module
1557
1558 def another_statement():
1559 pass
1560 "
1561 (python-tests-look-at "some_module")
1562 (python-nav-forward-sexp)
1563 (should (looking-at " import"))
1564 (python-nav-forward-sexp)
1565 (should (looking-at " some_sub_module"))
1566 (python-nav-forward-sexp)
1567 (should (looking-at "$"))
1568 (should
1569 (save-excursion
1570 (back-to-indentation)
1571 (looking-at
1572 "from some_module import some_sub_module")))
1573 (python-nav-forward-sexp)
1574 (should (looking-at "$"))
1575 (should
1576 (save-excursion
1577 (back-to-indentation)
1578 (looking-at
1579 "from another_module import another_sub_module")))
1580 (python-nav-forward-sexp)
1581 (should (looking-at "$"))
1582 (should
1583 (save-excursion
1584 (back-to-indentation)
1585 (looking-at
1586 "pass")))
1587 (python-nav-forward-sexp -1)
1588 (should (looking-at "def another_statement():"))
1589 (python-nav-forward-sexp -1)
1590 (should (looking-at "from another_module import another_sub_module"))
1591 (python-nav-forward-sexp -1)
1592 (should (looking-at "from some_module import some_sub_module"))))
1593
1594 (ert-deftest python-nav-forward-sexp-safe-1 ()
1595 (python-tests-with-temp-buffer
1596 "
1597 profile = Profile.objects.create(user=request.user)
1598 profile.notify()
1599 "
1600 (python-tests-look-at "profile =")
1601 (python-nav-forward-sexp-safe 1)
1602 (should (looking-at "$"))
1603 (beginning-of-line 1)
1604 (python-tests-look-at "user=request.user")
1605 (python-nav-forward-sexp-safe -1)
1606 (should (looking-at "(user=request.user)"))
1607 (python-nav-forward-sexp-safe -4)
1608 (should (looking-at "profile ="))
1609 (python-tests-look-at "user=request.user")
1610 (python-nav-forward-sexp-safe 3)
1611 (should (looking-at ")"))
1612 (python-nav-forward-sexp-safe 1)
1613 (should (looking-at "$"))
1614 (python-nav-forward-sexp-safe 1)
1615 (should (looking-at "$"))))
1616
1617 (ert-deftest python-nav-up-list-1 ()
1618 (python-tests-with-temp-buffer
1619 "
1620 def f():
1621 if True:
1622 return [i for i in range(3)]
1623 "
1624 (python-tests-look-at "3)]")
1625 (python-nav-up-list)
1626 (should (looking-at "]"))
1627 (python-nav-up-list)
1628 (should (looking-at "$"))))
1629
1630 (ert-deftest python-nav-backward-up-list-1 ()
1631 :expected-result :failed
1632 (python-tests-with-temp-buffer
1633 "
1634 def f():
1635 if True:
1636 return [i for i in range(3)]
1637 "
1638 (python-tests-look-at "3)]")
1639 (python-nav-backward-up-list)
1640 (should (looking-at "(3)\\]"))
1641 (python-nav-backward-up-list)
1642 (should (looking-at
1643 "\\[i for i in range(3)\\]"))
1644 ;; FIXME: Need to move to beginning-of-statement.
1645 (python-nav-backward-up-list)
1646 (should (looking-at
1647 "return \\[i for i in range(3)\\]"))
1648 (python-nav-backward-up-list)
1649 (should (looking-at "if True:"))
1650 (python-nav-backward-up-list)
1651 (should (looking-at "def f():"))))
1652
1653 \f
1654 ;;; Shell integration
1655
1656 (defvar python-tests-shell-interpreter "python")
1657
1658 (ert-deftest python-shell-get-process-name-1 ()
1659 "Check process name calculation on different scenarios."
1660 (python-tests-with-temp-buffer
1661 ""
1662 (should (string= (python-shell-get-process-name nil)
1663 python-shell-buffer-name))
1664 ;; When the `current-buffer' doesn't have `buffer-file-name', even
1665 ;; if dedicated flag is non-nil should not include its name.
1666 (should (string= (python-shell-get-process-name t)
1667 python-shell-buffer-name)))
1668 (python-tests-with-temp-file
1669 ""
1670 ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
1671 ;; should be respected.
1672 (should (string= (python-shell-get-process-name nil)
1673 python-shell-buffer-name))
1674 (should (string=
1675 (python-shell-get-process-name t)
1676 (format "%s[%s]" python-shell-buffer-name buffer-file-name)))))
1677
1678 (ert-deftest python-shell-internal-get-process-name-1 ()
1679 "Check the internal process name is config-unique."
1680 (let* ((python-shell-interpreter python-tests-shell-interpreter)
1681 (python-shell-interpreter-args "")
1682 (python-shell-prompt-regexp ">>> ")
1683 (python-shell-prompt-block-regexp "[.][.][.] ")
1684 (python-shell-setup-codes "")
1685 (python-shell-process-environment "")
1686 (python-shell-extra-pythonpaths "")
1687 (python-shell-exec-path "")
1688 (python-shell-virtualenv-path "")
1689 (expected (python-tests-with-temp-buffer
1690 "" (python-shell-internal-get-process-name))))
1691 ;; Same configurations should match.
1692 (should
1693 (string= expected
1694 (python-tests-with-temp-buffer
1695 "" (python-shell-internal-get-process-name))))
1696 (let ((python-shell-interpreter-args "-B"))
1697 ;; A minimal change should generate different names.
1698 (should
1699 (not (string=
1700 expected
1701 (python-tests-with-temp-buffer
1702 "" (python-shell-internal-get-process-name))))))))
1703
1704 (ert-deftest python-shell-parse-command-1 ()
1705 "Check the command to execute is calculated correctly.
1706 Using `python-shell-interpreter' and
1707 `python-shell-interpreter-args'."
1708 (skip-unless (executable-find python-tests-shell-interpreter))
1709 (let ((python-shell-interpreter (executable-find
1710 python-tests-shell-interpreter))
1711 (python-shell-interpreter-args "-B"))
1712 (should (string=
1713 (format "%s %s"
1714 python-shell-interpreter
1715 python-shell-interpreter-args)
1716 (python-shell-parse-command)))))
1717
1718 (ert-deftest python-shell-calculate-process-environment-1 ()
1719 "Test `python-shell-process-environment' modification."
1720 (let* ((original-process-environment process-environment)
1721 (python-shell-process-environment
1722 '("TESTVAR1=value1" "TESTVAR2=value2"))
1723 (process-environment
1724 (python-shell-calculate-process-environment)))
1725 (should (equal (getenv "TESTVAR1") "value1"))
1726 (should (equal (getenv "TESTVAR2") "value2"))))
1727
1728 (ert-deftest python-shell-calculate-process-environment-2 ()
1729 "Test `python-shell-extra-pythonpaths' modification."
1730 (let* ((original-process-environment process-environment)
1731 (original-pythonpath (getenv "PYTHONPATH"))
1732 (paths '("path1" "path2"))
1733 (python-shell-extra-pythonpaths paths)
1734 (process-environment
1735 (python-shell-calculate-process-environment)))
1736 (should (equal (getenv "PYTHONPATH")
1737 (concat
1738 (mapconcat 'identity paths path-separator)
1739 path-separator original-pythonpath)))))
1740
1741 (ert-deftest python-shell-calculate-process-environment-3 ()
1742 "Test `python-shell-virtualenv-path' modification."
1743 (let* ((original-process-environment process-environment)
1744 (original-path (or (getenv "PATH") ""))
1745 (python-shell-virtualenv-path
1746 (directory-file-name user-emacs-directory))
1747 (process-environment
1748 (python-shell-calculate-process-environment)))
1749 (should (not (getenv "PYTHONHOME")))
1750 (should (string= (getenv "VIRTUAL_ENV") python-shell-virtualenv-path))
1751 (should (equal (getenv "PATH")
1752 (format "%s/bin%s%s"
1753 python-shell-virtualenv-path
1754 path-separator original-path)))))
1755
1756 (ert-deftest python-shell-calculate-exec-path-1 ()
1757 "Test `python-shell-exec-path' modification."
1758 (let* ((original-exec-path exec-path)
1759 (python-shell-exec-path '("path1" "path2"))
1760 (exec-path (python-shell-calculate-exec-path)))
1761 (should (equal
1762 exec-path
1763 (append python-shell-exec-path
1764 original-exec-path)))))
1765
1766 (ert-deftest python-shell-calculate-exec-path-2 ()
1767 "Test `python-shell-exec-path' modification."
1768 (let* ((original-exec-path exec-path)
1769 (python-shell-virtualenv-path
1770 (directory-file-name (expand-file-name user-emacs-directory)))
1771 (exec-path (python-shell-calculate-exec-path)))
1772 (should (equal
1773 exec-path
1774 (append (cons
1775 (format "%s/bin" python-shell-virtualenv-path)
1776 original-exec-path))))))
1777
1778 (ert-deftest python-shell-make-comint-1 ()
1779 "Check comint creation for global shell buffer."
1780 (skip-unless (executable-find python-tests-shell-interpreter))
1781 ;; The interpreter can get killed too quickly to allow it to clean
1782 ;; up the tempfiles that the default python-shell-setup-codes create,
1783 ;; so it leaves tempfiles behind, which is a minor irritation.
1784 (let* ((python-shell-setup-codes nil)
1785 (python-shell-interpreter
1786 (executable-find python-tests-shell-interpreter))
1787 (proc-name (python-shell-get-process-name nil))
1788 (shell-buffer
1789 (python-tests-with-temp-buffer
1790 "" (python-shell-make-comint
1791 (python-shell-parse-command) proc-name)))
1792 (process (get-buffer-process shell-buffer)))
1793 (unwind-protect
1794 (progn
1795 (set-process-query-on-exit-flag process nil)
1796 (should (process-live-p process))
1797 (with-current-buffer shell-buffer
1798 (should (eq major-mode 'inferior-python-mode))
1799 (should (string= (buffer-name) (format "*%s*" proc-name)))))
1800 (kill-buffer shell-buffer))))
1801
1802 (ert-deftest python-shell-make-comint-2 ()
1803 "Check comint creation for internal shell buffer."
1804 (skip-unless (executable-find python-tests-shell-interpreter))
1805 (let* ((python-shell-setup-codes nil)
1806 (python-shell-interpreter
1807 (executable-find python-tests-shell-interpreter))
1808 (proc-name (python-shell-internal-get-process-name))
1809 (shell-buffer
1810 (python-tests-with-temp-buffer
1811 "" (python-shell-make-comint
1812 (python-shell-parse-command) proc-name nil t)))
1813 (process (get-buffer-process shell-buffer)))
1814 (unwind-protect
1815 (progn
1816 (set-process-query-on-exit-flag process nil)
1817 (should (process-live-p process))
1818 (with-current-buffer shell-buffer
1819 (should (eq major-mode 'inferior-python-mode))
1820 (should (string= (buffer-name) (format " *%s*" proc-name)))))
1821 (kill-buffer shell-buffer))))
1822
1823 (ert-deftest python-shell-make-comint-3 ()
1824 "Check comint creation with overridden python interpreter and args.
1825 The command passed to `python-shell-make-comint' as argument must
1826 locally override global values set in `python-shell-interpreter'
1827 and `python-shell-interpreter-args' in the new shell buffer."
1828 (skip-unless (executable-find python-tests-shell-interpreter))
1829 (let* ((python-shell-setup-codes nil)
1830 (python-shell-interpreter "interpreter")
1831 (python-shell-interpreter-args "--some-args")
1832 (proc-name (python-shell-get-process-name nil))
1833 (interpreter-override
1834 (concat (executable-find python-tests-shell-interpreter) " " "-i"))
1835 (shell-buffer
1836 (python-tests-with-temp-buffer
1837 "" (python-shell-make-comint interpreter-override proc-name nil)))
1838 (process (get-buffer-process shell-buffer)))
1839 (unwind-protect
1840 (progn
1841 (set-process-query-on-exit-flag process nil)
1842 (should (process-live-p process))
1843 (with-current-buffer shell-buffer
1844 (should (eq major-mode 'inferior-python-mode))
1845 (should (string= python-shell-interpreter
1846 (executable-find python-tests-shell-interpreter)))
1847 (should (string= python-shell-interpreter-args "-i"))))
1848 (kill-buffer shell-buffer))))
1849
1850 (ert-deftest python-shell-make-comint-4 ()
1851 "Check shell calculated prompts regexps are set."
1852 (skip-unless (executable-find python-tests-shell-interpreter))
1853 (let* ((process-environment process-environment)
1854 (python-shell-setup-codes nil)
1855 (python-shell-interpreter
1856 (executable-find python-tests-shell-interpreter))
1857 (python-shell-interpreter-args "-i")
1858 (python-shell--prompt-calculated-input-regexp nil)
1859 (python-shell--prompt-calculated-output-regexp nil)
1860 (python-shell-prompt-detect-enabled t)
1861 (python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
1862 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
1863 (python-shell-prompt-regexp "in")
1864 (python-shell-prompt-block-regexp "block")
1865 (python-shell-prompt-pdb-regexp "pdf")
1866 (python-shell-prompt-output-regexp "output")
1867 (startup-code (concat "import sys\n"
1868 "sys.ps1 = 'py> '\n"
1869 "sys.ps2 = '..> '\n"
1870 "sys.ps3 = 'out '\n"))
1871 (startup-file (python-shell--save-temp-file startup-code))
1872 (proc-name (python-shell-get-process-name nil))
1873 (shell-buffer
1874 (progn
1875 (setenv "PYTHONSTARTUP" startup-file)
1876 (python-tests-with-temp-buffer
1877 "" (python-shell-make-comint
1878 (python-shell-parse-command) proc-name nil))))
1879 (process (get-buffer-process shell-buffer)))
1880 (unwind-protect
1881 (progn
1882 (set-process-query-on-exit-flag process nil)
1883 (should (process-live-p process))
1884 (with-current-buffer shell-buffer
1885 (should (eq major-mode 'inferior-python-mode))
1886 (should (string=
1887 python-shell--prompt-calculated-input-regexp
1888 (concat "^\\(extralargeinputprompt\\|\\.\\.> \\|"
1889 "block\\|py> \\|pdf\\|sml\\|in\\)")))
1890 (should (string=
1891 python-shell--prompt-calculated-output-regexp
1892 "^\\(extralargeoutputprompt\\|output\\|out \\|sml\\)"))))
1893 (delete-file startup-file)
1894 (kill-buffer shell-buffer))))
1895
1896 (ert-deftest python-shell-get-process-1 ()
1897 "Check dedicated shell process preference over global."
1898 (skip-unless (executable-find python-tests-shell-interpreter))
1899 (python-tests-with-temp-file
1900 ""
1901 (let* ((python-shell-setup-codes nil)
1902 (python-shell-interpreter
1903 (executable-find python-tests-shell-interpreter))
1904 (global-proc-name (python-shell-get-process-name nil))
1905 (dedicated-proc-name (python-shell-get-process-name t))
1906 (global-shell-buffer
1907 (python-shell-make-comint
1908 (python-shell-parse-command) global-proc-name))
1909 (dedicated-shell-buffer
1910 (python-shell-make-comint
1911 (python-shell-parse-command) dedicated-proc-name))
1912 (global-process (get-buffer-process global-shell-buffer))
1913 (dedicated-process (get-buffer-process dedicated-shell-buffer)))
1914 (unwind-protect
1915 (progn
1916 (set-process-query-on-exit-flag global-process nil)
1917 (set-process-query-on-exit-flag dedicated-process nil)
1918 ;; Prefer dedicated if global also exists.
1919 (should (equal (python-shell-get-process) dedicated-process))
1920 (kill-buffer dedicated-shell-buffer)
1921 ;; If there's only global, use it.
1922 (should (equal (python-shell-get-process) global-process))
1923 (kill-buffer global-shell-buffer)
1924 ;; No buffer available.
1925 (should (not (python-shell-get-process))))
1926 (ignore-errors (kill-buffer global-shell-buffer))
1927 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
1928
1929 (ert-deftest python-shell-get-or-create-process-1 ()
1930 "Check shell dedicated process creation."
1931 (skip-unless (executable-find python-tests-shell-interpreter))
1932 (python-tests-with-temp-file
1933 ""
1934 (let* ((python-shell-interpreter
1935 (executable-find python-tests-shell-interpreter))
1936 (use-dialog-box)
1937 (dedicated-process-name (python-shell-get-process-name t))
1938 (dedicated-process
1939 (python-shell-get-or-create-process python-shell-interpreter t))
1940 (dedicated-shell-buffer (process-buffer dedicated-process)))
1941 (unwind-protect
1942 (progn
1943 (set-process-query-on-exit-flag dedicated-process nil)
1944 ;; should be dedicated.
1945 (should (equal (process-name dedicated-process)
1946 dedicated-process-name))
1947 (kill-buffer dedicated-shell-buffer)
1948 ;; Check there are no processes for current buffer.
1949 (should (not (python-shell-get-process))))
1950 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
1951
1952 (ert-deftest python-shell-get-or-create-process-2 ()
1953 "Check shell global process creation."
1954 (skip-unless (executable-find python-tests-shell-interpreter))
1955 (python-tests-with-temp-file
1956 ""
1957 (let* ((python-shell-interpreter
1958 (executable-find python-tests-shell-interpreter))
1959 (use-dialog-box)
1960 (process-name (python-shell-get-process-name nil))
1961 (process
1962 (python-shell-get-or-create-process python-shell-interpreter))
1963 (shell-buffer (process-buffer process)))
1964 (unwind-protect
1965 (progn
1966 (set-process-query-on-exit-flag process nil)
1967 ;; should be global.
1968 (should (equal (process-name process) process-name))
1969 (kill-buffer shell-buffer)
1970 ;; Check there are no processes for current buffer.
1971 (should (not (python-shell-get-process))))
1972 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
1973
1974 (ert-deftest python-shell-get-or-create-process-3 ()
1975 "Check shell dedicated/global process preference."
1976 (skip-unless (executable-find python-tests-shell-interpreter))
1977 (python-tests-with-temp-file
1978 ""
1979 (let* ((python-shell-interpreter
1980 (executable-find python-tests-shell-interpreter))
1981 (use-dialog-box)
1982 (dedicated-process-name (python-shell-get-process-name t))
1983 (global-process)
1984 (dedicated-process))
1985 (unwind-protect
1986 (progn
1987 ;; Create global process
1988 (run-python python-shell-interpreter nil)
1989 (setq global-process (get-buffer-process "*Python*"))
1990 (should global-process)
1991 (set-process-query-on-exit-flag global-process nil)
1992 ;; Create dedicated process
1993 (run-python python-shell-interpreter t)
1994 (setq dedicated-process (get-process dedicated-process-name))
1995 (should dedicated-process)
1996 (set-process-query-on-exit-flag dedicated-process nil)
1997 ;; Prefer dedicated.
1998 (should (equal (python-shell-get-or-create-process)
1999 dedicated-process))
2000 ;; Kill the dedicated so the global takes over.
2001 (kill-buffer (process-buffer dedicated-process))
2002 ;; Detect global.
2003 (should (equal (python-shell-get-or-create-process) global-process))
2004 ;; Kill the global.
2005 (kill-buffer (process-buffer global-process))
2006 ;; Check there are no processes for current buffer.
2007 (should (not (python-shell-get-process))))
2008 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2009
2010 (ert-deftest python-shell-internal-get-or-create-process-1 ()
2011 "Check internal shell process creation fallback."
2012 (skip-unless (executable-find python-tests-shell-interpreter))
2013 (python-tests-with-temp-file
2014 ""
2015 (should (not (process-live-p (python-shell-internal-get-process-name))))
2016 (let* ((python-shell-interpreter
2017 (executable-find python-tests-shell-interpreter))
2018 (internal-process-name (python-shell-internal-get-process-name))
2019 (internal-process (python-shell-internal-get-or-create-process))
2020 (internal-shell-buffer (process-buffer internal-process)))
2021 (unwind-protect
2022 (progn
2023 (set-process-query-on-exit-flag internal-process nil)
2024 (should (equal (process-name internal-process)
2025 internal-process-name))
2026 (should (equal internal-process
2027 (python-shell-internal-get-or-create-process)))
2028 ;; Assert the internal process is not a user process
2029 (should (not (python-shell-get-process)))
2030 (kill-buffer internal-shell-buffer))
2031 (ignore-errors (kill-buffer internal-shell-buffer))))))
2032
2033 (ert-deftest python-shell-prompt-detect-1 ()
2034 "Check prompt autodetection."
2035 (skip-unless (executable-find python-tests-shell-interpreter))
2036 (let ((process-environment process-environment))
2037 ;; Ensure no startup file is enabled
2038 (setenv "PYTHONSTARTUP" "")
2039 (should python-shell-prompt-detect-enabled)
2040 (should (equal (python-shell-prompt-detect) '(">>> " "... " "")))))
2041
2042 (ert-deftest python-shell-prompt-detect-2 ()
2043 "Check prompt autodetection with startup file. Bug#17370."
2044 (skip-unless (executable-find python-tests-shell-interpreter))
2045 (let* ((process-environment process-environment)
2046 (startup-code (concat "import sys\n"
2047 "sys.ps1 = 'py> '\n"
2048 "sys.ps2 = '..> '\n"
2049 "sys.ps3 = 'out '\n"))
2050 (startup-file (python-shell--save-temp-file startup-code)))
2051 (unwind-protect
2052 (progn
2053 ;; Ensure startup file is enabled
2054 (setenv "PYTHONSTARTUP" startup-file)
2055 (should python-shell-prompt-detect-enabled)
2056 (should (equal (python-shell-prompt-detect) '("py> " "..> " "out "))))
2057 (ignore-errors (delete-file startup-file)))))
2058
2059 (ert-deftest python-shell-prompt-detect-3 ()
2060 "Check prompts are not autodetected when feature is disabled."
2061 (skip-unless (executable-find python-tests-shell-interpreter))
2062 (let ((process-environment process-environment)
2063 (python-shell-prompt-detect-enabled nil))
2064 ;; Ensure no startup file is enabled
2065 (should (not python-shell-prompt-detect-enabled))
2066 (should (not (python-shell-prompt-detect)))))
2067
2068 (ert-deftest python-shell-prompt-detect-4 ()
2069 "Check warning is shown when detection fails."
2070 (skip-unless (executable-find python-tests-shell-interpreter))
2071 (let* ((process-environment process-environment)
2072 ;; Trigger failure by removing prompts in the startup file
2073 (startup-code (concat "import sys\n"
2074 "sys.ps1 = ''\n"
2075 "sys.ps2 = ''\n"
2076 "sys.ps3 = ''\n"))
2077 (startup-file (python-shell--save-temp-file startup-code)))
2078 (unwind-protect
2079 (progn
2080 (kill-buffer (get-buffer-create "*Warnings*"))
2081 (should (not (get-buffer "*Warnings*")))
2082 (setenv "PYTHONSTARTUP" startup-file)
2083 (should python-shell-prompt-detect-failure-warning)
2084 (should python-shell-prompt-detect-enabled)
2085 (should (not (python-shell-prompt-detect)))
2086 (should (get-buffer "*Warnings*")))
2087 (ignore-errors (delete-file startup-file)))))
2088
2089 (ert-deftest python-shell-prompt-detect-5 ()
2090 "Check disabled warnings are not shown when detection fails."
2091 (skip-unless (executable-find python-tests-shell-interpreter))
2092 (let* ((process-environment process-environment)
2093 (startup-code (concat "import sys\n"
2094 "sys.ps1 = ''\n"
2095 "sys.ps2 = ''\n"
2096 "sys.ps3 = ''\n"))
2097 (startup-file (python-shell--save-temp-file startup-code))
2098 (python-shell-prompt-detect-failure-warning nil))
2099 (unwind-protect
2100 (progn
2101 (kill-buffer (get-buffer-create "*Warnings*"))
2102 (should (not (get-buffer "*Warnings*")))
2103 (setenv "PYTHONSTARTUP" startup-file)
2104 (should (not python-shell-prompt-detect-failure-warning))
2105 (should python-shell-prompt-detect-enabled)
2106 (should (not (python-shell-prompt-detect)))
2107 (should (not (get-buffer "*Warnings*"))))
2108 (ignore-errors (delete-file startup-file)))))
2109
2110 (ert-deftest python-shell-prompt-detect-6 ()
2111 "Warnings are not shown when detection is disabled."
2112 (skip-unless (executable-find python-tests-shell-interpreter))
2113 (let* ((process-environment process-environment)
2114 (startup-code (concat "import sys\n"
2115 "sys.ps1 = ''\n"
2116 "sys.ps2 = ''\n"
2117 "sys.ps3 = ''\n"))
2118 (startup-file (python-shell--save-temp-file startup-code))
2119 (python-shell-prompt-detect-failure-warning t)
2120 (python-shell-prompt-detect-enabled nil))
2121 (unwind-protect
2122 (progn
2123 (kill-buffer (get-buffer-create "*Warnings*"))
2124 (should (not (get-buffer "*Warnings*")))
2125 (setenv "PYTHONSTARTUP" startup-file)
2126 (should python-shell-prompt-detect-failure-warning)
2127 (should (not python-shell-prompt-detect-enabled))
2128 (should (not (python-shell-prompt-detect)))
2129 (should (not (get-buffer "*Warnings*"))))
2130 (ignore-errors (delete-file startup-file)))))
2131
2132 (ert-deftest python-shell-prompt-validate-regexps-1 ()
2133 "Check `python-shell-prompt-input-regexps' are validated."
2134 (let* ((python-shell-prompt-input-regexps '("\\("))
2135 (error-data (should-error (python-shell-prompt-validate-regexps)
2136 :type 'user-error)))
2137 (should
2138 (string= (cadr error-data)
2139 "Invalid regexp \\( in `python-shell-prompt-input-regexps'"))))
2140
2141 (ert-deftest python-shell-prompt-validate-regexps-2 ()
2142 "Check `python-shell-prompt-output-regexps' are validated."
2143 (let* ((python-shell-prompt-output-regexps '("\\("))
2144 (error-data (should-error (python-shell-prompt-validate-regexps)
2145 :type 'user-error)))
2146 (should
2147 (string= (cadr error-data)
2148 "Invalid regexp \\( in `python-shell-prompt-output-regexps'"))))
2149
2150 (ert-deftest python-shell-prompt-validate-regexps-3 ()
2151 "Check `python-shell-prompt-regexp' is validated."
2152 (let* ((python-shell-prompt-regexp "\\(")
2153 (error-data (should-error (python-shell-prompt-validate-regexps)
2154 :type 'user-error)))
2155 (should
2156 (string= (cadr error-data)
2157 "Invalid regexp \\( in `python-shell-prompt-regexp'"))))
2158
2159 (ert-deftest python-shell-prompt-validate-regexps-4 ()
2160 "Check `python-shell-prompt-block-regexp' is validated."
2161 (let* ((python-shell-prompt-block-regexp "\\(")
2162 (error-data (should-error (python-shell-prompt-validate-regexps)
2163 :type 'user-error)))
2164 (should
2165 (string= (cadr error-data)
2166 "Invalid regexp \\( in `python-shell-prompt-block-regexp'"))))
2167
2168 (ert-deftest python-shell-prompt-validate-regexps-5 ()
2169 "Check `python-shell-prompt-pdb-regexp' is validated."
2170 (let* ((python-shell-prompt-pdb-regexp "\\(")
2171 (error-data (should-error (python-shell-prompt-validate-regexps)
2172 :type 'user-error)))
2173 (should
2174 (string= (cadr error-data)
2175 "Invalid regexp \\( in `python-shell-prompt-pdb-regexp'"))))
2176
2177 (ert-deftest python-shell-prompt-validate-regexps-6 ()
2178 "Check `python-shell-prompt-output-regexp' is validated."
2179 (let* ((python-shell-prompt-output-regexp "\\(")
2180 (error-data (should-error (python-shell-prompt-validate-regexps)
2181 :type 'user-error)))
2182 (should
2183 (string= (cadr error-data)
2184 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2185
2186 (ert-deftest python-shell-prompt-validate-regexps-7 ()
2187 "Check default regexps are valid."
2188 ;; should not signal error
2189 (python-shell-prompt-validate-regexps))
2190
2191 (ert-deftest python-shell-prompt-set-calculated-regexps-1 ()
2192 "Check regexps are validated."
2193 (let* ((python-shell-prompt-output-regexp '("\\("))
2194 (python-shell--prompt-calculated-input-regexp nil)
2195 (python-shell--prompt-calculated-output-regexp nil)
2196 (python-shell-prompt-detect-enabled nil)
2197 (error-data (should-error (python-shell-prompt-set-calculated-regexps)
2198 :type 'user-error)))
2199 (should
2200 (string= (cadr error-data)
2201 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2202
2203 (ert-deftest python-shell-prompt-set-calculated-regexps-2 ()
2204 "Check `python-shell-prompt-input-regexps' are set."
2205 (let* ((python-shell-prompt-input-regexps '("my" "prompt"))
2206 (python-shell-prompt-output-regexps '(""))
2207 (python-shell-prompt-regexp "")
2208 (python-shell-prompt-block-regexp "")
2209 (python-shell-prompt-pdb-regexp "")
2210 (python-shell-prompt-output-regexp "")
2211 (python-shell--prompt-calculated-input-regexp nil)
2212 (python-shell--prompt-calculated-output-regexp nil)
2213 (python-shell-prompt-detect-enabled nil))
2214 (python-shell-prompt-set-calculated-regexps)
2215 (should (string= python-shell--prompt-calculated-input-regexp
2216 "^\\(prompt\\|my\\|\\)"))))
2217
2218 (ert-deftest python-shell-prompt-set-calculated-regexps-3 ()
2219 "Check `python-shell-prompt-output-regexps' are set."
2220 (let* ((python-shell-prompt-input-regexps '(""))
2221 (python-shell-prompt-output-regexps '("my" "prompt"))
2222 (python-shell-prompt-regexp "")
2223 (python-shell-prompt-block-regexp "")
2224 (python-shell-prompt-pdb-regexp "")
2225 (python-shell-prompt-output-regexp "")
2226 (python-shell--prompt-calculated-input-regexp nil)
2227 (python-shell--prompt-calculated-output-regexp nil)
2228 (python-shell-prompt-detect-enabled nil))
2229 (python-shell-prompt-set-calculated-regexps)
2230 (should (string= python-shell--prompt-calculated-output-regexp
2231 "^\\(prompt\\|my\\|\\)"))))
2232
2233 (ert-deftest python-shell-prompt-set-calculated-regexps-4 ()
2234 "Check user defined prompts are set."
2235 (let* ((python-shell-prompt-input-regexps '(""))
2236 (python-shell-prompt-output-regexps '(""))
2237 (python-shell-prompt-regexp "prompt")
2238 (python-shell-prompt-block-regexp "block")
2239 (python-shell-prompt-pdb-regexp "pdb")
2240 (python-shell-prompt-output-regexp "output")
2241 (python-shell--prompt-calculated-input-regexp nil)
2242 (python-shell--prompt-calculated-output-regexp nil)
2243 (python-shell-prompt-detect-enabled nil))
2244 (python-shell-prompt-set-calculated-regexps)
2245 (should (string= python-shell--prompt-calculated-input-regexp
2246 "^\\(prompt\\|block\\|pdb\\|\\)"))
2247 (should (string= python-shell--prompt-calculated-output-regexp
2248 "^\\(output\\|\\)"))))
2249
2250 (ert-deftest python-shell-prompt-set-calculated-regexps-5 ()
2251 "Check order of regexps (larger first)."
2252 (let* ((python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2253 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2254 (python-shell-prompt-regexp "in")
2255 (python-shell-prompt-block-regexp "block")
2256 (python-shell-prompt-pdb-regexp "pdf")
2257 (python-shell-prompt-output-regexp "output")
2258 (python-shell--prompt-calculated-input-regexp nil)
2259 (python-shell--prompt-calculated-output-regexp nil)
2260 (python-shell-prompt-detect-enabled nil))
2261 (python-shell-prompt-set-calculated-regexps)
2262 (should (string= python-shell--prompt-calculated-input-regexp
2263 "^\\(extralargeinputprompt\\|block\\|pdf\\|sml\\|in\\)"))
2264 (should (string= python-shell--prompt-calculated-output-regexp
2265 "^\\(extralargeoutputprompt\\|output\\|sml\\)"))))
2266
2267 (ert-deftest python-shell-prompt-set-calculated-regexps-6 ()
2268 "Check detected prompts are included `regexp-quote'd."
2269 (skip-unless (executable-find python-tests-shell-interpreter))
2270 (let* ((python-shell-prompt-input-regexps '(""))
2271 (python-shell-prompt-output-regexps '(""))
2272 (python-shell-prompt-regexp "")
2273 (python-shell-prompt-block-regexp "")
2274 (python-shell-prompt-pdb-regexp "")
2275 (python-shell-prompt-output-regexp "")
2276 (python-shell--prompt-calculated-input-regexp nil)
2277 (python-shell--prompt-calculated-output-regexp nil)
2278 (python-shell-prompt-detect-enabled t)
2279 (process-environment process-environment)
2280 (startup-code (concat "import sys\n"
2281 "sys.ps1 = 'p.> '\n"
2282 "sys.ps2 = '..> '\n"
2283 "sys.ps3 = 'o.t '\n"))
2284 (startup-file (python-shell--save-temp-file startup-code)))
2285 (unwind-protect
2286 (progn
2287 (setenv "PYTHONSTARTUP" startup-file)
2288 (python-shell-prompt-set-calculated-regexps)
2289 (should (string= python-shell--prompt-calculated-input-regexp
2290 "^\\(\\.\\.> \\|p\\.> \\|\\)"))
2291 (should (string= python-shell--prompt-calculated-output-regexp
2292 "^\\(o\\.t \\|\\)")))
2293 (ignore-errors (delete-file startup-file)))))
2294
2295 \f
2296 ;;; Shell completion
2297
2298 \f
2299 ;;; PDB Track integration
2300
2301 \f
2302 ;;; Symbol completion
2303
2304 \f
2305 ;;; Fill paragraph
2306
2307 \f
2308 ;;; Skeletons
2309
2310 \f
2311 ;;; FFAP
2312
2313 \f
2314 ;;; Code check
2315
2316 \f
2317 ;;; Eldoc
2318
2319 \f
2320 ;;; Imenu
2321
2322 (ert-deftest python-imenu-create-index-1 ()
2323 (python-tests-with-temp-buffer
2324 "
2325 class Foo(models.Model):
2326 pass
2327
2328
2329 class Bar(models.Model):
2330 pass
2331
2332
2333 def decorator(arg1, arg2, arg3):
2334 '''print decorated function call data to stdout.
2335
2336 Usage:
2337
2338 @decorator('arg1', 'arg2')
2339 def func(a, b, c=True):
2340 pass
2341 '''
2342
2343 def wrap(f):
2344 print ('wrap')
2345 def wrapped_f(*args):
2346 print ('wrapped_f')
2347 print ('Decorator arguments:', arg1, arg2, arg3)
2348 f(*args)
2349 print ('called f(*args)')
2350 return wrapped_f
2351 return wrap
2352
2353
2354 class Baz(object):
2355
2356 def a(self):
2357 pass
2358
2359 def b(self):
2360 pass
2361
2362 class Frob(object):
2363
2364 def c(self):
2365 pass
2366 "
2367 (goto-char (point-max))
2368 (should (equal
2369 (list
2370 (cons "Foo (class)" (copy-marker 2))
2371 (cons "Bar (class)" (copy-marker 38))
2372 (list
2373 "decorator (def)"
2374 (cons "*function definition*" (copy-marker 74))
2375 (list
2376 "wrap (def)"
2377 (cons "*function definition*" (copy-marker 254))
2378 (cons "wrapped_f (def)" (copy-marker 294))))
2379 (list
2380 "Baz (class)"
2381 (cons "*class definition*" (copy-marker 519))
2382 (cons "a (def)" (copy-marker 539))
2383 (cons "b (def)" (copy-marker 570))
2384 (list
2385 "Frob (class)"
2386 (cons "*class definition*" (copy-marker 601))
2387 (cons "c (def)" (copy-marker 626)))))
2388 (python-imenu-create-index)))))
2389
2390 (ert-deftest python-imenu-create-index-2 ()
2391 (python-tests-with-temp-buffer
2392 "
2393 class Foo(object):
2394 def foo(self):
2395 def foo1():
2396 pass
2397
2398 def foobar(self):
2399 pass
2400 "
2401 (goto-char (point-max))
2402 (should (equal
2403 (list
2404 (list
2405 "Foo (class)"
2406 (cons "*class definition*" (copy-marker 2))
2407 (list
2408 "foo (def)"
2409 (cons "*function definition*" (copy-marker 21))
2410 (cons "foo1 (def)" (copy-marker 40)))
2411 (cons "foobar (def)" (copy-marker 78))))
2412 (python-imenu-create-index)))))
2413
2414 (ert-deftest python-imenu-create-index-3 ()
2415 (python-tests-with-temp-buffer
2416 "
2417 class Foo(object):
2418 def foo(self):
2419 def foo1():
2420 pass
2421 def foo2():
2422 pass
2423 "
2424 (goto-char (point-max))
2425 (should (equal
2426 (list
2427 (list
2428 "Foo (class)"
2429 (cons "*class definition*" (copy-marker 2))
2430 (list
2431 "foo (def)"
2432 (cons "*function definition*" (copy-marker 21))
2433 (cons "foo1 (def)" (copy-marker 40))
2434 (cons "foo2 (def)" (copy-marker 77)))))
2435 (python-imenu-create-index)))))
2436
2437 (ert-deftest python-imenu-create-index-4 ()
2438 (python-tests-with-temp-buffer
2439 "
2440 class Foo(object):
2441 class Bar(object):
2442 def __init__(self):
2443 pass
2444
2445 def __str__(self):
2446 pass
2447
2448 def __init__(self):
2449 pass
2450 "
2451 (goto-char (point-max))
2452 (should (equal
2453 (list
2454 (list
2455 "Foo (class)"
2456 (cons "*class definition*" (copy-marker 2))
2457 (list
2458 "Bar (class)"
2459 (cons "*class definition*" (copy-marker 21))
2460 (cons "__init__ (def)" (copy-marker 44))
2461 (cons "__str__ (def)" (copy-marker 90)))
2462 (cons "__init__ (def)" (copy-marker 135))))
2463 (python-imenu-create-index)))))
2464
2465 (ert-deftest python-imenu-create-flat-index-1 ()
2466 (python-tests-with-temp-buffer
2467 "
2468 class Foo(models.Model):
2469 pass
2470
2471
2472 class Bar(models.Model):
2473 pass
2474
2475
2476 def decorator(arg1, arg2, arg3):
2477 '''print decorated function call data to stdout.
2478
2479 Usage:
2480
2481 @decorator('arg1', 'arg2')
2482 def func(a, b, c=True):
2483 pass
2484 '''
2485
2486 def wrap(f):
2487 print ('wrap')
2488 def wrapped_f(*args):
2489 print ('wrapped_f')
2490 print ('Decorator arguments:', arg1, arg2, arg3)
2491 f(*args)
2492 print ('called f(*args)')
2493 return wrapped_f
2494 return wrap
2495
2496
2497 class Baz(object):
2498
2499 def a(self):
2500 pass
2501
2502 def b(self):
2503 pass
2504
2505 class Frob(object):
2506
2507 def c(self):
2508 pass
2509 "
2510 (goto-char (point-max))
2511 (should (equal
2512 (list (cons "Foo" (copy-marker 2))
2513 (cons "Bar" (copy-marker 38))
2514 (cons "decorator" (copy-marker 74))
2515 (cons "decorator.wrap" (copy-marker 254))
2516 (cons "decorator.wrap.wrapped_f" (copy-marker 294))
2517 (cons "Baz" (copy-marker 519))
2518 (cons "Baz.a" (copy-marker 539))
2519 (cons "Baz.b" (copy-marker 570))
2520 (cons "Baz.Frob" (copy-marker 601))
2521 (cons "Baz.Frob.c" (copy-marker 626)))
2522 (python-imenu-create-flat-index)))))
2523
2524 (ert-deftest python-imenu-create-flat-index-2 ()
2525 (python-tests-with-temp-buffer
2526 "
2527 class Foo(object):
2528 class Bar(object):
2529 def __init__(self):
2530 pass
2531
2532 def __str__(self):
2533 pass
2534
2535 def __init__(self):
2536 pass
2537 "
2538 (goto-char (point-max))
2539 (should (equal
2540 (list
2541 (cons "Foo" (copy-marker 2))
2542 (cons "Foo.Bar" (copy-marker 21))
2543 (cons "Foo.Bar.__init__" (copy-marker 44))
2544 (cons "Foo.Bar.__str__" (copy-marker 90))
2545 (cons "Foo.__init__" (copy-marker 135)))
2546 (python-imenu-create-flat-index)))))
2547
2548 \f
2549 ;;; Misc helpers
2550
2551 (ert-deftest python-info-current-defun-1 ()
2552 (python-tests-with-temp-buffer
2553 "
2554 def foo(a, b):
2555 "
2556 (forward-line 1)
2557 (should (string= "foo" (python-info-current-defun)))
2558 (should (string= "def foo" (python-info-current-defun t)))
2559 (forward-line 1)
2560 (should (not (python-info-current-defun)))
2561 (indent-for-tab-command)
2562 (should (string= "foo" (python-info-current-defun)))
2563 (should (string= "def foo" (python-info-current-defun t)))))
2564
2565 (ert-deftest python-info-current-defun-2 ()
2566 (python-tests-with-temp-buffer
2567 "
2568 class C(object):
2569
2570 def m(self):
2571 if True:
2572 return [i for i in range(3)]
2573 else:
2574 return []
2575
2576 def b():
2577 do_b()
2578
2579 def a():
2580 do_a()
2581
2582 def c(self):
2583 do_c()
2584 "
2585 (forward-line 1)
2586 (should (string= "C" (python-info-current-defun)))
2587 (should (string= "class C" (python-info-current-defun t)))
2588 (python-tests-look-at "return [i for ")
2589 (should (string= "C.m" (python-info-current-defun)))
2590 (should (string= "def C.m" (python-info-current-defun t)))
2591 (python-tests-look-at "def b():")
2592 (should (string= "C.m.b" (python-info-current-defun)))
2593 (should (string= "def C.m.b" (python-info-current-defun t)))
2594 (forward-line 2)
2595 (indent-for-tab-command)
2596 (python-indent-dedent-line-backspace 1)
2597 (should (string= "C.m" (python-info-current-defun)))
2598 (should (string= "def C.m" (python-info-current-defun t)))
2599 (python-tests-look-at "def c(self):")
2600 (forward-line -1)
2601 (indent-for-tab-command)
2602 (should (string= "C.m.a" (python-info-current-defun)))
2603 (should (string= "def C.m.a" (python-info-current-defun t)))
2604 (python-indent-dedent-line-backspace 1)
2605 (should (string= "C.m" (python-info-current-defun)))
2606 (should (string= "def C.m" (python-info-current-defun t)))
2607 (python-indent-dedent-line-backspace 1)
2608 (should (string= "C" (python-info-current-defun)))
2609 (should (string= "class C" (python-info-current-defun t)))
2610 (python-tests-look-at "def c(self):")
2611 (should (string= "C.c" (python-info-current-defun)))
2612 (should (string= "def C.c" (python-info-current-defun t)))
2613 (python-tests-look-at "do_c()")
2614 (should (string= "C.c" (python-info-current-defun)))
2615 (should (string= "def C.c" (python-info-current-defun t)))))
2616
2617 (ert-deftest python-info-current-defun-3 ()
2618 (python-tests-with-temp-buffer
2619 "
2620 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2621 '''print decorated function call data to stdout.
2622
2623 Usage:
2624
2625 @decoratorFunctionWithArguments('arg1', 'arg2')
2626 def func(a, b, c=True):
2627 pass
2628 '''
2629
2630 def wwrap(f):
2631 print 'Inside wwrap()'
2632 def wrapped_f(*args):
2633 print 'Inside wrapped_f()'
2634 print 'Decorator arguments:', arg1, arg2, arg3
2635 f(*args)
2636 print 'After f(*args)'
2637 return wrapped_f
2638 return wwrap
2639 "
2640 (python-tests-look-at "def wwrap(f):")
2641 (forward-line -1)
2642 (should (not (python-info-current-defun)))
2643 (indent-for-tab-command 1)
2644 (should (string= (python-info-current-defun)
2645 "decoratorFunctionWithArguments"))
2646 (should (string= (python-info-current-defun t)
2647 "def decoratorFunctionWithArguments"))
2648 (python-tests-look-at "def wrapped_f(*args):")
2649 (should (string= (python-info-current-defun)
2650 "decoratorFunctionWithArguments.wwrap.wrapped_f"))
2651 (should (string= (python-info-current-defun t)
2652 "def decoratorFunctionWithArguments.wwrap.wrapped_f"))
2653 (python-tests-look-at "return wrapped_f")
2654 (should (string= (python-info-current-defun)
2655 "decoratorFunctionWithArguments.wwrap"))
2656 (should (string= (python-info-current-defun t)
2657 "def decoratorFunctionWithArguments.wwrap"))
2658 (end-of-line 1)
2659 (python-tests-look-at "return wwrap")
2660 (should (string= (python-info-current-defun)
2661 "decoratorFunctionWithArguments"))
2662 (should (string= (python-info-current-defun t)
2663 "def decoratorFunctionWithArguments"))))
2664
2665 (ert-deftest python-info-current-symbol-1 ()
2666 (python-tests-with-temp-buffer
2667 "
2668 class C(object):
2669
2670 def m(self):
2671 self.c()
2672
2673 def c(self):
2674 print ('a')
2675 "
2676 (python-tests-look-at "self.c()")
2677 (should (string= "self.c" (python-info-current-symbol)))
2678 (should (string= "C.c" (python-info-current-symbol t)))))
2679
2680 (ert-deftest python-info-current-symbol-2 ()
2681 (python-tests-with-temp-buffer
2682 "
2683 class C(object):
2684
2685 class M(object):
2686
2687 def a(self):
2688 self.c()
2689
2690 def c(self):
2691 pass
2692 "
2693 (python-tests-look-at "self.c()")
2694 (should (string= "self.c" (python-info-current-symbol)))
2695 (should (string= "C.M.c" (python-info-current-symbol t)))))
2696
2697 (ert-deftest python-info-current-symbol-3 ()
2698 "Keywords should not be considered symbols."
2699 :expected-result :failed
2700 (python-tests-with-temp-buffer
2701 "
2702 class C(object):
2703 pass
2704 "
2705 ;; FIXME: keywords are not symbols.
2706 (python-tests-look-at "class C")
2707 (should (not (python-info-current-symbol)))
2708 (should (not (python-info-current-symbol t)))
2709 (python-tests-look-at "C(object)")
2710 (should (string= "C" (python-info-current-symbol)))
2711 (should (string= "class C" (python-info-current-symbol t)))))
2712
2713 (ert-deftest python-info-statement-starts-block-p-1 ()
2714 (python-tests-with-temp-buffer
2715 "
2716 def long_function_name(
2717 var_one, var_two, var_three,
2718 var_four):
2719 print (var_one)
2720 "
2721 (python-tests-look-at "def long_function_name")
2722 (should (python-info-statement-starts-block-p))
2723 (python-tests-look-at "print (var_one)")
2724 (python-util-forward-comment -1)
2725 (should (python-info-statement-starts-block-p))))
2726
2727 (ert-deftest python-info-statement-starts-block-p-2 ()
2728 (python-tests-with-temp-buffer
2729 "
2730 if width == 0 and height == 0 and \\\\
2731 color == 'red' and emphasis == 'strong' or \\\\
2732 highlight > 100:
2733 raise ValueError('sorry, you lose')
2734 "
2735 (python-tests-look-at "if width == 0 and")
2736 (should (python-info-statement-starts-block-p))
2737 (python-tests-look-at "raise ValueError(")
2738 (python-util-forward-comment -1)
2739 (should (python-info-statement-starts-block-p))))
2740
2741 (ert-deftest python-info-statement-ends-block-p-1 ()
2742 (python-tests-with-temp-buffer
2743 "
2744 def long_function_name(
2745 var_one, var_two, var_three,
2746 var_four):
2747 print (var_one)
2748 "
2749 (python-tests-look-at "print (var_one)")
2750 (should (python-info-statement-ends-block-p))))
2751
2752 (ert-deftest python-info-statement-ends-block-p-2 ()
2753 (python-tests-with-temp-buffer
2754 "
2755 if width == 0 and height == 0 and \\\\
2756 color == 'red' and emphasis == 'strong' or \\\\
2757 highlight > 100:
2758 raise ValueError(
2759 'sorry, you lose'
2760
2761 )
2762 "
2763 (python-tests-look-at "raise ValueError(")
2764 (should (python-info-statement-ends-block-p))))
2765
2766 (ert-deftest python-info-beginning-of-statement-p-1 ()
2767 (python-tests-with-temp-buffer
2768 "
2769 def long_function_name(
2770 var_one, var_two, var_three,
2771 var_four):
2772 print (var_one)
2773 "
2774 (python-tests-look-at "def long_function_name")
2775 (should (python-info-beginning-of-statement-p))
2776 (forward-char 10)
2777 (should (not (python-info-beginning-of-statement-p)))
2778 (python-tests-look-at "print (var_one)")
2779 (should (python-info-beginning-of-statement-p))
2780 (goto-char (line-beginning-position))
2781 (should (not (python-info-beginning-of-statement-p)))))
2782
2783 (ert-deftest python-info-beginning-of-statement-p-2 ()
2784 (python-tests-with-temp-buffer
2785 "
2786 if width == 0 and height == 0 and \\\\
2787 color == 'red' and emphasis == 'strong' or \\\\
2788 highlight > 100:
2789 raise ValueError(
2790 'sorry, you lose'
2791
2792 )
2793 "
2794 (python-tests-look-at "if width == 0 and")
2795 (should (python-info-beginning-of-statement-p))
2796 (forward-char 10)
2797 (should (not (python-info-beginning-of-statement-p)))
2798 (python-tests-look-at "raise ValueError(")
2799 (should (python-info-beginning-of-statement-p))
2800 (goto-char (line-beginning-position))
2801 (should (not (python-info-beginning-of-statement-p)))))
2802
2803 (ert-deftest python-info-end-of-statement-p-1 ()
2804 (python-tests-with-temp-buffer
2805 "
2806 def long_function_name(
2807 var_one, var_two, var_three,
2808 var_four):
2809 print (var_one)
2810 "
2811 (python-tests-look-at "def long_function_name")
2812 (should (not (python-info-end-of-statement-p)))
2813 (end-of-line)
2814 (should (not (python-info-end-of-statement-p)))
2815 (python-tests-look-at "print (var_one)")
2816 (python-util-forward-comment -1)
2817 (should (python-info-end-of-statement-p))
2818 (python-tests-look-at "print (var_one)")
2819 (should (not (python-info-end-of-statement-p)))
2820 (end-of-line)
2821 (should (python-info-end-of-statement-p))))
2822
2823 (ert-deftest python-info-end-of-statement-p-2 ()
2824 (python-tests-with-temp-buffer
2825 "
2826 if width == 0 and height == 0 and \\\\
2827 color == 'red' and emphasis == 'strong' or \\\\
2828 highlight > 100:
2829 raise ValueError(
2830 'sorry, you lose'
2831
2832 )
2833 "
2834 (python-tests-look-at "if width == 0 and")
2835 (should (not (python-info-end-of-statement-p)))
2836 (end-of-line)
2837 (should (not (python-info-end-of-statement-p)))
2838 (python-tests-look-at "raise ValueError(")
2839 (python-util-forward-comment -1)
2840 (should (python-info-end-of-statement-p))
2841 (python-tests-look-at "raise ValueError(")
2842 (should (not (python-info-end-of-statement-p)))
2843 (end-of-line)
2844 (should (not (python-info-end-of-statement-p)))
2845 (goto-char (point-max))
2846 (python-util-forward-comment -1)
2847 (should (python-info-end-of-statement-p))))
2848
2849 (ert-deftest python-info-beginning-of-block-p-1 ()
2850 (python-tests-with-temp-buffer
2851 "
2852 def long_function_name(
2853 var_one, var_two, var_three,
2854 var_four):
2855 print (var_one)
2856 "
2857 (python-tests-look-at "def long_function_name")
2858 (should (python-info-beginning-of-block-p))
2859 (python-tests-look-at "var_one, var_two, var_three,")
2860 (should (not (python-info-beginning-of-block-p)))
2861 (python-tests-look-at "print (var_one)")
2862 (should (not (python-info-beginning-of-block-p)))))
2863
2864 (ert-deftest python-info-beginning-of-block-p-2 ()
2865 (python-tests-with-temp-buffer
2866 "
2867 if width == 0 and height == 0 and \\\\
2868 color == 'red' and emphasis == 'strong' or \\\\
2869 highlight > 100:
2870 raise ValueError(
2871 'sorry, you lose'
2872
2873 )
2874 "
2875 (python-tests-look-at "if width == 0 and")
2876 (should (python-info-beginning-of-block-p))
2877 (python-tests-look-at "color == 'red' and emphasis")
2878 (should (not (python-info-beginning-of-block-p)))
2879 (python-tests-look-at "raise ValueError(")
2880 (should (not (python-info-beginning-of-block-p)))))
2881
2882 (ert-deftest python-info-end-of-block-p-1 ()
2883 (python-tests-with-temp-buffer
2884 "
2885 def long_function_name(
2886 var_one, var_two, var_three,
2887 var_four):
2888 print (var_one)
2889 "
2890 (python-tests-look-at "def long_function_name")
2891 (should (not (python-info-end-of-block-p)))
2892 (python-tests-look-at "var_one, var_two, var_three,")
2893 (should (not (python-info-end-of-block-p)))
2894 (python-tests-look-at "var_four):")
2895 (end-of-line)
2896 (should (not (python-info-end-of-block-p)))
2897 (python-tests-look-at "print (var_one)")
2898 (should (not (python-info-end-of-block-p)))
2899 (end-of-line 1)
2900 (should (python-info-end-of-block-p))))
2901
2902 (ert-deftest python-info-end-of-block-p-2 ()
2903 (python-tests-with-temp-buffer
2904 "
2905 if width == 0 and height == 0 and \\\\
2906 color == 'red' and emphasis == 'strong' or \\\\
2907 highlight > 100:
2908 raise ValueError(
2909 'sorry, you lose'
2910
2911 )
2912 "
2913 (python-tests-look-at "if width == 0 and")
2914 (should (not (python-info-end-of-block-p)))
2915 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
2916 (should (not (python-info-end-of-block-p)))
2917 (python-tests-look-at "highlight > 100:")
2918 (end-of-line)
2919 (should (not (python-info-end-of-block-p)))
2920 (python-tests-look-at "raise ValueError(")
2921 (should (not (python-info-end-of-block-p)))
2922 (end-of-line 1)
2923 (should (not (python-info-end-of-block-p)))
2924 (goto-char (point-max))
2925 (python-util-forward-comment -1)
2926 (should (python-info-end-of-block-p))))
2927
2928 (ert-deftest python-info-dedenter-opening-block-position-1 ()
2929 (python-tests-with-temp-buffer
2930 "
2931 if request.user.is_authenticated():
2932 try:
2933 profile = request.user.get_profile()
2934 except Profile.DoesNotExist:
2935 profile = Profile.objects.create(user=request.user)
2936 else:
2937 if profile.stats:
2938 profile.recalculate_stats()
2939 else:
2940 profile.clear_stats()
2941 finally:
2942 profile.views += 1
2943 profile.save()
2944 "
2945 (python-tests-look-at "try:")
2946 (should (not (python-info-dedenter-opening-block-position)))
2947 (python-tests-look-at "except Profile.DoesNotExist:")
2948 (should (= (python-tests-look-at "try:" -1 t)
2949 (python-info-dedenter-opening-block-position)))
2950 (python-tests-look-at "else:")
2951 (should (= (python-tests-look-at "except Profile.DoesNotExist:" -1 t)
2952 (python-info-dedenter-opening-block-position)))
2953 (python-tests-look-at "if profile.stats:")
2954 (should (not (python-info-dedenter-opening-block-position)))
2955 (python-tests-look-at "else:")
2956 (should (= (python-tests-look-at "if profile.stats:" -1 t)
2957 (python-info-dedenter-opening-block-position)))
2958 (python-tests-look-at "finally:")
2959 (should (= (python-tests-look-at "else:" -2 t)
2960 (python-info-dedenter-opening-block-position)))))
2961
2962 (ert-deftest python-info-dedenter-opening-block-position-2 ()
2963 (python-tests-with-temp-buffer
2964 "
2965 if request.user.is_authenticated():
2966 profile = Profile.objects.get_or_create(user=request.user)
2967 if profile.stats:
2968 profile.recalculate_stats()
2969
2970 data = {
2971 'else': 'do it'
2972 }
2973 'else'
2974 "
2975 (python-tests-look-at "'else': 'do it'")
2976 (should (not (python-info-dedenter-opening-block-position)))
2977 (python-tests-look-at "'else'")
2978 (should (not (python-info-dedenter-opening-block-position)))))
2979
2980 (ert-deftest python-info-dedenter-opening-block-position-3 ()
2981 (python-tests-with-temp-buffer
2982 "
2983 if save:
2984 try:
2985 write_to_disk(data)
2986 except IOError:
2987 msg = 'Error saving to disk'
2988 message(msg)
2989 logger.exception(msg)
2990 except Exception:
2991 if hide_details:
2992 logger.exception('Unhandled exception')
2993 else
2994 finally:
2995 data.free()
2996 "
2997 (python-tests-look-at "try:")
2998 (should (not (python-info-dedenter-opening-block-position)))
2999
3000 (python-tests-look-at "except IOError:")
3001 (should (= (python-tests-look-at "try:" -1 t)
3002 (python-info-dedenter-opening-block-position)))
3003
3004 (python-tests-look-at "except Exception:")
3005 (should (= (python-tests-look-at "except IOError:" -1 t)
3006 (python-info-dedenter-opening-block-position)))
3007
3008 (python-tests-look-at "if hide_details:")
3009 (should (not (python-info-dedenter-opening-block-position)))
3010
3011 ;; check indentation modifies the detected opening block
3012 (python-tests-look-at "else")
3013 (should (= (python-tests-look-at "if hide_details:" -1 t)
3014 (python-info-dedenter-opening-block-position)))
3015
3016 (indent-line-to 8)
3017 (should (= (python-tests-look-at "if hide_details:" -1 t)
3018 (python-info-dedenter-opening-block-position)))
3019
3020 (indent-line-to 4)
3021 (should (= (python-tests-look-at "except Exception:" -1 t)
3022 (python-info-dedenter-opening-block-position)))
3023
3024 (indent-line-to 0)
3025 (should (= (python-tests-look-at "if save:" -1 t)
3026 (python-info-dedenter-opening-block-position)))))
3027
3028 (ert-deftest python-info-dedenter-opening-block-positions-1 ()
3029 (python-tests-with-temp-buffer
3030 "
3031 if save:
3032 try:
3033 write_to_disk(data)
3034 except IOError:
3035 msg = 'Error saving to disk'
3036 message(msg)
3037 logger.exception(msg)
3038 except Exception:
3039 if hide_details:
3040 logger.exception('Unhandled exception')
3041 else
3042 finally:
3043 data.free()
3044 "
3045 (python-tests-look-at "try:")
3046 (should (not (python-info-dedenter-opening-block-positions)))
3047
3048 (python-tests-look-at "except IOError:")
3049 (should
3050 (equal (list
3051 (python-tests-look-at "try:" -1 t))
3052 (python-info-dedenter-opening-block-positions)))
3053
3054 (python-tests-look-at "except Exception:")
3055 (should
3056 (equal (list
3057 (python-tests-look-at "except IOError:" -1 t))
3058 (python-info-dedenter-opening-block-positions)))
3059
3060 (python-tests-look-at "if hide_details:")
3061 (should (not (python-info-dedenter-opening-block-positions)))
3062
3063 ;; check indentation does not modify the detected opening blocks
3064 (python-tests-look-at "else")
3065 (should
3066 (equal (list
3067 (python-tests-look-at "if hide_details:" -1 t)
3068 (python-tests-look-at "except Exception:" -1 t)
3069 (python-tests-look-at "if save:" -1 t))
3070 (python-info-dedenter-opening-block-positions)))
3071
3072 (indent-line-to 8)
3073 (should
3074 (equal (list
3075 (python-tests-look-at "if hide_details:" -1 t)
3076 (python-tests-look-at "except Exception:" -1 t)
3077 (python-tests-look-at "if save:" -1 t))
3078 (python-info-dedenter-opening-block-positions)))
3079
3080 (indent-line-to 4)
3081 (should
3082 (equal (list
3083 (python-tests-look-at "if hide_details:" -1 t)
3084 (python-tests-look-at "except Exception:" -1 t)
3085 (python-tests-look-at "if save:" -1 t))
3086 (python-info-dedenter-opening-block-positions)))
3087
3088 (indent-line-to 0)
3089 (should
3090 (equal (list
3091 (python-tests-look-at "if hide_details:" -1 t)
3092 (python-tests-look-at "except Exception:" -1 t)
3093 (python-tests-look-at "if save:" -1 t))
3094 (python-info-dedenter-opening-block-positions)))))
3095
3096 (ert-deftest python-info-dedenter-opening-block-positions-2 ()
3097 "Test detection of opening blocks for elif."
3098 (python-tests-with-temp-buffer
3099 "
3100 if var:
3101 if var2:
3102 something()
3103 elif var3:
3104 something_else()
3105 elif
3106 "
3107 (python-tests-look-at "elif var3:")
3108 (should
3109 (equal (list
3110 (python-tests-look-at "if var2:" -1 t)
3111 (python-tests-look-at "if var:" -1 t))
3112 (python-info-dedenter-opening-block-positions)))
3113
3114 (python-tests-look-at "elif\n")
3115 (should
3116 (equal (list
3117 (python-tests-look-at "elif var3:" -1 t)
3118 (python-tests-look-at "if var:" -1 t))
3119 (python-info-dedenter-opening-block-positions)))))
3120
3121 (ert-deftest python-info-dedenter-opening-block-positions-3 ()
3122 "Test detection of opening blocks for else."
3123 (python-tests-with-temp-buffer
3124 "
3125 try:
3126 something()
3127 except:
3128 if var:
3129 if var2:
3130 something()
3131 elif var3:
3132 something_else()
3133 else
3134
3135 if var4:
3136 while var5:
3137 var4.pop()
3138 else
3139
3140 for value in var6:
3141 if value > 0:
3142 print value
3143 else
3144 "
3145 (python-tests-look-at "else\n")
3146 (should
3147 (equal (list
3148 (python-tests-look-at "elif var3:" -1 t)
3149 (python-tests-look-at "if var:" -1 t)
3150 (python-tests-look-at "except:" -1 t))
3151 (python-info-dedenter-opening-block-positions)))
3152
3153 (python-tests-look-at "else\n")
3154 (should
3155 (equal (list
3156 (python-tests-look-at "while var5:" -1 t)
3157 (python-tests-look-at "if var4:" -1 t))
3158 (python-info-dedenter-opening-block-positions)))
3159
3160 (python-tests-look-at "else\n")
3161 (should
3162 (equal (list
3163 (python-tests-look-at "if value > 0:" -1 t)
3164 (python-tests-look-at "for value in var6:" -1 t)
3165 (python-tests-look-at "if var4:" -1 t))
3166 (python-info-dedenter-opening-block-positions)))))
3167
3168 (ert-deftest python-info-dedenter-opening-block-positions-4 ()
3169 "Test detection of opening blocks for except."
3170 (python-tests-with-temp-buffer
3171 "
3172 try:
3173 something()
3174 except ValueError:
3175 something_else()
3176 except
3177 "
3178 (python-tests-look-at "except ValueError:")
3179 (should
3180 (equal (list (python-tests-look-at "try:" -1 t))
3181 (python-info-dedenter-opening-block-positions)))
3182
3183 (python-tests-look-at "except\n")
3184 (should
3185 (equal (list (python-tests-look-at "except ValueError:" -1 t))
3186 (python-info-dedenter-opening-block-positions)))))
3187
3188 (ert-deftest python-info-dedenter-opening-block-positions-5 ()
3189 "Test detection of opening blocks for finally."
3190 (python-tests-with-temp-buffer
3191 "
3192 try:
3193 something()
3194 finally
3195
3196 try:
3197 something_else()
3198 except:
3199 logger.exception('something went wrong')
3200 finally
3201
3202 try:
3203 something_else_else()
3204 except Exception:
3205 logger.exception('something else went wrong')
3206 else:
3207 print ('all good')
3208 finally
3209 "
3210 (python-tests-look-at "finally\n")
3211 (should
3212 (equal (list (python-tests-look-at "try:" -1 t))
3213 (python-info-dedenter-opening-block-positions)))
3214
3215 (python-tests-look-at "finally\n")
3216 (should
3217 (equal (list (python-tests-look-at "except:" -1 t))
3218 (python-info-dedenter-opening-block-positions)))
3219
3220 (python-tests-look-at "finally\n")
3221 (should
3222 (equal (list (python-tests-look-at "else:" -1 t))
3223 (python-info-dedenter-opening-block-positions)))))
3224
3225 (ert-deftest python-info-dedenter-opening-block-message-1 ()
3226 "Test dedenters inside strings are ignored."
3227 (python-tests-with-temp-buffer
3228 "'''
3229 try:
3230 something()
3231 except:
3232 logger.exception('something went wrong')
3233 '''
3234 "
3235 (python-tests-look-at "except\n")
3236 (should (not (python-info-dedenter-opening-block-message)))))
3237
3238 (ert-deftest python-info-dedenter-opening-block-message-2 ()
3239 "Test except keyword."
3240 (python-tests-with-temp-buffer
3241 "
3242 try:
3243 something()
3244 except:
3245 logger.exception('something went wrong')
3246 "
3247 (python-tests-look-at "except:")
3248 (should (string=
3249 "Closes try:"
3250 (substring-no-properties
3251 (python-info-dedenter-opening-block-message))))
3252 (end-of-line)
3253 (should (string=
3254 "Closes try:"
3255 (substring-no-properties
3256 (python-info-dedenter-opening-block-message))))))
3257
3258 (ert-deftest python-info-dedenter-opening-block-message-3 ()
3259 "Test else keyword."
3260 (python-tests-with-temp-buffer
3261 "
3262 try:
3263 something()
3264 except:
3265 logger.exception('something went wrong')
3266 else:
3267 logger.debug('all good')
3268 "
3269 (python-tests-look-at "else:")
3270 (should (string=
3271 "Closes except:"
3272 (substring-no-properties
3273 (python-info-dedenter-opening-block-message))))
3274 (end-of-line)
3275 (should (string=
3276 "Closes except:"
3277 (substring-no-properties
3278 (python-info-dedenter-opening-block-message))))))
3279
3280 (ert-deftest python-info-dedenter-opening-block-message-4 ()
3281 "Test finally keyword."
3282 (python-tests-with-temp-buffer
3283 "
3284 try:
3285 something()
3286 except:
3287 logger.exception('something went wrong')
3288 else:
3289 logger.debug('all good')
3290 finally:
3291 clean()
3292 "
3293 (python-tests-look-at "finally:")
3294 (should (string=
3295 "Closes else:"
3296 (substring-no-properties
3297 (python-info-dedenter-opening-block-message))))
3298 (end-of-line)
3299 (should (string=
3300 "Closes else:"
3301 (substring-no-properties
3302 (python-info-dedenter-opening-block-message))))))
3303
3304 (ert-deftest python-info-dedenter-opening-block-message-5 ()
3305 "Test elif keyword."
3306 (python-tests-with-temp-buffer
3307 "
3308 if a:
3309 something()
3310 elif b:
3311 "
3312 (python-tests-look-at "elif b:")
3313 (should (string=
3314 "Closes if a:"
3315 (substring-no-properties
3316 (python-info-dedenter-opening-block-message))))
3317 (end-of-line)
3318 (should (string=
3319 "Closes if a:"
3320 (substring-no-properties
3321 (python-info-dedenter-opening-block-message))))))
3322
3323
3324 (ert-deftest python-info-dedenter-statement-p-1 ()
3325 "Test dedenters inside strings are ignored."
3326 (python-tests-with-temp-buffer
3327 "'''
3328 try:
3329 something()
3330 except:
3331 logger.exception('something went wrong')
3332 '''
3333 "
3334 (python-tests-look-at "except\n")
3335 (should (not (python-info-dedenter-statement-p)))))
3336
3337 (ert-deftest python-info-dedenter-statement-p-2 ()
3338 "Test except keyword."
3339 (python-tests-with-temp-buffer
3340 "
3341 try:
3342 something()
3343 except:
3344 logger.exception('something went wrong')
3345 "
3346 (python-tests-look-at "except:")
3347 (should (= (point) (python-info-dedenter-statement-p)))
3348 (end-of-line)
3349 (should (= (save-excursion
3350 (back-to-indentation)
3351 (point))
3352 (python-info-dedenter-statement-p)))))
3353
3354 (ert-deftest python-info-dedenter-statement-p-3 ()
3355 "Test else keyword."
3356 (python-tests-with-temp-buffer
3357 "
3358 try:
3359 something()
3360 except:
3361 logger.exception('something went wrong')
3362 else:
3363 logger.debug('all good')
3364 "
3365 (python-tests-look-at "else:")
3366 (should (= (point) (python-info-dedenter-statement-p)))
3367 (end-of-line)
3368 (should (= (save-excursion
3369 (back-to-indentation)
3370 (point))
3371 (python-info-dedenter-statement-p)))))
3372
3373 (ert-deftest python-info-dedenter-statement-p-4 ()
3374 "Test finally keyword."
3375 (python-tests-with-temp-buffer
3376 "
3377 try:
3378 something()
3379 except:
3380 logger.exception('something went wrong')
3381 else:
3382 logger.debug('all good')
3383 finally:
3384 clean()
3385 "
3386 (python-tests-look-at "finally:")
3387 (should (= (point) (python-info-dedenter-statement-p)))
3388 (end-of-line)
3389 (should (= (save-excursion
3390 (back-to-indentation)
3391 (point))
3392 (python-info-dedenter-statement-p)))))
3393
3394 (ert-deftest python-info-dedenter-statement-p-5 ()
3395 "Test elif keyword."
3396 (python-tests-with-temp-buffer
3397 "
3398 if a:
3399 something()
3400 elif b:
3401 "
3402 (python-tests-look-at "elif b:")
3403 (should (= (point) (python-info-dedenter-statement-p)))
3404 (end-of-line)
3405 (should (= (save-excursion
3406 (back-to-indentation)
3407 (point))
3408 (python-info-dedenter-statement-p)))))
3409
3410 (ert-deftest python-info-line-ends-backslash-p-1 ()
3411 (python-tests-with-temp-buffer
3412 "
3413 objects = Thing.objects.all() \\\\
3414 .filter(
3415 type='toy',
3416 status='bought'
3417 ) \\\\
3418 .aggregate(
3419 Sum('amount')
3420 ) \\\\
3421 .values_list()
3422 "
3423 (should (python-info-line-ends-backslash-p 2)) ; .filter(...
3424 (should (python-info-line-ends-backslash-p 3))
3425 (should (python-info-line-ends-backslash-p 4))
3426 (should (python-info-line-ends-backslash-p 5))
3427 (should (python-info-line-ends-backslash-p 6)) ; ) \...
3428 (should (python-info-line-ends-backslash-p 7))
3429 (should (python-info-line-ends-backslash-p 8))
3430 (should (python-info-line-ends-backslash-p 9))
3431 (should (not (python-info-line-ends-backslash-p 10))))) ; .values_list()...
3432
3433 (ert-deftest python-info-beginning-of-backslash-1 ()
3434 (python-tests-with-temp-buffer
3435 "
3436 objects = Thing.objects.all() \\\\
3437 .filter(
3438 type='toy',
3439 status='bought'
3440 ) \\\\
3441 .aggregate(
3442 Sum('amount')
3443 ) \\\\
3444 .values_list()
3445 "
3446 (let ((first 2)
3447 (second (python-tests-look-at ".filter("))
3448 (third (python-tests-look-at ".aggregate(")))
3449 (should (= first (python-info-beginning-of-backslash 2)))
3450 (should (= second (python-info-beginning-of-backslash 3)))
3451 (should (= second (python-info-beginning-of-backslash 4)))
3452 (should (= second (python-info-beginning-of-backslash 5)))
3453 (should (= second (python-info-beginning-of-backslash 6)))
3454 (should (= third (python-info-beginning-of-backslash 7)))
3455 (should (= third (python-info-beginning-of-backslash 8)))
3456 (should (= third (python-info-beginning-of-backslash 9)))
3457 (should (not (python-info-beginning-of-backslash 10))))))
3458
3459 (ert-deftest python-info-continuation-line-p-1 ()
3460 (python-tests-with-temp-buffer
3461 "
3462 if width == 0 and height == 0 and \\\\
3463 color == 'red' and emphasis == 'strong' or \\\\
3464 highlight > 100:
3465 raise ValueError(
3466 'sorry, you lose'
3467
3468 )
3469 "
3470 (python-tests-look-at "if width == 0 and height == 0 and")
3471 (should (not (python-info-continuation-line-p)))
3472 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3473 (should (python-info-continuation-line-p))
3474 (python-tests-look-at "highlight > 100:")
3475 (should (python-info-continuation-line-p))
3476 (python-tests-look-at "raise ValueError(")
3477 (should (not (python-info-continuation-line-p)))
3478 (python-tests-look-at "'sorry, you lose'")
3479 (should (python-info-continuation-line-p))
3480 (forward-line 1)
3481 (should (python-info-continuation-line-p))
3482 (python-tests-look-at ")")
3483 (should (python-info-continuation-line-p))
3484 (forward-line 1)
3485 (should (not (python-info-continuation-line-p)))))
3486
3487 (ert-deftest python-info-block-continuation-line-p-1 ()
3488 (python-tests-with-temp-buffer
3489 "
3490 if width == 0 and height == 0 and \\\\
3491 color == 'red' and emphasis == 'strong' or \\\\
3492 highlight > 100:
3493 raise ValueError(
3494 'sorry, you lose'
3495
3496 )
3497 "
3498 (python-tests-look-at "if width == 0 and")
3499 (should (not (python-info-block-continuation-line-p)))
3500 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3501 (should (= (python-info-block-continuation-line-p)
3502 (python-tests-look-at "if width == 0 and" -1 t)))
3503 (python-tests-look-at "highlight > 100:")
3504 (should (not (python-info-block-continuation-line-p)))))
3505
3506 (ert-deftest python-info-block-continuation-line-p-2 ()
3507 (python-tests-with-temp-buffer
3508 "
3509 def foo(a,
3510 b,
3511 c):
3512 pass
3513 "
3514 (python-tests-look-at "def foo(a,")
3515 (should (not (python-info-block-continuation-line-p)))
3516 (python-tests-look-at "b,")
3517 (should (= (python-info-block-continuation-line-p)
3518 (python-tests-look-at "def foo(a," -1 t)))
3519 (python-tests-look-at "c):")
3520 (should (not (python-info-block-continuation-line-p)))))
3521
3522 (ert-deftest python-info-assignment-continuation-line-p-1 ()
3523 (python-tests-with-temp-buffer
3524 "
3525 data = foo(), bar() \\\\
3526 baz(), 4 \\\\
3527 5, 6
3528 "
3529 (python-tests-look-at "data = foo(), bar()")
3530 (should (not (python-info-assignment-continuation-line-p)))
3531 (python-tests-look-at "baz(), 4")
3532 (should (= (python-info-assignment-continuation-line-p)
3533 (python-tests-look-at "foo()," -1 t)))
3534 (python-tests-look-at "5, 6")
3535 (should (not (python-info-assignment-continuation-line-p)))))
3536
3537 (ert-deftest python-info-assignment-continuation-line-p-2 ()
3538 (python-tests-with-temp-buffer
3539 "
3540 data = (foo(), bar()
3541 baz(), 4
3542 5, 6)
3543 "
3544 (python-tests-look-at "data = (foo(), bar()")
3545 (should (not (python-info-assignment-continuation-line-p)))
3546 (python-tests-look-at "baz(), 4")
3547 (should (= (python-info-assignment-continuation-line-p)
3548 (python-tests-look-at "(foo()," -1 t)))
3549 (python-tests-look-at "5, 6)")
3550 (should (not (python-info-assignment-continuation-line-p)))))
3551
3552 (ert-deftest python-info-looking-at-beginning-of-defun-1 ()
3553 (python-tests-with-temp-buffer
3554 "
3555 def decorat0r(deff):
3556 '''decorates stuff.
3557
3558 @decorat0r
3559 def foo(arg):
3560 ...
3561 '''
3562 def wrap():
3563 deff()
3564 return wwrap
3565 "
3566 (python-tests-look-at "def decorat0r(deff):")
3567 (should (python-info-looking-at-beginning-of-defun))
3568 (python-tests-look-at "def foo(arg):")
3569 (should (not (python-info-looking-at-beginning-of-defun)))
3570 (python-tests-look-at "def wrap():")
3571 (should (python-info-looking-at-beginning-of-defun))
3572 (python-tests-look-at "deff()")
3573 (should (not (python-info-looking-at-beginning-of-defun)))))
3574
3575 (ert-deftest python-info-current-line-comment-p-1 ()
3576 (python-tests-with-temp-buffer
3577 "
3578 # this is a comment
3579 foo = True # another comment
3580 '#this is a string'
3581 if foo:
3582 # more comments
3583 print ('bar') # print bar
3584 "
3585 (python-tests-look-at "# this is a comment")
3586 (should (python-info-current-line-comment-p))
3587 (python-tests-look-at "foo = True # another comment")
3588 (should (not (python-info-current-line-comment-p)))
3589 (python-tests-look-at "'#this is a string'")
3590 (should (not (python-info-current-line-comment-p)))
3591 (python-tests-look-at "# more comments")
3592 (should (python-info-current-line-comment-p))
3593 (python-tests-look-at "print ('bar') # print bar")
3594 (should (not (python-info-current-line-comment-p)))))
3595
3596 (ert-deftest python-info-current-line-empty-p ()
3597 (python-tests-with-temp-buffer
3598 "
3599 # this is a comment
3600
3601 foo = True # another comment
3602 "
3603 (should (python-info-current-line-empty-p))
3604 (python-tests-look-at "# this is a comment")
3605 (should (not (python-info-current-line-empty-p)))
3606 (forward-line 1)
3607 (should (python-info-current-line-empty-p))))
3608
3609 \f
3610 ;;; Utility functions
3611
3612 (ert-deftest python-util-goto-line-1 ()
3613 (python-tests-with-temp-buffer
3614 (concat
3615 "# a comment
3616 # another comment
3617 def foo(a, b, c):
3618 pass" (make-string 20 ?\n))
3619 (python-util-goto-line 10)
3620 (should (= (line-number-at-pos) 10))
3621 (python-util-goto-line 20)
3622 (should (= (line-number-at-pos) 20))))
3623
3624 (ert-deftest python-util-clone-local-variables-1 ()
3625 (let ((buffer (generate-new-buffer
3626 "python-util-clone-local-variables-1"))
3627 (varcons
3628 '((python-fill-docstring-style . django)
3629 (python-shell-interpreter . "python")
3630 (python-shell-interpreter-args . "manage.py shell")
3631 (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
3632 (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
3633 (python-shell-extra-pythonpaths "/home/user/pylib/")
3634 (python-shell-completion-setup-code
3635 . "from IPython.core.completerlib import module_completion")
3636 (python-shell-completion-string-code
3637 . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
3638 (python-shell-virtualenv-path
3639 . "/home/user/.virtualenvs/project"))))
3640 (with-current-buffer buffer
3641 (kill-all-local-variables)
3642 (dolist (ccons varcons)
3643 (set (make-local-variable (car ccons)) (cdr ccons))))
3644 (python-tests-with-temp-buffer
3645 ""
3646 (python-util-clone-local-variables buffer)
3647 (dolist (ccons varcons)
3648 (should
3649 (equal (symbol-value (car ccons)) (cdr ccons)))))
3650 (kill-buffer buffer)))
3651
3652 (ert-deftest python-util-strip-string-1 ()
3653 (should (string= (python-util-strip-string "\t\r\n str") "str"))
3654 (should (string= (python-util-strip-string "str \n\r") "str"))
3655 (should (string= (python-util-strip-string "\t\r\n str \n\r ") "str"))
3656 (should
3657 (string= (python-util-strip-string "\n str \nin \tg \n\r") "str \nin \tg"))
3658 (should (string= (python-util-strip-string "\n \t \n\r ") ""))
3659 (should (string= (python-util-strip-string "") "")))
3660
3661 (ert-deftest python-util-forward-comment-1 ()
3662 (python-tests-with-temp-buffer
3663 (concat
3664 "# a comment
3665 # another comment
3666 # bad indented comment
3667 # more comments" (make-string 9999 ?\n))
3668 (python-util-forward-comment 1)
3669 (should (= (point) (point-max)))
3670 (python-util-forward-comment -1)
3671 (should (= (point) (point-min)))))
3672
3673 (ert-deftest python-util-valid-regexp-p-1 ()
3674 (should (python-util-valid-regexp-p ""))
3675 (should (python-util-valid-regexp-p python-shell-prompt-regexp))
3676 (should (not (python-util-valid-regexp-p "\\("))))
3677
3678 \f
3679 ;;; Electricity
3680
3681 (ert-deftest python-parens-electric-indent-1 ()
3682 (require 'electric)
3683 (let ((eim electric-indent-mode))
3684 (unwind-protect
3685 (progn
3686 (python-tests-with-temp-buffer
3687 "
3688 from django.conf.urls import patterns, include, url
3689
3690 from django.contrib import admin
3691
3692 from myapp import views
3693
3694
3695 urlpatterns = patterns('',
3696 url(r'^$', views.index
3697 )
3698 "
3699 (electric-indent-mode 1)
3700 (python-tests-look-at "views.index")
3701 (end-of-line)
3702
3703 ;; Inserting commas within the same line should leave
3704 ;; indentation unchanged.
3705 (python-tests-self-insert ",")
3706 (should (= (current-indentation) 4))
3707
3708 ;; As well as any other input happening within the same
3709 ;; set of parens.
3710 (python-tests-self-insert " name='index')")
3711 (should (= (current-indentation) 4))
3712
3713 ;; But a comma outside it, should trigger indentation.
3714 (python-tests-self-insert ",")
3715 (should (= (current-indentation) 23))
3716
3717 ;; Newline indents to the first argument column
3718 (python-tests-self-insert "\n")
3719 (should (= (current-indentation) 23))
3720
3721 ;; All this input must not change indentation
3722 (indent-line-to 4)
3723 (python-tests-self-insert "url(r'^/login$', views.login)")
3724 (should (= (current-indentation) 4))
3725
3726 ;; But this comma does
3727 (python-tests-self-insert ",")
3728 (should (= (current-indentation) 23))))
3729 (or eim (electric-indent-mode -1)))))
3730
3731 (ert-deftest python-triple-quote-pairing ()
3732 (require 'electric)
3733 (let ((epm electric-pair-mode))
3734 (unwind-protect
3735 (progn
3736 (python-tests-with-temp-buffer
3737 "\"\"\n"
3738 (or epm (electric-pair-mode 1))
3739 (goto-char (1- (point-max)))
3740 (python-tests-self-insert ?\")
3741 (should (string= (buffer-string)
3742 "\"\"\"\"\"\"\n"))
3743 (should (= (point) 4)))
3744 (python-tests-with-temp-buffer
3745 "\n"
3746 (python-tests-self-insert (list ?\" ?\" ?\"))
3747 (should (string= (buffer-string)
3748 "\"\"\"\"\"\"\n"))
3749 (should (= (point) 4)))
3750 (python-tests-with-temp-buffer
3751 "\"\n\"\"\n"
3752 (goto-char (1- (point-max)))
3753 (python-tests-self-insert ?\")
3754 (should (= (point) (1- (point-max))))
3755 (should (string= (buffer-string)
3756 "\"\n\"\"\"\n"))))
3757 (or epm (electric-pair-mode -1)))))
3758
3759
3760 (provide 'python-tests)
3761
3762 ;; Local Variables:
3763 ;; coding: utf-8
3764 ;; indent-tabs-mode: nil
3765 ;; End:
3766
3767 ;;; python-tests.el ends here