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