python.el: Enhancements to process environment setup.
[emacs.git] / test / automated / python-tests.el
blob1f8533f9b1a80b1b67a98ace86a964b4da358c93
1 ;;; python-tests.el --- Test suite for python.el
3 ;; Copyright (C) 2013-2015 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
7 ;; GNU Emacs is free software: you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
20 ;;; Commentary:
22 ;;; Code:
24 (require 'ert)
25 (require 'python)
27 ;; Dependencies for testing:
28 (require 'electric)
29 (require 'hideshow)
30 (require 'tramp-sh)
33 (defmacro python-tests-with-temp-buffer (contents &rest body)
34 "Create a `python-mode' enabled temp buffer with CONTENTS.
35 BODY is code to be executed within the temp buffer. Point is
36 always located at the beginning of buffer."
37 (declare (indent 1) (debug t))
38 `(with-temp-buffer
39 (python-mode)
40 (insert ,contents)
41 (goto-char (point-min))
42 ,@body))
44 (defmacro python-tests-with-temp-file (contents &rest body)
45 "Create a `python-mode' enabled file with CONTENTS.
46 BODY is code to be executed within the temp buffer. Point is
47 always located at the beginning of buffer."
48 (declare (indent 1) (debug t))
49 ;; temp-file never actually used for anything?
50 `(let* ((temp-file (make-temp-file "python-tests" nil ".py"))
51 (buffer (find-file-noselect temp-file)))
52 (unwind-protect
53 (with-current-buffer buffer
54 (python-mode)
55 (insert ,contents)
56 (goto-char (point-min))
57 ,@body)
58 (and buffer (kill-buffer buffer))
59 (delete-file temp-file))))
61 (defun python-tests-look-at (string &optional num restore-point)
62 "Move point at beginning of STRING in the current buffer.
63 Optional argument NUM defaults to 1 and is an integer indicating
64 how many occurrences must be found, when positive the search is
65 done forwards, otherwise backwards. When RESTORE-POINT is
66 non-nil the point is not moved but the position found is still
67 returned. When searching forward and point is already looking at
68 STRING, it is skipped so the next STRING occurrence is selected."
69 (let* ((num (or num 1))
70 (starting-point (point))
71 (string (regexp-quote string))
72 (search-fn (if (> num 0) #'re-search-forward #'re-search-backward))
73 (deinc-fn (if (> num 0) #'1- #'1+))
74 (found-point))
75 (prog2
76 (catch 'exit
77 (while (not (= num 0))
78 (when (and (> num 0)
79 (looking-at string))
80 ;; Moving forward and already looking at STRING, skip it.
81 (forward-char (length (match-string-no-properties 0))))
82 (and (not (funcall search-fn string nil t))
83 (throw 'exit t))
84 (when (> num 0)
85 ;; `re-search-forward' leaves point at the end of the
86 ;; occurrence, move back so point is at the beginning
87 ;; instead.
88 (forward-char (- (length (match-string-no-properties 0)))))
89 (setq
90 num (funcall deinc-fn num)
91 found-point (point))))
92 found-point
93 (and restore-point (goto-char starting-point)))))
95 (defun python-tests-self-insert (char-or-str)
96 "Call `self-insert-command' for chars in CHAR-OR-STR."
97 (let ((chars
98 (cond
99 ((characterp char-or-str)
100 (list char-or-str))
101 ((stringp char-or-str)
102 (string-to-list char-or-str))
103 ((not
104 (cl-remove-if #'characterp char-or-str))
105 char-or-str)
106 (t (error "CHAR-OR-STR must be a char, string, or list of char")))))
107 (mapc
108 (lambda (char)
109 (let ((last-command-event char))
110 (call-interactively 'self-insert-command)))
111 chars)))
113 (defun python-tests-visible-string (&optional min max)
114 "Return the buffer string excluding invisible overlays.
115 Argument MIN and MAX delimit the region to be returned and
116 default to `point-min' and `point-max' respectively."
117 (let* ((min (or min (point-min)))
118 (max (or max (point-max)))
119 (buffer (current-buffer))
120 (buffer-contents (buffer-substring-no-properties min max))
121 (overlays
122 (sort (overlays-in min max)
123 (lambda (a b)
124 (let ((overlay-end-a (overlay-end a))
125 (overlay-end-b (overlay-end b)))
126 (> overlay-end-a overlay-end-b))))))
127 (with-temp-buffer
128 (insert buffer-contents)
129 (dolist (overlay overlays)
130 (if (overlay-get overlay 'invisible)
131 (delete-region (overlay-start overlay)
132 (overlay-end overlay))))
133 (buffer-substring-no-properties (point-min) (point-max)))))
136 ;;; Tests for your tests, so you can test while you test.
138 (ert-deftest python-tests-look-at-1 ()
139 "Test forward movement."
140 (python-tests-with-temp-buffer
141 "Lorem ipsum dolor sit amet, consectetur adipisicing elit,
142 sed do eiusmod tempor incididunt ut labore et dolore magna
143 aliqua."
144 (let ((expected (save-excursion
145 (dotimes (i 3)
146 (re-search-forward "et" nil t))
147 (forward-char -2)
148 (point))))
149 (should (= (python-tests-look-at "et" 3 t) expected))
150 ;; Even if NUM is bigger than found occurrences the point of last
151 ;; one should be returned.
152 (should (= (python-tests-look-at "et" 6 t) expected))
153 ;; If already looking at STRING, it should skip it.
154 (dotimes (i 2) (re-search-forward "et"))
155 (forward-char -2)
156 (should (= (python-tests-look-at "et") expected)))))
158 (ert-deftest python-tests-look-at-2 ()
159 "Test backward movement."
160 (python-tests-with-temp-buffer
161 "Lorem ipsum dolor sit amet, consectetur adipisicing elit,
162 sed do eiusmod tempor incididunt ut labore et dolore magna
163 aliqua."
164 (let ((expected
165 (save-excursion
166 (re-search-forward "et" nil t)
167 (forward-char -2)
168 (point))))
169 (dotimes (i 3)
170 (re-search-forward "et" nil t))
171 (should (= (python-tests-look-at "et" -3 t) expected))
172 (should (= (python-tests-look-at "et" -6 t) expected)))))
175 ;;; Bindings
178 ;;; Python specialized rx
181 ;;; Font-lock and syntax
183 (ert-deftest python-syntax-after-python-backspace ()
184 ;; `python-indent-dedent-line-backspace' garbles syntax
185 :expected-result :failed
186 (python-tests-with-temp-buffer
187 "\"\"\""
188 (goto-char (point-max))
189 (python-indent-dedent-line-backspace 1)
190 (should (string= (buffer-string) "\"\""))
191 (should (null (nth 3 (syntax-ppss))))))
194 ;;; Indentation
196 ;; See: http://www.python.org/dev/peps/pep-0008/#indentation
198 (ert-deftest python-indent-pep8-1 ()
199 "First pep8 case."
200 (python-tests-with-temp-buffer
201 "# Aligned with opening delimiter
202 foo = long_function_name(var_one, var_two,
203 var_three, var_four)
205 (should (eq (car (python-indent-context)) :no-indent))
206 (should (= (python-indent-calculate-indentation) 0))
207 (python-tests-look-at "foo = long_function_name(var_one, var_two,")
208 (should (eq (car (python-indent-context)) :after-comment))
209 (should (= (python-indent-calculate-indentation) 0))
210 (python-tests-look-at "var_three, var_four)")
211 (should (eq (car (python-indent-context)) :inside-paren))
212 (should (= (python-indent-calculate-indentation) 25))))
214 (ert-deftest python-indent-pep8-2 ()
215 "Second pep8 case."
216 (python-tests-with-temp-buffer
217 "# More indentation included to distinguish this from the rest.
218 def long_function_name(
219 var_one, var_two, var_three,
220 var_four):
221 print (var_one)
223 (should (eq (car (python-indent-context)) :no-indent))
224 (should (= (python-indent-calculate-indentation) 0))
225 (python-tests-look-at "def long_function_name(")
226 (should (eq (car (python-indent-context)) :after-comment))
227 (should (= (python-indent-calculate-indentation) 0))
228 (python-tests-look-at "var_one, var_two, var_three,")
229 (should (eq (car (python-indent-context))
230 :inside-paren-newline-start-from-block))
231 (should (= (python-indent-calculate-indentation) 8))
232 (python-tests-look-at "var_four):")
233 (should (eq (car (python-indent-context))
234 :inside-paren-newline-start-from-block))
235 (should (= (python-indent-calculate-indentation) 8))
236 (python-tests-look-at "print (var_one)")
237 (should (eq (car (python-indent-context))
238 :after-block-start))
239 (should (= (python-indent-calculate-indentation) 4))))
241 (ert-deftest python-indent-pep8-3 ()
242 "Third pep8 case."
243 (python-tests-with-temp-buffer
244 "# Extra indentation is not necessary.
245 foo = long_function_name(
246 var_one, var_two,
247 var_three, var_four)
249 (should (eq (car (python-indent-context)) :no-indent))
250 (should (= (python-indent-calculate-indentation) 0))
251 (python-tests-look-at "foo = long_function_name(")
252 (should (eq (car (python-indent-context)) :after-comment))
253 (should (= (python-indent-calculate-indentation) 0))
254 (python-tests-look-at "var_one, var_two,")
255 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
256 (should (= (python-indent-calculate-indentation) 4))
257 (python-tests-look-at "var_three, var_four)")
258 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
259 (should (= (python-indent-calculate-indentation) 4))))
261 (ert-deftest python-indent-base-case ()
262 "Check base case does not trigger errors."
263 (python-tests-with-temp-buffer
267 (goto-char (point-min))
268 (should (eq (car (python-indent-context)) :no-indent))
269 (should (= (python-indent-calculate-indentation) 0))
270 (forward-line 1)
271 (should (eq (car (python-indent-context)) :no-indent))
272 (should (= (python-indent-calculate-indentation) 0))
273 (forward-line 1)
274 (should (eq (car (python-indent-context)) :no-indent))
275 (should (= (python-indent-calculate-indentation) 0))))
277 (ert-deftest python-indent-after-comment-1 ()
278 "The most simple after-comment case that shouldn't fail."
279 (python-tests-with-temp-buffer
280 "# Contents will be modified to correct indentation
281 class Blag(object):
282 def _on_child_complete(self, child_future):
283 if self.in_terminal_state():
284 pass
285 # We only complete when all our async children have entered a
286 # terminal state. At that point, if any child failed, we fail
287 # with the exception with which the first child failed.
289 (python-tests-look-at "# We only complete")
290 (should (eq (car (python-indent-context)) :after-block-end))
291 (should (= (python-indent-calculate-indentation) 8))
292 (python-tests-look-at "# terminal state")
293 (should (eq (car (python-indent-context)) :after-comment))
294 (should (= (python-indent-calculate-indentation) 8))
295 (python-tests-look-at "# with the exception")
296 (should (eq (car (python-indent-context)) :after-comment))
297 ;; This one indents relative to previous block, even given the fact
298 ;; that it was under-indented.
299 (should (= (python-indent-calculate-indentation) 4))
300 (python-tests-look-at "# terminal state" -1)
301 ;; It doesn't hurt to check again.
302 (should (eq (car (python-indent-context)) :after-comment))
303 (python-indent-line)
304 (should (= (current-indentation) 8))
305 (python-tests-look-at "# with the exception")
306 (should (eq (car (python-indent-context)) :after-comment))
307 ;; Now everything should be lined up.
308 (should (= (python-indent-calculate-indentation) 8))))
310 (ert-deftest python-indent-after-comment-2 ()
311 "Test after-comment in weird cases."
312 (python-tests-with-temp-buffer
313 "# Contents will be modified to correct indentation
314 def func(arg):
315 # I don't do much
316 return arg
317 # This comment is badly indented because the user forced so.
318 # At this line python.el wont dedent, user is always right.
320 comment_wins_over_ender = True
322 # yeah, that.
324 (python-tests-look-at "# I don't do much")
325 (should (eq (car (python-indent-context)) :after-block-start))
326 (should (= (python-indent-calculate-indentation) 4))
327 (python-tests-look-at "return arg")
328 ;; Comment here just gets ignored, this line is not a comment so
329 ;; the rules won't apply here.
330 (should (eq (car (python-indent-context)) :after-block-start))
331 (should (= (python-indent-calculate-indentation) 4))
332 (python-tests-look-at "# This comment is badly indented")
333 (should (eq (car (python-indent-context)) :after-block-end))
334 ;; The return keyword do make indentation lose a level...
335 (should (= (python-indent-calculate-indentation) 0))
336 ;; ...but the current indentation was forced by the user.
337 (python-tests-look-at "# At this line python.el wont dedent")
338 (should (eq (car (python-indent-context)) :after-comment))
339 (should (= (python-indent-calculate-indentation) 4))
340 ;; Should behave the same for blank lines: potentially a comment.
341 (forward-line 1)
342 (should (eq (car (python-indent-context)) :after-comment))
343 (should (= (python-indent-calculate-indentation) 4))
344 (python-tests-look-at "comment_wins_over_ender")
345 ;; The comment won over the ender because the user said so.
346 (should (eq (car (python-indent-context)) :after-comment))
347 (should (= (python-indent-calculate-indentation) 4))
348 ;; The indentation calculated fine for the assignment, but the user
349 ;; choose to force it back to the first column. Next line should
350 ;; be aware of that.
351 (python-tests-look-at "# yeah, that.")
352 (should (eq (car (python-indent-context)) :after-line))
353 (should (= (python-indent-calculate-indentation) 0))))
355 (ert-deftest python-indent-after-comment-3 ()
356 "Test after-comment in buggy case."
357 (python-tests-with-temp-buffer
359 class A(object):
361 def something(self, arg):
362 if True:
363 return arg
365 # A comment
367 @adecorator
368 def method(self, a, b):
369 pass
371 (python-tests-look-at "@adecorator")
372 (should (eq (car (python-indent-context)) :after-comment))
373 (should (= (python-indent-calculate-indentation) 4))))
375 (ert-deftest python-indent-inside-paren-1 ()
376 "The most simple inside-paren case that shouldn't fail."
377 (python-tests-with-temp-buffer
379 data = {
380 'key':
382 'objlist': [
384 'pk': 1,
385 'name': 'first',
388 'pk': 2,
389 'name': 'second',
395 (python-tests-look-at "data = {")
396 (should (eq (car (python-indent-context)) :no-indent))
397 (should (= (python-indent-calculate-indentation) 0))
398 (python-tests-look-at "'key':")
399 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
400 (should (= (python-indent-calculate-indentation) 4))
401 (python-tests-look-at "{")
402 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
403 (should (= (python-indent-calculate-indentation) 4))
404 (python-tests-look-at "'objlist': [")
405 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
406 (should (= (python-indent-calculate-indentation) 8))
407 (python-tests-look-at "{")
408 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
409 (should (= (python-indent-calculate-indentation) 12))
410 (python-tests-look-at "'pk': 1,")
411 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
412 (should (= (python-indent-calculate-indentation) 16))
413 (python-tests-look-at "'name': 'first',")
414 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
415 (should (= (python-indent-calculate-indentation) 16))
416 (python-tests-look-at "},")
417 (should (eq (car (python-indent-context))
418 :inside-paren-at-closing-nested-paren))
419 (should (= (python-indent-calculate-indentation) 12))
420 (python-tests-look-at "{")
421 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
422 (should (= (python-indent-calculate-indentation) 12))
423 (python-tests-look-at "'pk': 2,")
424 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
425 (should (= (python-indent-calculate-indentation) 16))
426 (python-tests-look-at "'name': 'second',")
427 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
428 (should (= (python-indent-calculate-indentation) 16))
429 (python-tests-look-at "}")
430 (should (eq (car (python-indent-context))
431 :inside-paren-at-closing-nested-paren))
432 (should (= (python-indent-calculate-indentation) 12))
433 (python-tests-look-at "]")
434 (should (eq (car (python-indent-context))
435 :inside-paren-at-closing-nested-paren))
436 (should (= (python-indent-calculate-indentation) 8))
437 (python-tests-look-at "}")
438 (should (eq (car (python-indent-context))
439 :inside-paren-at-closing-nested-paren))
440 (should (= (python-indent-calculate-indentation) 4))
441 (python-tests-look-at "}")
442 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
443 (should (= (python-indent-calculate-indentation) 0))))
445 (ert-deftest python-indent-inside-paren-2 ()
446 "Another more compact paren group style."
447 (python-tests-with-temp-buffer
449 data = {'key': {
450 'objlist': [
451 {'pk': 1,
452 'name': 'first'},
453 {'pk': 2,
454 'name': 'second'}
458 (python-tests-look-at "data = {")
459 (should (eq (car (python-indent-context)) :no-indent))
460 (should (= (python-indent-calculate-indentation) 0))
461 (python-tests-look-at "'objlist': [")
462 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
463 (should (= (python-indent-calculate-indentation) 4))
464 (python-tests-look-at "{'pk': 1,")
465 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
466 (should (= (python-indent-calculate-indentation) 8))
467 (python-tests-look-at "'name': 'first'},")
468 (should (eq (car (python-indent-context)) :inside-paren))
469 (should (= (python-indent-calculate-indentation) 9))
470 (python-tests-look-at "{'pk': 2,")
471 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
472 (should (= (python-indent-calculate-indentation) 8))
473 (python-tests-look-at "'name': 'second'}")
474 (should (eq (car (python-indent-context)) :inside-paren))
475 (should (= (python-indent-calculate-indentation) 9))
476 (python-tests-look-at "]")
477 (should (eq (car (python-indent-context))
478 :inside-paren-at-closing-nested-paren))
479 (should (= (python-indent-calculate-indentation) 4))
480 (python-tests-look-at "}}")
481 (should (eq (car (python-indent-context))
482 :inside-paren-at-closing-nested-paren))
483 (should (= (python-indent-calculate-indentation) 0))
484 (python-tests-look-at "}")
485 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
486 (should (= (python-indent-calculate-indentation) 0))))
488 (ert-deftest python-indent-inside-paren-3 ()
489 "The simplest case possible."
490 (python-tests-with-temp-buffer
492 data = ('these',
493 'are',
494 'the',
495 'tokens')
497 (python-tests-look-at "data = ('these',")
498 (should (eq (car (python-indent-context)) :no-indent))
499 (should (= (python-indent-calculate-indentation) 0))
500 (forward-line 1)
501 (should (eq (car (python-indent-context)) :inside-paren))
502 (should (= (python-indent-calculate-indentation) 8))
503 (forward-line 1)
504 (should (eq (car (python-indent-context)) :inside-paren))
505 (should (= (python-indent-calculate-indentation) 8))
506 (forward-line 1)
507 (should (eq (car (python-indent-context)) :inside-paren))
508 (should (= (python-indent-calculate-indentation) 8))))
510 (ert-deftest python-indent-inside-paren-4 ()
511 "Respect indentation of first column."
512 (python-tests-with-temp-buffer
514 data = [ [ 'these', 'are'],
515 ['the', 'tokens' ] ]
517 (python-tests-look-at "data = [ [ 'these', 'are'],")
518 (should (eq (car (python-indent-context)) :no-indent))
519 (should (= (python-indent-calculate-indentation) 0))
520 (forward-line 1)
521 (should (eq (car (python-indent-context)) :inside-paren))
522 (should (= (python-indent-calculate-indentation) 9))))
524 (ert-deftest python-indent-inside-paren-5 ()
525 "Test when :inside-paren initial parens are skipped in context start."
526 (python-tests-with-temp-buffer
528 while ((not some_condition) and
529 another_condition):
530 do_something_interesting(
531 with_some_arg)
533 (python-tests-look-at "while ((not some_condition) and")
534 (should (eq (car (python-indent-context)) :no-indent))
535 (should (= (python-indent-calculate-indentation) 0))
536 (forward-line 1)
537 (should (eq (car (python-indent-context)) :inside-paren))
538 (should (= (python-indent-calculate-indentation) 7))
539 (forward-line 1)
540 (should (eq (car (python-indent-context)) :after-block-start))
541 (should (= (python-indent-calculate-indentation) 4))
542 (forward-line 1)
543 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
544 (should (= (python-indent-calculate-indentation) 8))))
546 (ert-deftest python-indent-inside-paren-6 ()
547 "This should be aligned.."
548 (python-tests-with-temp-buffer
550 CHOICES = (('some', 'choice'),
551 ('another', 'choice'),
552 ('more', 'choices'))
554 (python-tests-look-at "CHOICES = (('some', 'choice'),")
555 (should (eq (car (python-indent-context)) :no-indent))
556 (should (= (python-indent-calculate-indentation) 0))
557 (forward-line 1)
558 (should (eq (car (python-indent-context)) :inside-paren))
559 (should (= (python-indent-calculate-indentation) 11))
560 (forward-line 1)
561 (should (eq (car (python-indent-context)) :inside-paren))
562 (should (= (python-indent-calculate-indentation) 11))))
564 (ert-deftest python-indent-after-block-1 ()
565 "The most simple after-block case that shouldn't fail."
566 (python-tests-with-temp-buffer
568 def foo(a, b, c=True):
570 (should (eq (car (python-indent-context)) :no-indent))
571 (should (= (python-indent-calculate-indentation) 0))
572 (goto-char (point-max))
573 (should (eq (car (python-indent-context)) :after-block-start))
574 (should (= (python-indent-calculate-indentation) 4))))
576 (ert-deftest python-indent-after-block-2 ()
577 "A weird (malformed) multiline block statement."
578 (python-tests-with-temp-buffer
580 def foo(a, b, c={
581 'a':
584 (goto-char (point-max))
585 (should (eq (car (python-indent-context)) :after-block-start))
586 (should (= (python-indent-calculate-indentation) 4))))
588 (ert-deftest python-indent-after-block-3 ()
589 "A weird (malformed) sample, usually found in python shells."
590 (python-tests-with-temp-buffer
592 In [1]:
593 def func():
594 pass
596 In [2]:
597 something
599 (python-tests-look-at "pass")
600 (should (eq (car (python-indent-context)) :after-block-start))
601 (should (= (python-indent-calculate-indentation) 4))
602 (python-tests-look-at "something")
603 (end-of-line)
604 (should (eq (car (python-indent-context)) :after-line))
605 (should (= (python-indent-calculate-indentation) 0))))
607 (ert-deftest python-indent-after-backslash-1 ()
608 "The most common case."
609 (python-tests-with-temp-buffer
611 from foo.bar.baz import something, something_1 \\\\
612 something_2 something_3, \\\\
613 something_4, something_5
615 (python-tests-look-at "from foo.bar.baz import something, something_1")
616 (should (eq (car (python-indent-context)) :no-indent))
617 (should (= (python-indent-calculate-indentation) 0))
618 (python-tests-look-at "something_2 something_3,")
619 (should (eq (car (python-indent-context)) :after-backslash-first-line))
620 (should (= (python-indent-calculate-indentation) 4))
621 (python-tests-look-at "something_4, something_5")
622 (should (eq (car (python-indent-context)) :after-backslash))
623 (should (= (python-indent-calculate-indentation) 4))
624 (goto-char (point-max))
625 (should (eq (car (python-indent-context)) :after-line))
626 (should (= (python-indent-calculate-indentation) 0))))
628 (ert-deftest python-indent-after-backslash-2 ()
629 "A pretty extreme complicated case."
630 (python-tests-with-temp-buffer
632 objects = Thing.objects.all() \\\\
633 .filter(
634 type='toy',
635 status='bought'
636 ) \\\\
637 .aggregate(
638 Sum('amount')
639 ) \\\\
640 .values_list()
642 (python-tests-look-at "objects = Thing.objects.all()")
643 (should (eq (car (python-indent-context)) :no-indent))
644 (should (= (python-indent-calculate-indentation) 0))
645 (python-tests-look-at ".filter(")
646 (should (eq (car (python-indent-context))
647 :after-backslash-dotted-continuation))
648 (should (= (python-indent-calculate-indentation) 23))
649 (python-tests-look-at "type='toy',")
650 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
651 (should (= (python-indent-calculate-indentation) 27))
652 (python-tests-look-at "status='bought'")
653 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
654 (should (= (python-indent-calculate-indentation) 27))
655 (python-tests-look-at ") \\\\")
656 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
657 (should (= (python-indent-calculate-indentation) 23))
658 (python-tests-look-at ".aggregate(")
659 (should (eq (car (python-indent-context))
660 :after-backslash-dotted-continuation))
661 (should (= (python-indent-calculate-indentation) 23))
662 (python-tests-look-at "Sum('amount')")
663 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
664 (should (= (python-indent-calculate-indentation) 27))
665 (python-tests-look-at ") \\\\")
666 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
667 (should (= (python-indent-calculate-indentation) 23))
668 (python-tests-look-at ".values_list()")
669 (should (eq (car (python-indent-context))
670 :after-backslash-dotted-continuation))
671 (should (= (python-indent-calculate-indentation) 23))
672 (forward-line 1)
673 (should (eq (car (python-indent-context)) :after-line))
674 (should (= (python-indent-calculate-indentation) 0))))
676 (ert-deftest python-indent-after-backslash-3 ()
677 "Backslash continuation from block start."
678 (python-tests-with-temp-buffer
680 with open('/path/to/some/file/you/want/to/read') as file_1, \\\\
681 open('/path/to/some/file/being/written', 'w') as file_2:
682 file_2.write(file_1.read())
684 (python-tests-look-at
685 "with open('/path/to/some/file/you/want/to/read') as file_1, \\\\")
686 (should (eq (car (python-indent-context)) :no-indent))
687 (should (= (python-indent-calculate-indentation) 0))
688 (python-tests-look-at
689 "open('/path/to/some/file/being/written', 'w') as file_2")
690 (should (eq (car (python-indent-context))
691 :after-backslash-block-continuation))
692 (should (= (python-indent-calculate-indentation) 5))
693 (python-tests-look-at "file_2.write(file_1.read())")
694 (should (eq (car (python-indent-context)) :after-block-start))
695 (should (= (python-indent-calculate-indentation) 4))))
697 (ert-deftest python-indent-after-backslash-4 ()
698 "Backslash continuation from assignment."
699 (python-tests-with-temp-buffer
701 super_awful_assignment = some_calculation() and \\\\
702 another_calculation() and \\\\
703 some_final_calculation()
705 (python-tests-look-at
706 "super_awful_assignment = some_calculation() and \\\\")
707 (should (eq (car (python-indent-context)) :no-indent))
708 (should (= (python-indent-calculate-indentation) 0))
709 (python-tests-look-at "another_calculation() and \\\\")
710 (should (eq (car (python-indent-context))
711 :after-backslash-assignment-continuation))
712 (should (= (python-indent-calculate-indentation) 25))
713 (python-tests-look-at "some_final_calculation()")
714 (should (eq (car (python-indent-context)) :after-backslash))
715 (should (= (python-indent-calculate-indentation) 25))))
717 (ert-deftest python-indent-after-backslash-5 ()
718 "Dotted continuation bizarre example."
719 (python-tests-with-temp-buffer
721 def delete_all_things():
722 Thing \\\\
723 .objects.all() \\\\
724 .delete()
726 (python-tests-look-at "Thing \\\\")
727 (should (eq (car (python-indent-context)) :after-block-start))
728 (should (= (python-indent-calculate-indentation) 4))
729 (python-tests-look-at ".objects.all() \\\\")
730 (should (eq (car (python-indent-context)) :after-backslash-first-line))
731 (should (= (python-indent-calculate-indentation) 8))
732 (python-tests-look-at ".delete()")
733 (should (eq (car (python-indent-context))
734 :after-backslash-dotted-continuation))
735 (should (= (python-indent-calculate-indentation) 16))))
737 (ert-deftest python-indent-block-enders-1 ()
738 "Test de-indentation for pass keyword."
739 (python-tests-with-temp-buffer
741 Class foo(object):
743 def bar(self):
744 if self.baz:
745 return (1,
749 else:
750 pass
752 (python-tests-look-at "3)")
753 (forward-line 1)
754 (should (= (python-indent-calculate-indentation) 8))
755 (python-tests-look-at "pass")
756 (forward-line 1)
757 (should (eq (car (python-indent-context)) :after-block-end))
758 (should (= (python-indent-calculate-indentation) 8))))
760 (ert-deftest python-indent-block-enders-2 ()
761 "Test de-indentation for return keyword."
762 (python-tests-with-temp-buffer
764 Class foo(object):
765 '''raise lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
767 eiusmod tempor incididunt ut labore et dolore magna aliqua.
769 def bar(self):
770 \"return (1, 2, 3).\"
771 if self.baz:
772 return (1,
776 (python-tests-look-at "def")
777 (should (= (python-indent-calculate-indentation) 4))
778 (python-tests-look-at "if")
779 (should (= (python-indent-calculate-indentation) 8))
780 (python-tests-look-at "return")
781 (should (= (python-indent-calculate-indentation) 12))
782 (goto-char (point-max))
783 (should (eq (car (python-indent-context)) :after-block-end))
784 (should (= (python-indent-calculate-indentation) 8))))
786 (ert-deftest python-indent-block-enders-3 ()
787 "Test de-indentation for continue keyword."
788 (python-tests-with-temp-buffer
790 for element in lst:
791 if element is None:
792 continue
794 (python-tests-look-at "if")
795 (should (= (python-indent-calculate-indentation) 4))
796 (python-tests-look-at "continue")
797 (should (= (python-indent-calculate-indentation) 8))
798 (forward-line 1)
799 (should (eq (car (python-indent-context)) :after-block-end))
800 (should (= (python-indent-calculate-indentation) 4))))
802 (ert-deftest python-indent-block-enders-4 ()
803 "Test de-indentation for break keyword."
804 (python-tests-with-temp-buffer
806 for element in lst:
807 if element is None:
808 break
810 (python-tests-look-at "if")
811 (should (= (python-indent-calculate-indentation) 4))
812 (python-tests-look-at "break")
813 (should (= (python-indent-calculate-indentation) 8))
814 (forward-line 1)
815 (should (eq (car (python-indent-context)) :after-block-end))
816 (should (= (python-indent-calculate-indentation) 4))))
818 (ert-deftest python-indent-block-enders-5 ()
819 "Test de-indentation for raise keyword."
820 (python-tests-with-temp-buffer
822 for element in lst:
823 if element is None:
824 raise ValueError('Element cannot be None')
826 (python-tests-look-at "if")
827 (should (= (python-indent-calculate-indentation) 4))
828 (python-tests-look-at "raise")
829 (should (= (python-indent-calculate-indentation) 8))
830 (forward-line 1)
831 (should (eq (car (python-indent-context)) :after-block-end))
832 (should (= (python-indent-calculate-indentation) 4))))
834 (ert-deftest python-indent-dedenters-1 ()
835 "Test de-indentation for the elif keyword."
836 (python-tests-with-temp-buffer
838 if save:
839 try:
840 write_to_disk(data)
841 finally:
842 cleanup()
843 elif
845 (python-tests-look-at "elif\n")
846 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
847 (should (= (python-indent-calculate-indentation) 0))
848 (should (= (python-indent-calculate-indentation t) 0))))
850 (ert-deftest python-indent-dedenters-2 ()
851 "Test de-indentation for the else keyword."
852 (python-tests-with-temp-buffer
854 if save:
855 try:
856 write_to_disk(data)
857 except IOError:
858 msg = 'Error saving to disk'
859 message(msg)
860 logger.exception(msg)
861 except Exception:
862 if hide_details:
863 logger.exception('Unhandled exception')
864 else
865 finally:
866 data.free()
868 (python-tests-look-at "else\n")
869 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
870 (should (= (python-indent-calculate-indentation) 8))
871 (python-indent-line t)
872 (should (= (python-indent-calculate-indentation t) 4))
873 (python-indent-line t)
874 (should (= (python-indent-calculate-indentation t) 0))
875 (python-indent-line t)
876 (should (= (python-indent-calculate-indentation t) 8))))
878 (ert-deftest python-indent-dedenters-3 ()
879 "Test de-indentation for the except keyword."
880 (python-tests-with-temp-buffer
882 if save:
883 try:
884 write_to_disk(data)
885 except
887 (python-tests-look-at "except\n")
888 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
889 (should (= (python-indent-calculate-indentation) 4))
890 (python-indent-line t)
891 (should (= (python-indent-calculate-indentation t) 4))))
893 (ert-deftest python-indent-dedenters-4 ()
894 "Test de-indentation for the finally keyword."
895 (python-tests-with-temp-buffer
897 if save:
898 try:
899 write_to_disk(data)
900 finally
902 (python-tests-look-at "finally\n")
903 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
904 (should (= (python-indent-calculate-indentation) 4))
905 (python-indent-line t)
906 (should (= (python-indent-calculate-indentation) 4))))
908 (ert-deftest python-indent-dedenters-5 ()
909 "Test invalid levels are skipped in a complex example."
910 (python-tests-with-temp-buffer
912 if save:
913 try:
914 write_to_disk(data)
915 except IOError:
916 msg = 'Error saving to disk'
917 message(msg)
918 logger.exception(msg)
919 finally:
920 if cleanup:
921 do_cleanup()
922 else
924 (python-tests-look-at "else\n")
925 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
926 (should (= (python-indent-calculate-indentation) 8))
927 (should (= (python-indent-calculate-indentation t) 0))
928 (python-indent-line t)
929 (should (= (python-indent-calculate-indentation t) 8))))
931 (ert-deftest python-indent-dedenters-6 ()
932 "Test indentation is zero when no opening block for dedenter."
933 (python-tests-with-temp-buffer
935 try:
936 # if save:
937 write_to_disk(data)
938 else
940 (python-tests-look-at "else\n")
941 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
942 (should (= (python-indent-calculate-indentation) 0))
943 (should (= (python-indent-calculate-indentation t) 0))))
945 (ert-deftest python-indent-dedenters-7 ()
946 "Test indentation case from Bug#15163."
947 (python-tests-with-temp-buffer
949 if a:
950 if b:
951 pass
952 else:
953 pass
954 else:
956 (python-tests-look-at "else:" 2)
957 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
958 (should (= (python-indent-calculate-indentation) 0))
959 (should (= (python-indent-calculate-indentation t) 0))))
961 (ert-deftest python-indent-dedenters-8 ()
962 "Test indentation for Bug#18432."
963 (python-tests-with-temp-buffer
965 if (a == 1 or
966 a == 2):
967 pass
968 elif (a == 3 or
969 a == 4):
971 (python-tests-look-at "elif (a == 3 or")
972 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
973 (should (= (python-indent-calculate-indentation) 0))
974 (should (= (python-indent-calculate-indentation t) 0))
975 (python-tests-look-at "a == 4):\n")
976 (should (eq (car (python-indent-context)) :inside-paren))
977 (should (= (python-indent-calculate-indentation) 6))
978 (python-indent-line)
979 (should (= (python-indent-calculate-indentation t) 4))
980 (python-indent-line t)
981 (should (= (python-indent-calculate-indentation t) 0))
982 (python-indent-line t)
983 (should (= (python-indent-calculate-indentation t) 6))))
985 (ert-deftest python-indent-inside-string-1 ()
986 "Test indentation for strings."
987 (python-tests-with-temp-buffer
989 multiline = '''
990 bunch
992 lines
995 (python-tests-look-at "multiline = '''")
996 (should (eq (car (python-indent-context)) :no-indent))
997 (should (= (python-indent-calculate-indentation) 0))
998 (python-tests-look-at "bunch")
999 (should (eq (car (python-indent-context)) :inside-string))
1000 (should (= (python-indent-calculate-indentation) 0))
1001 (python-tests-look-at "of")
1002 (should (eq (car (python-indent-context)) :inside-string))
1003 (should (= (python-indent-calculate-indentation) 0))
1004 (python-tests-look-at "lines")
1005 (should (eq (car (python-indent-context)) :inside-string))
1006 (should (= (python-indent-calculate-indentation) 0))
1007 (python-tests-look-at "'''")
1008 (should (eq (car (python-indent-context)) :inside-string))
1009 (should (= (python-indent-calculate-indentation) 0))))
1011 (ert-deftest python-indent-inside-string-2 ()
1012 "Test indentation for docstrings."
1013 (python-tests-with-temp-buffer
1015 def fn(a, b, c=True):
1016 '''docstring
1017 bunch
1019 lines
1022 (python-tests-look-at "'''docstring")
1023 (should (eq (car (python-indent-context)) :after-block-start))
1024 (should (= (python-indent-calculate-indentation) 4))
1025 (python-tests-look-at "bunch")
1026 (should (eq (car (python-indent-context)) :inside-docstring))
1027 (should (= (python-indent-calculate-indentation) 4))
1028 (python-tests-look-at "of")
1029 (should (eq (car (python-indent-context)) :inside-docstring))
1030 ;; Any indentation deeper than the base-indent must remain unmodified.
1031 (should (= (python-indent-calculate-indentation) 8))
1032 (python-tests-look-at "lines")
1033 (should (eq (car (python-indent-context)) :inside-docstring))
1034 (should (= (python-indent-calculate-indentation) 4))
1035 (python-tests-look-at "'''")
1036 (should (eq (car (python-indent-context)) :inside-docstring))
1037 (should (= (python-indent-calculate-indentation) 4))))
1039 (ert-deftest python-indent-inside-string-3 ()
1040 "Test indentation for nested strings."
1041 (python-tests-with-temp-buffer
1043 def fn(a, b, c=True):
1044 some_var = '''
1045 bunch
1047 lines
1050 (python-tests-look-at "some_var = '''")
1051 (should (eq (car (python-indent-context)) :after-block-start))
1052 (should (= (python-indent-calculate-indentation) 4))
1053 (python-tests-look-at "bunch")
1054 (should (eq (car (python-indent-context)) :inside-string))
1055 (should (= (python-indent-calculate-indentation) 4))
1056 (python-tests-look-at "of")
1057 (should (eq (car (python-indent-context)) :inside-string))
1058 (should (= (python-indent-calculate-indentation) 4))
1059 (python-tests-look-at "lines")
1060 (should (eq (car (python-indent-context)) :inside-string))
1061 (should (= (python-indent-calculate-indentation) 4))
1062 (python-tests-look-at "'''")
1063 (should (eq (car (python-indent-context)) :inside-string))
1064 (should (= (python-indent-calculate-indentation) 4))))
1066 (ert-deftest python-indent-electric-colon-1 ()
1067 "Test indentation case from Bug#18228."
1068 (python-tests-with-temp-buffer
1070 def a():
1071 pass
1073 def b()
1075 (python-tests-look-at "def b()")
1076 (goto-char (line-end-position))
1077 (python-tests-self-insert ":")
1078 (should (= (current-indentation) 0))))
1080 (ert-deftest python-indent-electric-colon-2 ()
1081 "Test indentation case for dedenter."
1082 (python-tests-with-temp-buffer
1084 if do:
1085 something()
1086 else
1088 (python-tests-look-at "else")
1089 (goto-char (line-end-position))
1090 (python-tests-self-insert ":")
1091 (should (= (current-indentation) 0))))
1093 (ert-deftest python-indent-electric-colon-3 ()
1094 "Test indentation case for multi-line dedenter."
1095 (python-tests-with-temp-buffer
1097 if do:
1098 something()
1099 elif (this
1101 that)
1103 (python-tests-look-at "that)")
1104 (goto-char (line-end-position))
1105 (python-tests-self-insert ":")
1106 (python-tests-look-at "elif" -1)
1107 (should (= (current-indentation) 0))
1108 (python-tests-look-at "and")
1109 (should (= (current-indentation) 6))
1110 (python-tests-look-at "that)")
1111 (should (= (current-indentation) 6))))
1113 (ert-deftest python-indent-region-1 ()
1114 "Test indentation case from Bug#18843."
1115 (let ((contents "
1116 def foo ():
1117 try:
1118 pass
1119 except:
1120 pass
1122 (python-tests-with-temp-buffer
1123 contents
1124 (python-indent-region (point-min) (point-max))
1125 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1126 contents)))))
1128 (ert-deftest python-indent-region-2 ()
1129 "Test region indentation on comments."
1130 (let ((contents "
1131 def f():
1132 if True:
1133 pass
1135 # This is
1136 # some multiline
1137 # comment
1139 (python-tests-with-temp-buffer
1140 contents
1141 (python-indent-region (point-min) (point-max))
1142 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1143 contents)))))
1145 (ert-deftest python-indent-region-3 ()
1146 "Test region indentation on comments."
1147 (let ((contents "
1148 def f():
1149 if True:
1150 pass
1151 # This is
1152 # some multiline
1153 # comment
1155 (expected "
1156 def f():
1157 if True:
1158 pass
1159 # This is
1160 # some multiline
1161 # comment
1163 (python-tests-with-temp-buffer
1164 contents
1165 (python-indent-region (point-min) (point-max))
1166 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1167 expected)))))
1169 (ert-deftest python-indent-region-4 ()
1170 "Test region indentation block starts, dedenters and enders."
1171 (let ((contents "
1172 def f():
1173 if True:
1174 a = 5
1175 else:
1176 a = 10
1177 return a
1179 (expected "
1180 def f():
1181 if True:
1182 a = 5
1183 else:
1184 a = 10
1185 return a
1187 (python-tests-with-temp-buffer
1188 contents
1189 (python-indent-region (point-min) (point-max))
1190 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1191 expected)))))
1193 (ert-deftest python-indent-region-5 ()
1194 "Test region indentation for docstrings."
1195 (let ((contents "
1196 def f():
1198 this is
1199 a multiline
1200 string
1202 x = \\
1204 this is an arbitrarily
1205 indented multiline
1206 string
1209 (expected "
1210 def f():
1212 this is
1213 a multiline
1214 string
1216 x = \\
1218 this is an arbitrarily
1219 indented multiline
1220 string
1223 (python-tests-with-temp-buffer
1224 contents
1225 (python-indent-region (point-min) (point-max))
1226 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1227 expected)))))
1230 ;;; Mark
1232 (ert-deftest python-mark-defun-1 ()
1233 """Test `python-mark-defun' with point at defun symbol start."""
1234 (python-tests-with-temp-buffer
1236 def foo(x):
1237 return x
1239 class A:
1240 pass
1242 class B:
1244 def __init__(self):
1245 self.b = 'b'
1247 def fun(self):
1248 return self.b
1250 class C:
1251 '''docstring'''
1253 (let ((expected-mark-beginning-position
1254 (progn
1255 (python-tests-look-at "class A:")
1256 (1- (point))))
1257 (expected-mark-end-position-1
1258 (save-excursion
1259 (python-tests-look-at "pass")
1260 (forward-line)
1261 (point)))
1262 (expected-mark-end-position-2
1263 (save-excursion
1264 (python-tests-look-at "return self.b")
1265 (forward-line)
1266 (point)))
1267 (expected-mark-end-position-3
1268 (save-excursion
1269 (python-tests-look-at "'''docstring'''")
1270 (forward-line)
1271 (point))))
1272 ;; Select class A only, with point at bol.
1273 (python-mark-defun 1)
1274 (should (= (point) expected-mark-beginning-position))
1275 (should (= (marker-position (mark-marker))
1276 expected-mark-end-position-1))
1277 ;; expand to class B, start position should remain the same.
1278 (python-mark-defun 1)
1279 (should (= (point) expected-mark-beginning-position))
1280 (should (= (marker-position (mark-marker))
1281 expected-mark-end-position-2))
1282 ;; expand to class C, start position should remain the same.
1283 (python-mark-defun 1)
1284 (should (= (point) expected-mark-beginning-position))
1285 (should (= (marker-position (mark-marker))
1286 expected-mark-end-position-3)))))
1288 (ert-deftest python-mark-defun-2 ()
1289 """Test `python-mark-defun' with point at nested defun symbol start."""
1290 (python-tests-with-temp-buffer
1292 def foo(x):
1293 return x
1295 class A:
1296 pass
1298 class B:
1300 def __init__(self):
1301 self.b = 'b'
1303 def fun(self):
1304 return self.b
1306 class C:
1307 '''docstring'''
1309 (let ((expected-mark-beginning-position
1310 (progn
1311 (python-tests-look-at "def __init__(self):")
1312 (1- (line-beginning-position))))
1313 (expected-mark-end-position-1
1314 (save-excursion
1315 (python-tests-look-at "self.b = 'b'")
1316 (forward-line)
1317 (point)))
1318 (expected-mark-end-position-2
1319 (save-excursion
1320 (python-tests-look-at "return self.b")
1321 (forward-line)
1322 (point)))
1323 (expected-mark-end-position-3
1324 (save-excursion
1325 (python-tests-look-at "'''docstring'''")
1326 (forward-line)
1327 (point))))
1328 ;; Select B.__init only, with point at its start.
1329 (python-mark-defun 1)
1330 (should (= (point) expected-mark-beginning-position))
1331 (should (= (marker-position (mark-marker))
1332 expected-mark-end-position-1))
1333 ;; expand to B.fun, start position should remain the same.
1334 (python-mark-defun 1)
1335 (should (= (point) expected-mark-beginning-position))
1336 (should (= (marker-position (mark-marker))
1337 expected-mark-end-position-2))
1338 ;; expand to class C, start position should remain the same.
1339 (python-mark-defun 1)
1340 (should (= (point) expected-mark-beginning-position))
1341 (should (= (marker-position (mark-marker))
1342 expected-mark-end-position-3)))))
1344 (ert-deftest python-mark-defun-3 ()
1345 """Test `python-mark-defun' with point inside defun symbol."""
1346 (python-tests-with-temp-buffer
1348 def foo(x):
1349 return x
1351 class A:
1352 pass
1354 class B:
1356 def __init__(self):
1357 self.b = 'b'
1359 def fun(self):
1360 return self.b
1362 class C:
1363 '''docstring'''
1365 (let ((expected-mark-beginning-position
1366 (progn
1367 (python-tests-look-at "def fun(self):")
1368 (python-tests-look-at "(self):")
1369 (1- (line-beginning-position))))
1370 (expected-mark-end-position
1371 (save-excursion
1372 (python-tests-look-at "return self.b")
1373 (forward-line)
1374 (point))))
1375 ;; Should select B.fun, despite point is inside the defun symbol.
1376 (python-mark-defun 1)
1377 (should (= (point) expected-mark-beginning-position))
1378 (should (= (marker-position (mark-marker))
1379 expected-mark-end-position)))))
1382 ;;; Navigation
1384 (ert-deftest python-nav-beginning-of-defun-1 ()
1385 (python-tests-with-temp-buffer
1387 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1388 '''print decorated function call data to stdout.
1390 Usage:
1392 @decoratorFunctionWithArguments('arg1', 'arg2')
1393 def func(a, b, c=True):
1394 pass
1397 def wwrap(f):
1398 print 'Inside wwrap()'
1399 def wrapped_f(*args):
1400 print 'Inside wrapped_f()'
1401 print 'Decorator arguments:', arg1, arg2, arg3
1402 f(*args)
1403 print 'After f(*args)'
1404 return wrapped_f
1405 return wwrap
1407 (python-tests-look-at "return wrap")
1408 (should (= (save-excursion
1409 (python-nav-beginning-of-defun)
1410 (point))
1411 (save-excursion
1412 (python-tests-look-at "def wrapped_f(*args):" -1)
1413 (beginning-of-line)
1414 (point))))
1415 (python-tests-look-at "def wrapped_f(*args):" -1)
1416 (should (= (save-excursion
1417 (python-nav-beginning-of-defun)
1418 (point))
1419 (save-excursion
1420 (python-tests-look-at "def wwrap(f):" -1)
1421 (beginning-of-line)
1422 (point))))
1423 (python-tests-look-at "def wwrap(f):" -1)
1424 (should (= (save-excursion
1425 (python-nav-beginning-of-defun)
1426 (point))
1427 (save-excursion
1428 (python-tests-look-at "def decoratorFunctionWithArguments" -1)
1429 (beginning-of-line)
1430 (point))))))
1432 (ert-deftest python-nav-beginning-of-defun-2 ()
1433 (python-tests-with-temp-buffer
1435 class C(object):
1437 def m(self):
1438 self.c()
1440 def b():
1441 pass
1443 def a():
1444 pass
1446 def c(self):
1447 pass
1449 ;; Nested defuns, are handled with care.
1450 (python-tests-look-at "def c(self):")
1451 (should (= (save-excursion
1452 (python-nav-beginning-of-defun)
1453 (point))
1454 (save-excursion
1455 (python-tests-look-at "def m(self):" -1)
1456 (beginning-of-line)
1457 (point))))
1458 ;; Defuns on same levels should be respected.
1459 (python-tests-look-at "def a():" -1)
1460 (should (= (save-excursion
1461 (python-nav-beginning-of-defun)
1462 (point))
1463 (save-excursion
1464 (python-tests-look-at "def b():" -1)
1465 (beginning-of-line)
1466 (point))))
1467 ;; Jump to a top level defun.
1468 (python-tests-look-at "def b():" -1)
1469 (should (= (save-excursion
1470 (python-nav-beginning-of-defun)
1471 (point))
1472 (save-excursion
1473 (python-tests-look-at "def m(self):" -1)
1474 (beginning-of-line)
1475 (point))))
1476 ;; Jump to a top level defun again.
1477 (python-tests-look-at "def m(self):" -1)
1478 (should (= (save-excursion
1479 (python-nav-beginning-of-defun)
1480 (point))
1481 (save-excursion
1482 (python-tests-look-at "class C(object):" -1)
1483 (beginning-of-line)
1484 (point))))))
1486 (ert-deftest python-nav-end-of-defun-1 ()
1487 (python-tests-with-temp-buffer
1489 class C(object):
1491 def m(self):
1492 self.c()
1494 def b():
1495 pass
1497 def a():
1498 pass
1500 def c(self):
1501 pass
1503 (should (= (save-excursion
1504 (python-tests-look-at "class C(object):")
1505 (python-nav-end-of-defun)
1506 (point))
1507 (save-excursion
1508 (point-max))))
1509 (should (= (save-excursion
1510 (python-tests-look-at "def m(self):")
1511 (python-nav-end-of-defun)
1512 (point))
1513 (save-excursion
1514 (python-tests-look-at "def c(self):")
1515 (forward-line -1)
1516 (point))))
1517 (should (= (save-excursion
1518 (python-tests-look-at "def b():")
1519 (python-nav-end-of-defun)
1520 (point))
1521 (save-excursion
1522 (python-tests-look-at "def b():")
1523 (forward-line 2)
1524 (point))))
1525 (should (= (save-excursion
1526 (python-tests-look-at "def c(self):")
1527 (python-nav-end-of-defun)
1528 (point))
1529 (save-excursion
1530 (point-max))))))
1532 (ert-deftest python-nav-end-of-defun-2 ()
1533 (python-tests-with-temp-buffer
1535 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1536 '''print decorated function call data to stdout.
1538 Usage:
1540 @decoratorFunctionWithArguments('arg1', 'arg2')
1541 def func(a, b, c=True):
1542 pass
1545 def wwrap(f):
1546 print 'Inside wwrap()'
1547 def wrapped_f(*args):
1548 print 'Inside wrapped_f()'
1549 print 'Decorator arguments:', arg1, arg2, arg3
1550 f(*args)
1551 print 'After f(*args)'
1552 return wrapped_f
1553 return wwrap
1555 (should (= (save-excursion
1556 (python-tests-look-at "def decoratorFunctionWithArguments")
1557 (python-nav-end-of-defun)
1558 (point))
1559 (save-excursion
1560 (point-max))))
1561 (should (= (save-excursion
1562 (python-tests-look-at "@decoratorFunctionWithArguments")
1563 (python-nav-end-of-defun)
1564 (point))
1565 (save-excursion
1566 (point-max))))
1567 (should (= (save-excursion
1568 (python-tests-look-at "def wwrap(f):")
1569 (python-nav-end-of-defun)
1570 (point))
1571 (save-excursion
1572 (python-tests-look-at "return wwrap")
1573 (line-beginning-position))))
1574 (should (= (save-excursion
1575 (python-tests-look-at "def wrapped_f(*args):")
1576 (python-nav-end-of-defun)
1577 (point))
1578 (save-excursion
1579 (python-tests-look-at "return wrapped_f")
1580 (line-beginning-position))))
1581 (should (= (save-excursion
1582 (python-tests-look-at "f(*args)")
1583 (python-nav-end-of-defun)
1584 (point))
1585 (save-excursion
1586 (python-tests-look-at "return wrapped_f")
1587 (line-beginning-position))))))
1589 (ert-deftest python-nav-backward-defun-1 ()
1590 (python-tests-with-temp-buffer
1592 class A(object): # A
1594 def a(self): # a
1595 pass
1597 def b(self): # b
1598 pass
1600 class B(object): # B
1602 class C(object): # C
1604 def d(self): # d
1605 pass
1607 # def e(self): # e
1608 # pass
1610 def c(self): # c
1611 pass
1613 # def d(self): # d
1614 # pass
1616 (goto-char (point-max))
1617 (should (= (save-excursion (python-nav-backward-defun))
1618 (python-tests-look-at " def c(self): # c" -1)))
1619 (should (= (save-excursion (python-nav-backward-defun))
1620 (python-tests-look-at " def d(self): # d" -1)))
1621 (should (= (save-excursion (python-nav-backward-defun))
1622 (python-tests-look-at " class C(object): # C" -1)))
1623 (should (= (save-excursion (python-nav-backward-defun))
1624 (python-tests-look-at " class B(object): # B" -1)))
1625 (should (= (save-excursion (python-nav-backward-defun))
1626 (python-tests-look-at " def b(self): # b" -1)))
1627 (should (= (save-excursion (python-nav-backward-defun))
1628 (python-tests-look-at " def a(self): # a" -1)))
1629 (should (= (save-excursion (python-nav-backward-defun))
1630 (python-tests-look-at "class A(object): # A" -1)))
1631 (should (not (python-nav-backward-defun)))))
1633 (ert-deftest python-nav-backward-defun-2 ()
1634 (python-tests-with-temp-buffer
1636 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1637 '''print decorated function call data to stdout.
1639 Usage:
1641 @decoratorFunctionWithArguments('arg1', 'arg2')
1642 def func(a, b, c=True):
1643 pass
1646 def wwrap(f):
1647 print 'Inside wwrap()'
1648 def wrapped_f(*args):
1649 print 'Inside wrapped_f()'
1650 print 'Decorator arguments:', arg1, arg2, arg3
1651 f(*args)
1652 print 'After f(*args)'
1653 return wrapped_f
1654 return wwrap
1656 (goto-char (point-max))
1657 (should (= (save-excursion (python-nav-backward-defun))
1658 (python-tests-look-at " def wrapped_f(*args):" -1)))
1659 (should (= (save-excursion (python-nav-backward-defun))
1660 (python-tests-look-at " def wwrap(f):" -1)))
1661 (should (= (save-excursion (python-nav-backward-defun))
1662 (python-tests-look-at "def decoratorFunctionWithArguments(arg1, arg2, arg3):" -1)))
1663 (should (not (python-nav-backward-defun)))))
1665 (ert-deftest python-nav-backward-defun-3 ()
1666 (python-tests-with-temp-buffer
1669 def u(self):
1670 pass
1672 def v(self):
1673 pass
1675 def w(self):
1676 pass
1679 class A(object):
1680 pass
1682 (goto-char (point-min))
1683 (let ((point (python-tests-look-at "class A(object):")))
1684 (should (not (python-nav-backward-defun)))
1685 (should (= point (point))))))
1687 (ert-deftest python-nav-forward-defun-1 ()
1688 (python-tests-with-temp-buffer
1690 class A(object): # A
1692 def a(self): # a
1693 pass
1695 def b(self): # b
1696 pass
1698 class B(object): # B
1700 class C(object): # C
1702 def d(self): # d
1703 pass
1705 # def e(self): # e
1706 # pass
1708 def c(self): # c
1709 pass
1711 # def d(self): # d
1712 # pass
1714 (goto-char (point-min))
1715 (should (= (save-excursion (python-nav-forward-defun))
1716 (python-tests-look-at "(object): # A")))
1717 (should (= (save-excursion (python-nav-forward-defun))
1718 (python-tests-look-at "(self): # a")))
1719 (should (= (save-excursion (python-nav-forward-defun))
1720 (python-tests-look-at "(self): # b")))
1721 (should (= (save-excursion (python-nav-forward-defun))
1722 (python-tests-look-at "(object): # B")))
1723 (should (= (save-excursion (python-nav-forward-defun))
1724 (python-tests-look-at "(object): # C")))
1725 (should (= (save-excursion (python-nav-forward-defun))
1726 (python-tests-look-at "(self): # d")))
1727 (should (= (save-excursion (python-nav-forward-defun))
1728 (python-tests-look-at "(self): # c")))
1729 (should (not (python-nav-forward-defun)))))
1731 (ert-deftest python-nav-forward-defun-2 ()
1732 (python-tests-with-temp-buffer
1734 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1735 '''print decorated function call data to stdout.
1737 Usage:
1739 @decoratorFunctionWithArguments('arg1', 'arg2')
1740 def func(a, b, c=True):
1741 pass
1744 def wwrap(f):
1745 print 'Inside wwrap()'
1746 def wrapped_f(*args):
1747 print 'Inside wrapped_f()'
1748 print 'Decorator arguments:', arg1, arg2, arg3
1749 f(*args)
1750 print 'After f(*args)'
1751 return wrapped_f
1752 return wwrap
1754 (goto-char (point-min))
1755 (should (= (save-excursion (python-nav-forward-defun))
1756 (python-tests-look-at "(arg1, arg2, arg3):")))
1757 (should (= (save-excursion (python-nav-forward-defun))
1758 (python-tests-look-at "(f):")))
1759 (should (= (save-excursion (python-nav-forward-defun))
1760 (python-tests-look-at "(*args):")))
1761 (should (not (python-nav-forward-defun)))))
1763 (ert-deftest python-nav-forward-defun-3 ()
1764 (python-tests-with-temp-buffer
1766 class A(object):
1767 pass
1770 def u(self):
1771 pass
1773 def v(self):
1774 pass
1776 def w(self):
1777 pass
1780 (goto-char (point-min))
1781 (let ((point (python-tests-look-at "(object):")))
1782 (should (not (python-nav-forward-defun)))
1783 (should (= point (point))))))
1785 (ert-deftest python-nav-beginning-of-statement-1 ()
1786 (python-tests-with-temp-buffer
1788 v1 = 123 + \
1789 456 + \
1791 v2 = (value1,
1792 value2,
1794 value3,
1795 value4)
1796 v3 = ('this is a string'
1798 'that is continued'
1799 'between lines'
1800 'within a paren',
1801 # this is a comment, yo
1802 'continue previous line')
1803 v4 = '''
1804 a very long
1805 string
1808 (python-tests-look-at "v2 =")
1809 (python-util-forward-comment -1)
1810 (should (= (save-excursion
1811 (python-nav-beginning-of-statement)
1812 (point))
1813 (python-tests-look-at "v1 =" -1 t)))
1814 (python-tests-look-at "v3 =")
1815 (python-util-forward-comment -1)
1816 (should (= (save-excursion
1817 (python-nav-beginning-of-statement)
1818 (point))
1819 (python-tests-look-at "v2 =" -1 t)))
1820 (python-tests-look-at "v4 =")
1821 (python-util-forward-comment -1)
1822 (should (= (save-excursion
1823 (python-nav-beginning-of-statement)
1824 (point))
1825 (python-tests-look-at "v3 =" -1 t)))
1826 (goto-char (point-max))
1827 (python-util-forward-comment -1)
1828 (should (= (save-excursion
1829 (python-nav-beginning-of-statement)
1830 (point))
1831 (python-tests-look-at "v4 =" -1 t)))))
1833 (ert-deftest python-nav-end-of-statement-1 ()
1834 (python-tests-with-temp-buffer
1836 v1 = 123 + \
1837 456 + \
1839 v2 = (value1,
1840 value2,
1842 value3,
1843 value4)
1844 v3 = ('this is a string'
1846 'that is continued'
1847 'between lines'
1848 'within a paren',
1849 # this is a comment, yo
1850 'continue previous line')
1851 v4 = '''
1852 a very long
1853 string
1856 (python-tests-look-at "v1 =")
1857 (should (= (save-excursion
1858 (python-nav-end-of-statement)
1859 (point))
1860 (save-excursion
1861 (python-tests-look-at "789")
1862 (line-end-position))))
1863 (python-tests-look-at "v2 =")
1864 (should (= (save-excursion
1865 (python-nav-end-of-statement)
1866 (point))
1867 (save-excursion
1868 (python-tests-look-at "value4)")
1869 (line-end-position))))
1870 (python-tests-look-at "v3 =")
1871 (should (= (save-excursion
1872 (python-nav-end-of-statement)
1873 (point))
1874 (save-excursion
1875 (python-tests-look-at
1876 "'continue previous line')")
1877 (line-end-position))))
1878 (python-tests-look-at "v4 =")
1879 (should (= (save-excursion
1880 (python-nav-end-of-statement)
1881 (point))
1882 (save-excursion
1883 (goto-char (point-max))
1884 (python-util-forward-comment -1)
1885 (point))))))
1887 (ert-deftest python-nav-forward-statement-1 ()
1888 (python-tests-with-temp-buffer
1890 v1 = 123 + \
1891 456 + \
1893 v2 = (value1,
1894 value2,
1896 value3,
1897 value4)
1898 v3 = ('this is a string'
1900 'that is continued'
1901 'between lines'
1902 'within a paren',
1903 # this is a comment, yo
1904 'continue previous line')
1905 v4 = '''
1906 a very long
1907 string
1910 (python-tests-look-at "v1 =")
1911 (should (= (save-excursion
1912 (python-nav-forward-statement)
1913 (point))
1914 (python-tests-look-at "v2 =")))
1915 (should (= (save-excursion
1916 (python-nav-forward-statement)
1917 (point))
1918 (python-tests-look-at "v3 =")))
1919 (should (= (save-excursion
1920 (python-nav-forward-statement)
1921 (point))
1922 (python-tests-look-at "v4 =")))
1923 (should (= (save-excursion
1924 (python-nav-forward-statement)
1925 (point))
1926 (point-max)))))
1928 (ert-deftest python-nav-backward-statement-1 ()
1929 (python-tests-with-temp-buffer
1931 v1 = 123 + \
1932 456 + \
1934 v2 = (value1,
1935 value2,
1937 value3,
1938 value4)
1939 v3 = ('this is a string'
1941 'that is continued'
1942 'between lines'
1943 'within a paren',
1944 # this is a comment, yo
1945 'continue previous line')
1946 v4 = '''
1947 a very long
1948 string
1951 (goto-char (point-max))
1952 (should (= (save-excursion
1953 (python-nav-backward-statement)
1954 (point))
1955 (python-tests-look-at "v4 =" -1)))
1956 (should (= (save-excursion
1957 (python-nav-backward-statement)
1958 (point))
1959 (python-tests-look-at "v3 =" -1)))
1960 (should (= (save-excursion
1961 (python-nav-backward-statement)
1962 (point))
1963 (python-tests-look-at "v2 =" -1)))
1964 (should (= (save-excursion
1965 (python-nav-backward-statement)
1966 (point))
1967 (python-tests-look-at "v1 =" -1)))))
1969 (ert-deftest python-nav-backward-statement-2 ()
1970 :expected-result :failed
1971 (python-tests-with-temp-buffer
1973 v1 = 123 + \
1974 456 + \
1976 v2 = (value1,
1977 value2,
1979 value3,
1980 value4)
1982 ;; FIXME: For some reason `python-nav-backward-statement' is moving
1983 ;; back two sentences when starting from 'value4)'.
1984 (goto-char (point-max))
1985 (python-util-forward-comment -1)
1986 (should (= (save-excursion
1987 (python-nav-backward-statement)
1988 (point))
1989 (python-tests-look-at "v2 =" -1 t)))))
1991 (ert-deftest python-nav-beginning-of-block-1 ()
1992 (python-tests-with-temp-buffer
1994 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1995 '''print decorated function call data to stdout.
1997 Usage:
1999 @decoratorFunctionWithArguments('arg1', 'arg2')
2000 def func(a, b, c=True):
2001 pass
2004 def wwrap(f):
2005 print 'Inside wwrap()'
2006 def wrapped_f(*args):
2007 print 'Inside wrapped_f()'
2008 print 'Decorator arguments:', arg1, arg2, arg3
2009 f(*args)
2010 print 'After f(*args)'
2011 return wrapped_f
2012 return wwrap
2014 (python-tests-look-at "return wwrap")
2015 (should (= (save-excursion
2016 (python-nav-beginning-of-block)
2017 (point))
2018 (python-tests-look-at "def decoratorFunctionWithArguments" -1)))
2019 (python-tests-look-at "print 'Inside wwrap()'")
2020 (should (= (save-excursion
2021 (python-nav-beginning-of-block)
2022 (point))
2023 (python-tests-look-at "def wwrap(f):" -1)))
2024 (python-tests-look-at "print 'After f(*args)'")
2025 (end-of-line)
2026 (should (= (save-excursion
2027 (python-nav-beginning-of-block)
2028 (point))
2029 (python-tests-look-at "def wrapped_f(*args):" -1)))
2030 (python-tests-look-at "return wrapped_f")
2031 (should (= (save-excursion
2032 (python-nav-beginning-of-block)
2033 (point))
2034 (python-tests-look-at "def wwrap(f):" -1)))))
2036 (ert-deftest python-nav-end-of-block-1 ()
2037 (python-tests-with-temp-buffer
2039 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2040 '''print decorated function call data to stdout.
2042 Usage:
2044 @decoratorFunctionWithArguments('arg1', 'arg2')
2045 def func(a, b, c=True):
2046 pass
2049 def wwrap(f):
2050 print 'Inside wwrap()'
2051 def wrapped_f(*args):
2052 print 'Inside wrapped_f()'
2053 print 'Decorator arguments:', arg1, arg2, arg3
2054 f(*args)
2055 print 'After f(*args)'
2056 return wrapped_f
2057 return wwrap
2059 (python-tests-look-at "def decoratorFunctionWithArguments")
2060 (should (= (save-excursion
2061 (python-nav-end-of-block)
2062 (point))
2063 (save-excursion
2064 (goto-char (point-max))
2065 (python-util-forward-comment -1)
2066 (point))))
2067 (python-tests-look-at "def wwrap(f):")
2068 (should (= (save-excursion
2069 (python-nav-end-of-block)
2070 (point))
2071 (save-excursion
2072 (python-tests-look-at "return wrapped_f")
2073 (line-end-position))))
2074 (end-of-line)
2075 (should (= (save-excursion
2076 (python-nav-end-of-block)
2077 (point))
2078 (save-excursion
2079 (python-tests-look-at "return wrapped_f")
2080 (line-end-position))))
2081 (python-tests-look-at "f(*args)")
2082 (should (= (save-excursion
2083 (python-nav-end-of-block)
2084 (point))
2085 (save-excursion
2086 (python-tests-look-at "print 'After f(*args)'")
2087 (line-end-position))))))
2089 (ert-deftest python-nav-forward-block-1 ()
2090 "This also accounts as a test for `python-nav-backward-block'."
2091 (python-tests-with-temp-buffer
2093 if request.user.is_authenticated():
2094 # def block():
2095 # pass
2096 try:
2097 profile = request.user.get_profile()
2098 except Profile.DoesNotExist:
2099 profile = Profile.objects.create(user=request.user)
2100 else:
2101 if profile.stats:
2102 profile.recalculate_stats()
2103 else:
2104 profile.clear_stats()
2105 finally:
2106 profile.views += 1
2107 profile.save()
2109 (should (= (save-excursion (python-nav-forward-block))
2110 (python-tests-look-at "if request.user.is_authenticated():")))
2111 (should (= (save-excursion (python-nav-forward-block))
2112 (python-tests-look-at "try:")))
2113 (should (= (save-excursion (python-nav-forward-block))
2114 (python-tests-look-at "except Profile.DoesNotExist:")))
2115 (should (= (save-excursion (python-nav-forward-block))
2116 (python-tests-look-at "else:")))
2117 (should (= (save-excursion (python-nav-forward-block))
2118 (python-tests-look-at "if profile.stats:")))
2119 (should (= (save-excursion (python-nav-forward-block))
2120 (python-tests-look-at "else:")))
2121 (should (= (save-excursion (python-nav-forward-block))
2122 (python-tests-look-at "finally:")))
2123 ;; When point is at the last block, leave it there and return nil
2124 (should (not (save-excursion (python-nav-forward-block))))
2125 ;; Move backwards, and even if the number of moves is less than the
2126 ;; provided argument return the point.
2127 (should (= (save-excursion (python-nav-forward-block -10))
2128 (python-tests-look-at
2129 "if request.user.is_authenticated():" -1)))))
2131 (ert-deftest python-nav-forward-sexp-1 ()
2132 (python-tests-with-temp-buffer
2138 (python-tests-look-at "a()")
2139 (python-nav-forward-sexp)
2140 (should (looking-at "$"))
2141 (should (save-excursion
2142 (beginning-of-line)
2143 (looking-at "a()")))
2144 (python-nav-forward-sexp)
2145 (should (looking-at "$"))
2146 (should (save-excursion
2147 (beginning-of-line)
2148 (looking-at "b()")))
2149 (python-nav-forward-sexp)
2150 (should (looking-at "$"))
2151 (should (save-excursion
2152 (beginning-of-line)
2153 (looking-at "c()")))
2154 ;; The default behavior when next to a paren should do what lisp
2155 ;; does and, otherwise `blink-matching-open' breaks.
2156 (python-nav-forward-sexp -1)
2157 (should (looking-at "()"))
2158 (should (save-excursion
2159 (beginning-of-line)
2160 (looking-at "c()")))
2161 (end-of-line)
2162 ;; Skipping parens should jump to `bolp'
2163 (python-nav-forward-sexp -1 nil t)
2164 (should (looking-at "c()"))
2165 (forward-line -1)
2166 (end-of-line)
2167 ;; b()
2168 (python-nav-forward-sexp -1)
2169 (should (looking-at "()"))
2170 (python-nav-forward-sexp -1)
2171 (should (looking-at "b()"))
2172 (end-of-line)
2173 (python-nav-forward-sexp -1 nil t)
2174 (should (looking-at "b()"))
2175 (forward-line -1)
2176 (end-of-line)
2177 ;; a()
2178 (python-nav-forward-sexp -1)
2179 (should (looking-at "()"))
2180 (python-nav-forward-sexp -1)
2181 (should (looking-at "a()"))
2182 (end-of-line)
2183 (python-nav-forward-sexp -1 nil t)
2184 (should (looking-at "a()"))))
2186 (ert-deftest python-nav-forward-sexp-2 ()
2187 (python-tests-with-temp-buffer
2189 def func():
2190 if True:
2191 aaa = bbb
2192 ccc = ddd
2193 eee = fff
2194 return ggg
2196 (python-tests-look-at "aa =")
2197 (python-nav-forward-sexp)
2198 (should (looking-at " = bbb"))
2199 (python-nav-forward-sexp)
2200 (should (looking-at "$"))
2201 (should (save-excursion
2202 (back-to-indentation)
2203 (looking-at "aaa = bbb")))
2204 (python-nav-forward-sexp)
2205 (should (looking-at "$"))
2206 (should (save-excursion
2207 (back-to-indentation)
2208 (looking-at "ccc = ddd")))
2209 (python-nav-forward-sexp)
2210 (should (looking-at "$"))
2211 (should (save-excursion
2212 (back-to-indentation)
2213 (looking-at "eee = fff")))
2214 (python-nav-forward-sexp)
2215 (should (looking-at "$"))
2216 (should (save-excursion
2217 (back-to-indentation)
2218 (looking-at "return ggg")))
2219 (python-nav-forward-sexp -1)
2220 (should (looking-at "def func():"))))
2222 (ert-deftest python-nav-forward-sexp-3 ()
2223 (python-tests-with-temp-buffer
2225 from some_module import some_sub_module
2226 from another_module import another_sub_module
2228 def another_statement():
2229 pass
2231 (python-tests-look-at "some_module")
2232 (python-nav-forward-sexp)
2233 (should (looking-at " import"))
2234 (python-nav-forward-sexp)
2235 (should (looking-at " some_sub_module"))
2236 (python-nav-forward-sexp)
2237 (should (looking-at "$"))
2238 (should
2239 (save-excursion
2240 (back-to-indentation)
2241 (looking-at
2242 "from some_module import some_sub_module")))
2243 (python-nav-forward-sexp)
2244 (should (looking-at "$"))
2245 (should
2246 (save-excursion
2247 (back-to-indentation)
2248 (looking-at
2249 "from another_module import another_sub_module")))
2250 (python-nav-forward-sexp)
2251 (should (looking-at "$"))
2252 (should
2253 (save-excursion
2254 (back-to-indentation)
2255 (looking-at
2256 "pass")))
2257 (python-nav-forward-sexp -1)
2258 (should (looking-at "def another_statement():"))
2259 (python-nav-forward-sexp -1)
2260 (should (looking-at "from another_module import another_sub_module"))
2261 (python-nav-forward-sexp -1)
2262 (should (looking-at "from some_module import some_sub_module"))))
2264 (ert-deftest python-nav-forward-sexp-safe-1 ()
2265 (python-tests-with-temp-buffer
2267 profile = Profile.objects.create(user=request.user)
2268 profile.notify()
2270 (python-tests-look-at "profile =")
2271 (python-nav-forward-sexp-safe 1)
2272 (should (looking-at "$"))
2273 (beginning-of-line 1)
2274 (python-tests-look-at "user=request.user")
2275 (python-nav-forward-sexp-safe -1)
2276 (should (looking-at "(user=request.user)"))
2277 (python-nav-forward-sexp-safe -4)
2278 (should (looking-at "profile ="))
2279 (python-tests-look-at "user=request.user")
2280 (python-nav-forward-sexp-safe 3)
2281 (should (looking-at ")"))
2282 (python-nav-forward-sexp-safe 1)
2283 (should (looking-at "$"))
2284 (python-nav-forward-sexp-safe 1)
2285 (should (looking-at "$"))))
2287 (ert-deftest python-nav-up-list-1 ()
2288 (python-tests-with-temp-buffer
2290 def f():
2291 if True:
2292 return [i for i in range(3)]
2294 (python-tests-look-at "3)]")
2295 (python-nav-up-list)
2296 (should (looking-at "]"))
2297 (python-nav-up-list)
2298 (should (looking-at "$"))))
2300 (ert-deftest python-nav-backward-up-list-1 ()
2301 :expected-result :failed
2302 (python-tests-with-temp-buffer
2304 def f():
2305 if True:
2306 return [i for i in range(3)]
2308 (python-tests-look-at "3)]")
2309 (python-nav-backward-up-list)
2310 (should (looking-at "(3)\\]"))
2311 (python-nav-backward-up-list)
2312 (should (looking-at
2313 "\\[i for i in range(3)\\]"))
2314 ;; FIXME: Need to move to beginning-of-statement.
2315 (python-nav-backward-up-list)
2316 (should (looking-at
2317 "return \\[i for i in range(3)\\]"))
2318 (python-nav-backward-up-list)
2319 (should (looking-at "if True:"))
2320 (python-nav-backward-up-list)
2321 (should (looking-at "def f():"))))
2323 (ert-deftest python-indent-dedent-line-backspace-1 ()
2324 "Check de-indentation on first call. Bug#18319."
2325 (python-tests-with-temp-buffer
2327 if True:
2328 x ()
2329 if False:
2331 (python-tests-look-at "if False:")
2332 (call-interactively #'python-indent-dedent-line-backspace)
2333 (should (zerop (current-indentation)))
2334 ;; XXX: This should be a call to `undo' but it's triggering errors.
2335 (insert " ")
2336 (should (= (current-indentation) 4))
2337 (call-interactively #'python-indent-dedent-line-backspace)
2338 (should (zerop (current-indentation)))))
2340 (ert-deftest python-indent-dedent-line-backspace-2 ()
2341 "Check de-indentation with tabs. Bug#19730."
2342 (let ((tab-width 8))
2343 (python-tests-with-temp-buffer
2345 if x:
2346 \tabcdefg
2348 (python-tests-look-at "abcdefg")
2349 (goto-char (line-end-position))
2350 (call-interactively #'python-indent-dedent-line-backspace)
2351 (should
2352 (string= (buffer-substring-no-properties
2353 (line-beginning-position) (line-end-position))
2354 "\tabcdef")))))
2356 (ert-deftest python-indent-dedent-line-backspace-3 ()
2357 "Paranoid check of de-indentation with tabs. Bug#19730."
2358 (let ((tab-width 8))
2359 (python-tests-with-temp-buffer
2361 if x:
2362 \tif y:
2363 \t abcdefg
2365 (python-tests-look-at "abcdefg")
2366 (goto-char (line-end-position))
2367 (call-interactively #'python-indent-dedent-line-backspace)
2368 (should
2369 (string= (buffer-substring-no-properties
2370 (line-beginning-position) (line-end-position))
2371 "\t abcdef"))
2372 (back-to-indentation)
2373 (call-interactively #'python-indent-dedent-line-backspace)
2374 (should
2375 (string= (buffer-substring-no-properties
2376 (line-beginning-position) (line-end-position))
2377 "\tabcdef"))
2378 (call-interactively #'python-indent-dedent-line-backspace)
2379 (should
2380 (string= (buffer-substring-no-properties
2381 (line-beginning-position) (line-end-position))
2382 " abcdef"))
2383 (call-interactively #'python-indent-dedent-line-backspace)
2384 (should
2385 (string= (buffer-substring-no-properties
2386 (line-beginning-position) (line-end-position))
2387 "abcdef")))))
2390 ;;; Shell integration
2392 (defvar python-tests-shell-interpreter "python")
2394 (ert-deftest python-shell-get-process-name-1 ()
2395 "Check process name calculation sans `buffer-file-name'."
2396 (python-tests-with-temp-buffer
2398 (should (string= (python-shell-get-process-name nil)
2399 python-shell-buffer-name))
2400 (should (string= (python-shell-get-process-name t)
2401 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2403 (ert-deftest python-shell-get-process-name-2 ()
2404 "Check process name calculation with `buffer-file-name'."
2405 (python-tests-with-temp-file
2407 ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
2408 ;; should be respected.
2409 (should (string= (python-shell-get-process-name nil)
2410 python-shell-buffer-name))
2411 (should (string=
2412 (python-shell-get-process-name t)
2413 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2415 (ert-deftest python-shell-internal-get-process-name-1 ()
2416 "Check the internal process name is buffer-unique sans `buffer-file-name'."
2417 (python-tests-with-temp-buffer
2419 (should (string= (python-shell-internal-get-process-name)
2420 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2422 (ert-deftest python-shell-internal-get-process-name-2 ()
2423 "Check the internal process name is buffer-unique with `buffer-file-name'."
2424 (python-tests-with-temp-file
2426 (should (string= (python-shell-internal-get-process-name)
2427 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2429 (ert-deftest python-shell-calculate-command-1 ()
2430 "Check the command to execute is calculated correctly.
2431 Using `python-shell-interpreter' and
2432 `python-shell-interpreter-args'."
2433 (skip-unless (executable-find python-tests-shell-interpreter))
2434 (let ((python-shell-interpreter (executable-find
2435 python-tests-shell-interpreter))
2436 (python-shell-interpreter-args "-B"))
2437 (should (string=
2438 (format "%s %s"
2439 python-shell-interpreter
2440 python-shell-interpreter-args)
2441 (python-shell-calculate-command)))))
2443 (ert-deftest python-shell-calculate-pythonpath-1 ()
2444 "Test PYTHONPATH calculation."
2445 (let ((process-environment '("PYTHONPATH=/path0"))
2446 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2447 (should (string= (python-shell-calculate-pythonpath)
2448 "/path1:/path2:/path0"))))
2450 (ert-deftest python-shell-calculate-pythonpath-2 ()
2451 "Test existing paths are moved to front."
2452 (let ((process-environment '("PYTHONPATH=/path0:/path1"))
2453 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2454 (should (string= (python-shell-calculate-pythonpath)
2455 "/path1:/path2:/path0"))))
2457 (ert-deftest python-shell-calculate-process-environment-1 ()
2458 "Test `python-shell-process-environment' modification."
2459 (let* ((python-shell-process-environment
2460 '("TESTVAR1=value1" "TESTVAR2=value2"))
2461 (process-environment (python-shell-calculate-process-environment)))
2462 (should (equal (getenv "TESTVAR1") "value1"))
2463 (should (equal (getenv "TESTVAR2") "value2"))))
2465 (ert-deftest python-shell-calculate-process-environment-2 ()
2466 "Test `python-shell-extra-pythonpaths' modification."
2467 (let* ((process-environment process-environment)
2468 (original-pythonpath (setenv "PYTHONPATH" "/path0"))
2469 (python-shell-extra-pythonpaths '("/path1" "/path2"))
2470 (process-environment (python-shell-calculate-process-environment)))
2471 (should (equal (getenv "PYTHONPATH") "/path1:/path2:/path0"))))
2473 (ert-deftest python-shell-calculate-process-environment-3 ()
2474 "Test `python-shell-virtualenv-root' modification."
2475 (let* ((python-shell-virtualenv-root "/env")
2476 (process-environment
2477 (let (process-environment process-environment)
2478 (setenv "PYTHONHOME" "/home")
2479 (setenv "VIRTUAL_ENV")
2480 (python-shell-calculate-process-environment))))
2481 (should (not (getenv "PYTHONHOME")))
2482 (should (string= (getenv "VIRTUAL_ENV") "/env"))))
2484 (ert-deftest python-shell-calculate-process-environment-4 ()
2485 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is non-nil."
2486 (let* ((python-shell-unbuffered t)
2487 (process-environment
2488 (let ((process-environment process-environment))
2489 (setenv "PYTHONUNBUFFERED")
2490 (python-shell-calculate-process-environment))))
2491 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2493 (ert-deftest python-shell-calculate-process-environment-5 ()
2494 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is nil."
2495 (let* ((python-shell-unbuffered nil)
2496 (process-environment
2497 (let ((process-environment process-environment))
2498 (setenv "PYTHONUNBUFFERED")
2499 (python-shell-calculate-process-environment))))
2500 (should (not (getenv "PYTHONUNBUFFERED")))))
2502 (ert-deftest python-shell-calculate-process-environment-6 ()
2503 "Test PYTHONUNBUFFERED=1 when `python-shell-unbuffered' is nil."
2504 (let* ((python-shell-unbuffered nil)
2505 (process-environment
2506 (let ((process-environment process-environment))
2507 (setenv "PYTHONUNBUFFERED" "1")
2508 (python-shell-calculate-process-environment))))
2509 ;; User default settings must remain untouched:
2510 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2512 (ert-deftest python-shell-calculate-process-environment-7 ()
2513 "Test no side-effects on `process-environment'."
2514 (let* ((python-shell-process-environment
2515 '("TESTVAR1=value1" "TESTVAR2=value2"))
2516 (python-shell-virtualenv-root "/env")
2517 (python-shell-unbuffered t)
2518 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2519 (original-process-environment (copy-sequence process-environment)))
2520 (python-shell-calculate-process-environment)
2521 (should (equal process-environment original-process-environment))))
2523 (ert-deftest python-shell-calculate-process-environment-8 ()
2524 "Test no side-effects on `tramp-remote-process-environment'."
2525 (let* ((default-directory "/ssh::/example/dir/")
2526 (python-shell-process-environment
2527 '("TESTVAR1=value1" "TESTVAR2=value2"))
2528 (python-shell-virtualenv-root "/env")
2529 (python-shell-unbuffered t)
2530 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2531 (original-process-environment
2532 (copy-sequence tramp-remote-process-environment)))
2533 (python-shell-calculate-process-environment)
2534 (should (equal tramp-remote-process-environment original-process-environment))))
2536 (ert-deftest python-shell-calculate-exec-path-1 ()
2537 "Test `python-shell-exec-path' modification."
2538 (let* ((exec-path '("/path0"))
2539 (python-shell-exec-path '("/path1" "/path2"))
2540 (new-exec-path (python-shell-calculate-exec-path)))
2541 (should (equal new-exec-path '("/path1" "/path2" "/path0")))))
2543 (ert-deftest python-shell-calculate-exec-path-2 ()
2544 "Test `python-shell-virtualenv-root' modification."
2545 (let* ((exec-path '("/path0"))
2546 (python-shell-virtualenv-root "/env")
2547 (new-exec-path (python-shell-calculate-exec-path)))
2548 (should (equal new-exec-path '("/env/bin" "/path0")))))
2550 (ert-deftest python-shell-calculate-exec-path-3 ()
2551 "Test complete `python-shell-virtualenv-root' modification."
2552 (let* ((exec-path '("/path0"))
2553 (python-shell-exec-path '("/path1" "/path2"))
2554 (python-shell-virtualenv-root "/env")
2555 (new-exec-path (python-shell-calculate-exec-path)))
2556 (should (equal new-exec-path '("/env/bin" "/path1" "/path2" "/path0")))))
2558 (ert-deftest python-shell-calculate-exec-path-4 ()
2559 "Test complete `python-shell-virtualenv-root' with remote."
2560 (let* ((default-directory "/ssh::/example/dir/")
2561 (python-shell-remote-exec-path '("/path0"))
2562 (python-shell-exec-path '("/path1" "/path2"))
2563 (python-shell-virtualenv-root "/env")
2564 (new-exec-path (python-shell-calculate-exec-path)))
2565 (should (equal new-exec-path '("/env/bin" "/path1" "/path2" "/path0")))))
2567 (ert-deftest python-shell-calculate-exec-path-5 ()
2568 "Test no side-effects on `exec-path'."
2569 (let* ((exec-path '("/path0"))
2570 (python-shell-exec-path '("/path1" "/path2"))
2571 (python-shell-virtualenv-root "/env")
2572 (original-exec-path (copy-sequence exec-path)))
2573 (python-shell-calculate-exec-path)
2574 (should (equal exec-path original-exec-path))))
2576 (ert-deftest python-shell-calculate-exec-path-6 ()
2577 "Test no side-effects on `python-shell-remote-exec-path'."
2578 (let* ((default-directory "/ssh::/example/dir/")
2579 (python-shell-remote-exec-path '("/path0"))
2580 (python-shell-exec-path '("/path1" "/path2"))
2581 (python-shell-virtualenv-root "/env")
2582 (original-exec-path (copy-sequence python-shell-remote-exec-path)))
2583 (python-shell-calculate-exec-path)
2584 (should (equal python-shell-remote-exec-path original-exec-path))))
2586 (ert-deftest python-shell-with-environment-1 ()
2587 "Test environment with local `default-directory'."
2588 (let* ((exec-path '("/path0"))
2589 (python-shell-exec-path '("/path1" "/path2"))
2590 (original-exec-path exec-path)
2591 (python-shell-virtualenv-root "/env"))
2592 (python-shell-with-environment
2593 (should (equal exec-path '("/env/bin" "/path1" "/path2" "/path0")))
2594 (should (not (getenv "PYTHONHOME")))
2595 (should (string= (getenv "VIRTUAL_ENV") "/env")))
2596 (should (equal exec-path original-exec-path))))
2598 (ert-deftest python-shell-with-environment-2 ()
2599 "Test environment with remote `default-directory'."
2600 (let* ((default-directory "/ssh::/example/dir/")
2601 (python-shell-remote-exec-path '("/remote1" "/remote2"))
2602 (python-shell-exec-path '("/path1" "/path2"))
2603 (tramp-remote-process-environment '("EMACS=t"))
2604 (original-process-environment (copy-sequence tramp-remote-process-environment))
2605 (python-shell-virtualenv-root "/env"))
2606 (python-shell-with-environment
2607 (should (equal (python-shell-calculate-exec-path)
2608 '("/env/bin" "/path1" "/path2" "/remote1" "/remote2")))
2609 (let ((process-environment tramp-remote-process-environment))
2610 (should (not (getenv "PYTHONHOME")))
2611 (should (string= (getenv "VIRTUAL_ENV") "/env"))))
2612 (should (equal tramp-remote-process-environment original-process-environment))))
2614 (ert-deftest python-shell-with-environment-3 ()
2615 "Test `python-shell-with-environment' is idempotent."
2616 (let* ((python-shell-extra-pythonpaths '("/example/dir/"))
2617 (python-shell-exec-path '("path1" "path2"))
2618 (python-shell-virtualenv-root "/home/user/env")
2619 (single-call
2620 (python-shell-with-environment
2621 (list exec-path process-environment)))
2622 (nested-call
2623 (python-shell-with-environment
2624 (python-shell-with-environment
2625 (list exec-path process-environment)))))
2626 (should (equal single-call nested-call))))
2628 (ert-deftest python-shell-make-comint-1 ()
2629 "Check comint creation for global shell buffer."
2630 (skip-unless (executable-find python-tests-shell-interpreter))
2631 ;; The interpreter can get killed too quickly to allow it to clean
2632 ;; up the tempfiles that the default python-shell-setup-codes create,
2633 ;; so it leaves tempfiles behind, which is a minor irritation.
2634 (let* ((python-shell-setup-codes nil)
2635 (python-shell-interpreter
2636 (executable-find python-tests-shell-interpreter))
2637 (proc-name (python-shell-get-process-name nil))
2638 (shell-buffer
2639 (python-tests-with-temp-buffer
2640 "" (python-shell-make-comint
2641 (python-shell-calculate-command) proc-name)))
2642 (process (get-buffer-process shell-buffer)))
2643 (unwind-protect
2644 (progn
2645 (set-process-query-on-exit-flag process nil)
2646 (should (process-live-p process))
2647 (with-current-buffer shell-buffer
2648 (should (eq major-mode 'inferior-python-mode))
2649 (should (string= (buffer-name) (format "*%s*" proc-name)))))
2650 (kill-buffer shell-buffer))))
2652 (ert-deftest python-shell-make-comint-2 ()
2653 "Check comint creation for internal shell buffer."
2654 (skip-unless (executable-find python-tests-shell-interpreter))
2655 (let* ((python-shell-setup-codes nil)
2656 (python-shell-interpreter
2657 (executable-find python-tests-shell-interpreter))
2658 (proc-name (python-shell-internal-get-process-name))
2659 (shell-buffer
2660 (python-tests-with-temp-buffer
2661 "" (python-shell-make-comint
2662 (python-shell-calculate-command) proc-name nil t)))
2663 (process (get-buffer-process shell-buffer)))
2664 (unwind-protect
2665 (progn
2666 (set-process-query-on-exit-flag process nil)
2667 (should (process-live-p process))
2668 (with-current-buffer shell-buffer
2669 (should (eq major-mode 'inferior-python-mode))
2670 (should (string= (buffer-name) (format " *%s*" proc-name)))))
2671 (kill-buffer shell-buffer))))
2673 (ert-deftest python-shell-make-comint-3 ()
2674 "Check comint creation with overridden python interpreter and args.
2675 The command passed to `python-shell-make-comint' as argument must
2676 locally override global values set in `python-shell-interpreter'
2677 and `python-shell-interpreter-args' in the new shell buffer."
2678 (skip-unless (executable-find python-tests-shell-interpreter))
2679 (let* ((python-shell-setup-codes nil)
2680 (python-shell-interpreter "interpreter")
2681 (python-shell-interpreter-args "--some-args")
2682 (proc-name (python-shell-get-process-name nil))
2683 (interpreter-override
2684 (concat (executable-find python-tests-shell-interpreter) " " "-i"))
2685 (shell-buffer
2686 (python-tests-with-temp-buffer
2687 "" (python-shell-make-comint interpreter-override proc-name nil)))
2688 (process (get-buffer-process shell-buffer)))
2689 (unwind-protect
2690 (progn
2691 (set-process-query-on-exit-flag process nil)
2692 (should (process-live-p process))
2693 (with-current-buffer shell-buffer
2694 (should (eq major-mode 'inferior-python-mode))
2695 (should (file-equal-p
2696 python-shell-interpreter
2697 (executable-find python-tests-shell-interpreter)))
2698 (should (string= python-shell-interpreter-args "-i"))))
2699 (kill-buffer shell-buffer))))
2701 (ert-deftest python-shell-make-comint-4 ()
2702 "Check shell calculated prompts regexps are set."
2703 (skip-unless (executable-find python-tests-shell-interpreter))
2704 (let* ((process-environment process-environment)
2705 (python-shell-setup-codes nil)
2706 (python-shell-interpreter
2707 (executable-find python-tests-shell-interpreter))
2708 (python-shell-interpreter-args "-i")
2709 (python-shell--prompt-calculated-input-regexp nil)
2710 (python-shell--prompt-calculated-output-regexp nil)
2711 (python-shell-prompt-detect-enabled t)
2712 (python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2713 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2714 (python-shell-prompt-regexp "in")
2715 (python-shell-prompt-block-regexp "block")
2716 (python-shell-prompt-pdb-regexp "pdf")
2717 (python-shell-prompt-output-regexp "output")
2718 (startup-code (concat "import sys\n"
2719 "sys.ps1 = 'py> '\n"
2720 "sys.ps2 = '..> '\n"
2721 "sys.ps3 = 'out '\n"))
2722 (startup-file (python-shell--save-temp-file startup-code))
2723 (proc-name (python-shell-get-process-name nil))
2724 (shell-buffer
2725 (progn
2726 (setenv "PYTHONSTARTUP" startup-file)
2727 (python-tests-with-temp-buffer
2728 "" (python-shell-make-comint
2729 (python-shell-calculate-command) proc-name nil))))
2730 (process (get-buffer-process shell-buffer)))
2731 (unwind-protect
2732 (progn
2733 (set-process-query-on-exit-flag process nil)
2734 (should (process-live-p process))
2735 (with-current-buffer shell-buffer
2736 (should (eq major-mode 'inferior-python-mode))
2737 (should (string=
2738 python-shell--prompt-calculated-input-regexp
2739 (concat "^\\(extralargeinputprompt\\|\\.\\.> \\|"
2740 "block\\|py> \\|pdf\\|sml\\|in\\)")))
2741 (should (string=
2742 python-shell--prompt-calculated-output-regexp
2743 "^\\(extralargeoutputprompt\\|output\\|out \\|sml\\)"))))
2744 (delete-file startup-file)
2745 (kill-buffer shell-buffer))))
2747 (ert-deftest python-shell-get-process-1 ()
2748 "Check dedicated shell process preference over global."
2749 (skip-unless (executable-find python-tests-shell-interpreter))
2750 (python-tests-with-temp-file
2752 (let* ((python-shell-setup-codes nil)
2753 (python-shell-interpreter
2754 (executable-find python-tests-shell-interpreter))
2755 (global-proc-name (python-shell-get-process-name nil))
2756 (dedicated-proc-name (python-shell-get-process-name t))
2757 (global-shell-buffer
2758 (python-shell-make-comint
2759 (python-shell-calculate-command) global-proc-name))
2760 (dedicated-shell-buffer
2761 (python-shell-make-comint
2762 (python-shell-calculate-command) dedicated-proc-name))
2763 (global-process (get-buffer-process global-shell-buffer))
2764 (dedicated-process (get-buffer-process dedicated-shell-buffer)))
2765 (unwind-protect
2766 (progn
2767 (set-process-query-on-exit-flag global-process nil)
2768 (set-process-query-on-exit-flag dedicated-process nil)
2769 ;; Prefer dedicated if global also exists.
2770 (should (equal (python-shell-get-process) dedicated-process))
2771 (kill-buffer dedicated-shell-buffer)
2772 ;; If there's only global, use it.
2773 (should (equal (python-shell-get-process) global-process))
2774 (kill-buffer global-shell-buffer)
2775 ;; No buffer available.
2776 (should (not (python-shell-get-process))))
2777 (ignore-errors (kill-buffer global-shell-buffer))
2778 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2780 (ert-deftest python-shell-internal-get-or-create-process-1 ()
2781 "Check internal shell process creation fallback."
2782 (skip-unless (executable-find python-tests-shell-interpreter))
2783 (python-tests-with-temp-file
2785 (should (not (process-live-p (python-shell-internal-get-process-name))))
2786 (let* ((python-shell-interpreter
2787 (executable-find python-tests-shell-interpreter))
2788 (internal-process-name (python-shell-internal-get-process-name))
2789 (internal-process (python-shell-internal-get-or-create-process))
2790 (internal-shell-buffer (process-buffer internal-process)))
2791 (unwind-protect
2792 (progn
2793 (set-process-query-on-exit-flag internal-process nil)
2794 (should (equal (process-name internal-process)
2795 internal-process-name))
2796 (should (equal internal-process
2797 (python-shell-internal-get-or-create-process)))
2798 ;; Assert the internal process is not a user process
2799 (should (not (python-shell-get-process)))
2800 (kill-buffer internal-shell-buffer))
2801 (ignore-errors (kill-buffer internal-shell-buffer))))))
2803 (ert-deftest python-shell-prompt-detect-1 ()
2804 "Check prompt autodetection."
2805 (skip-unless (executable-find python-tests-shell-interpreter))
2806 (let ((process-environment process-environment))
2807 ;; Ensure no startup file is enabled
2808 (setenv "PYTHONSTARTUP" "")
2809 (should python-shell-prompt-detect-enabled)
2810 (should (equal (python-shell-prompt-detect) '(">>> " "... " "")))))
2812 (ert-deftest python-shell-prompt-detect-2 ()
2813 "Check prompt autodetection with startup file. Bug#17370."
2814 (skip-unless (executable-find python-tests-shell-interpreter))
2815 (let* ((process-environment process-environment)
2816 (startup-code (concat "import sys\n"
2817 "sys.ps1 = 'py> '\n"
2818 "sys.ps2 = '..> '\n"
2819 "sys.ps3 = 'out '\n"))
2820 (startup-file (python-shell--save-temp-file startup-code)))
2821 (unwind-protect
2822 (progn
2823 ;; Ensure startup file is enabled
2824 (setenv "PYTHONSTARTUP" startup-file)
2825 (should python-shell-prompt-detect-enabled)
2826 (should (equal (python-shell-prompt-detect) '("py> " "..> " "out "))))
2827 (ignore-errors (delete-file startup-file)))))
2829 (ert-deftest python-shell-prompt-detect-3 ()
2830 "Check prompts are not autodetected when feature is disabled."
2831 (skip-unless (executable-find python-tests-shell-interpreter))
2832 (let ((process-environment process-environment)
2833 (python-shell-prompt-detect-enabled nil))
2834 ;; Ensure no startup file is enabled
2835 (should (not python-shell-prompt-detect-enabled))
2836 (should (not (python-shell-prompt-detect)))))
2838 (ert-deftest python-shell-prompt-detect-4 ()
2839 "Check warning is shown when detection fails."
2840 (skip-unless (executable-find python-tests-shell-interpreter))
2841 (let* ((process-environment process-environment)
2842 ;; Trigger failure by removing prompts in the startup file
2843 (startup-code (concat "import sys\n"
2844 "sys.ps1 = ''\n"
2845 "sys.ps2 = ''\n"
2846 "sys.ps3 = ''\n"))
2847 (startup-file (python-shell--save-temp-file startup-code)))
2848 (unwind-protect
2849 (progn
2850 (kill-buffer (get-buffer-create "*Warnings*"))
2851 (should (not (get-buffer "*Warnings*")))
2852 (setenv "PYTHONSTARTUP" startup-file)
2853 (should python-shell-prompt-detect-failure-warning)
2854 (should python-shell-prompt-detect-enabled)
2855 (should (not (python-shell-prompt-detect)))
2856 (should (get-buffer "*Warnings*")))
2857 (ignore-errors (delete-file startup-file)))))
2859 (ert-deftest python-shell-prompt-detect-5 ()
2860 "Check disabled warnings are not shown when detection fails."
2861 (skip-unless (executable-find python-tests-shell-interpreter))
2862 (let* ((process-environment process-environment)
2863 (startup-code (concat "import sys\n"
2864 "sys.ps1 = ''\n"
2865 "sys.ps2 = ''\n"
2866 "sys.ps3 = ''\n"))
2867 (startup-file (python-shell--save-temp-file startup-code))
2868 (python-shell-prompt-detect-failure-warning nil))
2869 (unwind-protect
2870 (progn
2871 (kill-buffer (get-buffer-create "*Warnings*"))
2872 (should (not (get-buffer "*Warnings*")))
2873 (setenv "PYTHONSTARTUP" startup-file)
2874 (should (not python-shell-prompt-detect-failure-warning))
2875 (should python-shell-prompt-detect-enabled)
2876 (should (not (python-shell-prompt-detect)))
2877 (should (not (get-buffer "*Warnings*"))))
2878 (ignore-errors (delete-file startup-file)))))
2880 (ert-deftest python-shell-prompt-detect-6 ()
2881 "Warnings are not shown when detection is disabled."
2882 (skip-unless (executable-find python-tests-shell-interpreter))
2883 (let* ((process-environment process-environment)
2884 (startup-code (concat "import sys\n"
2885 "sys.ps1 = ''\n"
2886 "sys.ps2 = ''\n"
2887 "sys.ps3 = ''\n"))
2888 (startup-file (python-shell--save-temp-file startup-code))
2889 (python-shell-prompt-detect-failure-warning t)
2890 (python-shell-prompt-detect-enabled nil))
2891 (unwind-protect
2892 (progn
2893 (kill-buffer (get-buffer-create "*Warnings*"))
2894 (should (not (get-buffer "*Warnings*")))
2895 (setenv "PYTHONSTARTUP" startup-file)
2896 (should python-shell-prompt-detect-failure-warning)
2897 (should (not python-shell-prompt-detect-enabled))
2898 (should (not (python-shell-prompt-detect)))
2899 (should (not (get-buffer "*Warnings*"))))
2900 (ignore-errors (delete-file startup-file)))))
2902 (ert-deftest python-shell-prompt-validate-regexps-1 ()
2903 "Check `python-shell-prompt-input-regexps' are validated."
2904 (let* ((python-shell-prompt-input-regexps '("\\("))
2905 (error-data (should-error (python-shell-prompt-validate-regexps)
2906 :type 'user-error)))
2907 (should
2908 (string= (cadr error-data)
2909 "Invalid regexp \\( in `python-shell-prompt-input-regexps'"))))
2911 (ert-deftest python-shell-prompt-validate-regexps-2 ()
2912 "Check `python-shell-prompt-output-regexps' are validated."
2913 (let* ((python-shell-prompt-output-regexps '("\\("))
2914 (error-data (should-error (python-shell-prompt-validate-regexps)
2915 :type 'user-error)))
2916 (should
2917 (string= (cadr error-data)
2918 "Invalid regexp \\( in `python-shell-prompt-output-regexps'"))))
2920 (ert-deftest python-shell-prompt-validate-regexps-3 ()
2921 "Check `python-shell-prompt-regexp' is validated."
2922 (let* ((python-shell-prompt-regexp "\\(")
2923 (error-data (should-error (python-shell-prompt-validate-regexps)
2924 :type 'user-error)))
2925 (should
2926 (string= (cadr error-data)
2927 "Invalid regexp \\( in `python-shell-prompt-regexp'"))))
2929 (ert-deftest python-shell-prompt-validate-regexps-4 ()
2930 "Check `python-shell-prompt-block-regexp' is validated."
2931 (let* ((python-shell-prompt-block-regexp "\\(")
2932 (error-data (should-error (python-shell-prompt-validate-regexps)
2933 :type 'user-error)))
2934 (should
2935 (string= (cadr error-data)
2936 "Invalid regexp \\( in `python-shell-prompt-block-regexp'"))))
2938 (ert-deftest python-shell-prompt-validate-regexps-5 ()
2939 "Check `python-shell-prompt-pdb-regexp' is validated."
2940 (let* ((python-shell-prompt-pdb-regexp "\\(")
2941 (error-data (should-error (python-shell-prompt-validate-regexps)
2942 :type 'user-error)))
2943 (should
2944 (string= (cadr error-data)
2945 "Invalid regexp \\( in `python-shell-prompt-pdb-regexp'"))))
2947 (ert-deftest python-shell-prompt-validate-regexps-6 ()
2948 "Check `python-shell-prompt-output-regexp' is validated."
2949 (let* ((python-shell-prompt-output-regexp "\\(")
2950 (error-data (should-error (python-shell-prompt-validate-regexps)
2951 :type 'user-error)))
2952 (should
2953 (string= (cadr error-data)
2954 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2956 (ert-deftest python-shell-prompt-validate-regexps-7 ()
2957 "Check default regexps are valid."
2958 ;; should not signal error
2959 (python-shell-prompt-validate-regexps))
2961 (ert-deftest python-shell-prompt-set-calculated-regexps-1 ()
2962 "Check regexps are validated."
2963 (let* ((python-shell-prompt-output-regexp '("\\("))
2964 (python-shell--prompt-calculated-input-regexp nil)
2965 (python-shell--prompt-calculated-output-regexp nil)
2966 (python-shell-prompt-detect-enabled nil)
2967 (error-data (should-error (python-shell-prompt-set-calculated-regexps)
2968 :type 'user-error)))
2969 (should
2970 (string= (cadr error-data)
2971 "Invalid regexp \\( in `python-shell-prompt-output-regexp'"))))
2973 (ert-deftest python-shell-prompt-set-calculated-regexps-2 ()
2974 "Check `python-shell-prompt-input-regexps' are set."
2975 (let* ((python-shell-prompt-input-regexps '("my" "prompt"))
2976 (python-shell-prompt-output-regexps '(""))
2977 (python-shell-prompt-regexp "")
2978 (python-shell-prompt-block-regexp "")
2979 (python-shell-prompt-pdb-regexp "")
2980 (python-shell-prompt-output-regexp "")
2981 (python-shell--prompt-calculated-input-regexp nil)
2982 (python-shell--prompt-calculated-output-regexp nil)
2983 (python-shell-prompt-detect-enabled nil))
2984 (python-shell-prompt-set-calculated-regexps)
2985 (should (string= python-shell--prompt-calculated-input-regexp
2986 "^\\(prompt\\|my\\|\\)"))))
2988 (ert-deftest python-shell-prompt-set-calculated-regexps-3 ()
2989 "Check `python-shell-prompt-output-regexps' are set."
2990 (let* ((python-shell-prompt-input-regexps '(""))
2991 (python-shell-prompt-output-regexps '("my" "prompt"))
2992 (python-shell-prompt-regexp "")
2993 (python-shell-prompt-block-regexp "")
2994 (python-shell-prompt-pdb-regexp "")
2995 (python-shell-prompt-output-regexp "")
2996 (python-shell--prompt-calculated-input-regexp nil)
2997 (python-shell--prompt-calculated-output-regexp nil)
2998 (python-shell-prompt-detect-enabled nil))
2999 (python-shell-prompt-set-calculated-regexps)
3000 (should (string= python-shell--prompt-calculated-output-regexp
3001 "^\\(prompt\\|my\\|\\)"))))
3003 (ert-deftest python-shell-prompt-set-calculated-regexps-4 ()
3004 "Check user defined prompts are set."
3005 (let* ((python-shell-prompt-input-regexps '(""))
3006 (python-shell-prompt-output-regexps '(""))
3007 (python-shell-prompt-regexp "prompt")
3008 (python-shell-prompt-block-regexp "block")
3009 (python-shell-prompt-pdb-regexp "pdb")
3010 (python-shell-prompt-output-regexp "output")
3011 (python-shell--prompt-calculated-input-regexp nil)
3012 (python-shell--prompt-calculated-output-regexp nil)
3013 (python-shell-prompt-detect-enabled nil))
3014 (python-shell-prompt-set-calculated-regexps)
3015 (should (string= python-shell--prompt-calculated-input-regexp
3016 "^\\(prompt\\|block\\|pdb\\|\\)"))
3017 (should (string= python-shell--prompt-calculated-output-regexp
3018 "^\\(output\\|\\)"))))
3020 (ert-deftest python-shell-prompt-set-calculated-regexps-5 ()
3021 "Check order of regexps (larger first)."
3022 (let* ((python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
3023 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
3024 (python-shell-prompt-regexp "in")
3025 (python-shell-prompt-block-regexp "block")
3026 (python-shell-prompt-pdb-regexp "pdf")
3027 (python-shell-prompt-output-regexp "output")
3028 (python-shell--prompt-calculated-input-regexp nil)
3029 (python-shell--prompt-calculated-output-regexp nil)
3030 (python-shell-prompt-detect-enabled nil))
3031 (python-shell-prompt-set-calculated-regexps)
3032 (should (string= python-shell--prompt-calculated-input-regexp
3033 "^\\(extralargeinputprompt\\|block\\|pdf\\|sml\\|in\\)"))
3034 (should (string= python-shell--prompt-calculated-output-regexp
3035 "^\\(extralargeoutputprompt\\|output\\|sml\\)"))))
3037 (ert-deftest python-shell-prompt-set-calculated-regexps-6 ()
3038 "Check detected prompts are included `regexp-quote'd."
3039 (skip-unless (executable-find python-tests-shell-interpreter))
3040 (let* ((python-shell-prompt-input-regexps '(""))
3041 (python-shell-prompt-output-regexps '(""))
3042 (python-shell-prompt-regexp "")
3043 (python-shell-prompt-block-regexp "")
3044 (python-shell-prompt-pdb-regexp "")
3045 (python-shell-prompt-output-regexp "")
3046 (python-shell--prompt-calculated-input-regexp nil)
3047 (python-shell--prompt-calculated-output-regexp nil)
3048 (python-shell-prompt-detect-enabled t)
3049 (process-environment process-environment)
3050 (startup-code (concat "import sys\n"
3051 "sys.ps1 = 'p.> '\n"
3052 "sys.ps2 = '..> '\n"
3053 "sys.ps3 = 'o.t '\n"))
3054 (startup-file (python-shell--save-temp-file startup-code)))
3055 (unwind-protect
3056 (progn
3057 (setenv "PYTHONSTARTUP" startup-file)
3058 (python-shell-prompt-set-calculated-regexps)
3059 (should (string= python-shell--prompt-calculated-input-regexp
3060 "^\\(\\.\\.> \\|p\\.> \\|\\)"))
3061 (should (string= python-shell--prompt-calculated-output-regexp
3062 "^\\(o\\.t \\|\\)")))
3063 (ignore-errors (delete-file startup-file)))))
3065 (ert-deftest python-shell-buffer-substring-1 ()
3066 "Selecting a substring of the whole buffer must match its contents."
3067 (python-tests-with-temp-buffer
3069 class Foo(models.Model):
3070 pass
3073 class Bar(models.Model):
3074 pass
3076 (should (string= (buffer-string)
3077 (python-shell-buffer-substring (point-min) (point-max))))))
3079 (ert-deftest python-shell-buffer-substring-2 ()
3080 "Main block should be removed if NOMAIN is non-nil."
3081 (python-tests-with-temp-buffer
3083 class Foo(models.Model):
3084 pass
3086 class Bar(models.Model):
3087 pass
3089 if __name__ == \"__main__\":
3090 foo = Foo()
3091 print (foo)
3093 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3095 class Foo(models.Model):
3096 pass
3098 class Bar(models.Model):
3099 pass
3104 "))))
3106 (ert-deftest python-shell-buffer-substring-3 ()
3107 "Main block should be removed if NOMAIN is non-nil."
3108 (python-tests-with-temp-buffer
3110 class Foo(models.Model):
3111 pass
3113 if __name__ == \"__main__\":
3114 foo = Foo()
3115 print (foo)
3117 class Bar(models.Model):
3118 pass
3120 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3122 class Foo(models.Model):
3123 pass
3129 class Bar(models.Model):
3130 pass
3131 "))))
3133 (ert-deftest python-shell-buffer-substring-4 ()
3134 "Coding cookie should be added for substrings."
3135 (python-tests-with-temp-buffer
3136 "# coding: latin-1
3138 class Foo(models.Model):
3139 pass
3141 if __name__ == \"__main__\":
3142 foo = Foo()
3143 print (foo)
3145 class Bar(models.Model):
3146 pass
3148 (should (string= (python-shell-buffer-substring
3149 (python-tests-look-at "class Foo(models.Model):")
3150 (progn (python-nav-forward-sexp) (point)))
3151 "# -*- coding: latin-1 -*-
3153 class Foo(models.Model):
3154 pass"))))
3156 (ert-deftest python-shell-buffer-substring-5 ()
3157 "The proper amount of blank lines is added for a substring."
3158 (python-tests-with-temp-buffer
3159 "# coding: latin-1
3161 class Foo(models.Model):
3162 pass
3164 if __name__ == \"__main__\":
3165 foo = Foo()
3166 print (foo)
3168 class Bar(models.Model):
3169 pass
3171 (should (string= (python-shell-buffer-substring
3172 (python-tests-look-at "class Bar(models.Model):")
3173 (progn (python-nav-forward-sexp) (point)))
3174 "# -*- coding: latin-1 -*-
3183 class Bar(models.Model):
3184 pass"))))
3186 (ert-deftest python-shell-buffer-substring-6 ()
3187 "Handle substring with coding cookie in the second line."
3188 (python-tests-with-temp-buffer
3190 # coding: latin-1
3192 class Foo(models.Model):
3193 pass
3195 if __name__ == \"__main__\":
3196 foo = Foo()
3197 print (foo)
3199 class Bar(models.Model):
3200 pass
3202 (should (string= (python-shell-buffer-substring
3203 (python-tests-look-at "# coding: latin-1")
3204 (python-tests-look-at "if __name__ == \"__main__\":"))
3205 "# -*- coding: latin-1 -*-
3208 class Foo(models.Model):
3209 pass
3211 "))))
3213 (ert-deftest python-shell-buffer-substring-7 ()
3214 "Ensure first coding cookie gets precedence."
3215 (python-tests-with-temp-buffer
3216 "# coding: utf-8
3217 # coding: latin-1
3219 class Foo(models.Model):
3220 pass
3222 if __name__ == \"__main__\":
3223 foo = Foo()
3224 print (foo)
3226 class Bar(models.Model):
3227 pass
3229 (should (string= (python-shell-buffer-substring
3230 (python-tests-look-at "# coding: latin-1")
3231 (python-tests-look-at "if __name__ == \"__main__\":"))
3232 "# -*- coding: utf-8 -*-
3235 class Foo(models.Model):
3236 pass
3238 "))))
3240 (ert-deftest python-shell-buffer-substring-8 ()
3241 "Ensure first coding cookie gets precedence when sending whole buffer."
3242 (python-tests-with-temp-buffer
3243 "# coding: utf-8
3244 # coding: latin-1
3246 class Foo(models.Model):
3247 pass
3249 (should (string= (python-shell-buffer-substring (point-min) (point-max))
3250 "# coding: utf-8
3253 class Foo(models.Model):
3254 pass
3255 "))))
3257 (ert-deftest python-shell-buffer-substring-9 ()
3258 "Check substring starting from `point-min'."
3259 (python-tests-with-temp-buffer
3260 "# coding: utf-8
3262 class Foo(models.Model):
3263 pass
3265 class Bar(models.Model):
3266 pass
3268 (should (string= (python-shell-buffer-substring
3269 (point-min)
3270 (python-tests-look-at "class Bar(models.Model):"))
3271 "# coding: utf-8
3273 class Foo(models.Model):
3274 pass
3276 "))))
3279 ;;; Shell completion
3281 (ert-deftest python-shell-completion-native-interpreter-disabled-p-1 ()
3282 (let* ((python-shell-completion-native-disabled-interpreters (list "pypy"))
3283 (python-shell-interpreter "/some/path/to/bin/pypy"))
3284 (should (python-shell-completion-native-interpreter-disabled-p))))
3289 ;;; PDB Track integration
3292 ;;; Symbol completion
3295 ;;; Fill paragraph
3298 ;;; Skeletons
3301 ;;; FFAP
3304 ;;; Code check
3307 ;;; Eldoc
3309 (ert-deftest python-eldoc--get-symbol-at-point-1 ()
3310 "Test paren handling."
3311 (python-tests-with-temp-buffer
3313 map(xx
3314 map(codecs.open('somefile'
3316 (python-tests-look-at "ap(xx")
3317 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3318 (goto-char (line-end-position))
3319 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3320 (python-tests-look-at "('somefile'")
3321 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3322 (goto-char (line-end-position))
3323 (should (string= (python-eldoc--get-symbol-at-point) "codecs.open"))))
3325 (ert-deftest python-eldoc--get-symbol-at-point-2 ()
3326 "Ensure self is replaced with the class name."
3327 (python-tests-with-temp-buffer
3329 class TheClass:
3331 def some_method(self, n):
3332 return n
3334 def other(self):
3335 return self.some_method(1234)
3338 (python-tests-look-at "self.some_method")
3339 (should (string= (python-eldoc--get-symbol-at-point)
3340 "TheClass.some_method"))
3341 (python-tests-look-at "1234)")
3342 (should (string= (python-eldoc--get-symbol-at-point)
3343 "TheClass.some_method"))))
3345 (ert-deftest python-eldoc--get-symbol-at-point-3 ()
3346 "Ensure symbol is found when point is at end of buffer."
3347 (python-tests-with-temp-buffer
3349 some_symbol
3352 (goto-char (point-max))
3353 (should (string= (python-eldoc--get-symbol-at-point)
3354 "some_symbol"))))
3356 (ert-deftest python-eldoc--get-symbol-at-point-4 ()
3357 "Ensure symbol is found when point is at whitespace."
3358 (python-tests-with-temp-buffer
3360 some_symbol some_other_symbol
3362 (python-tests-look-at " some_other_symbol")
3363 (should (string= (python-eldoc--get-symbol-at-point)
3364 "some_symbol"))))
3367 ;;; Imenu
3369 (ert-deftest python-imenu-create-index-1 ()
3370 (python-tests-with-temp-buffer
3372 class Foo(models.Model):
3373 pass
3376 class Bar(models.Model):
3377 pass
3380 def decorator(arg1, arg2, arg3):
3381 '''print decorated function call data to stdout.
3383 Usage:
3385 @decorator('arg1', 'arg2')
3386 def func(a, b, c=True):
3387 pass
3390 def wrap(f):
3391 print ('wrap')
3392 def wrapped_f(*args):
3393 print ('wrapped_f')
3394 print ('Decorator arguments:', arg1, arg2, arg3)
3395 f(*args)
3396 print ('called f(*args)')
3397 return wrapped_f
3398 return wrap
3401 class Baz(object):
3403 def a(self):
3404 pass
3406 def b(self):
3407 pass
3409 class Frob(object):
3411 def c(self):
3412 pass
3414 (goto-char (point-max))
3415 (should (equal
3416 (list
3417 (cons "Foo (class)" (copy-marker 2))
3418 (cons "Bar (class)" (copy-marker 38))
3419 (list
3420 "decorator (def)"
3421 (cons "*function definition*" (copy-marker 74))
3422 (list
3423 "wrap (def)"
3424 (cons "*function definition*" (copy-marker 254))
3425 (cons "wrapped_f (def)" (copy-marker 294))))
3426 (list
3427 "Baz (class)"
3428 (cons "*class definition*" (copy-marker 519))
3429 (cons "a (def)" (copy-marker 539))
3430 (cons "b (def)" (copy-marker 570))
3431 (list
3432 "Frob (class)"
3433 (cons "*class definition*" (copy-marker 601))
3434 (cons "c (def)" (copy-marker 626)))))
3435 (python-imenu-create-index)))))
3437 (ert-deftest python-imenu-create-index-2 ()
3438 (python-tests-with-temp-buffer
3440 class Foo(object):
3441 def foo(self):
3442 def foo1():
3443 pass
3445 def foobar(self):
3446 pass
3448 (goto-char (point-max))
3449 (should (equal
3450 (list
3451 (list
3452 "Foo (class)"
3453 (cons "*class definition*" (copy-marker 2))
3454 (list
3455 "foo (def)"
3456 (cons "*function definition*" (copy-marker 21))
3457 (cons "foo1 (def)" (copy-marker 40)))
3458 (cons "foobar (def)" (copy-marker 78))))
3459 (python-imenu-create-index)))))
3461 (ert-deftest python-imenu-create-index-3 ()
3462 (python-tests-with-temp-buffer
3464 class Foo(object):
3465 def foo(self):
3466 def foo1():
3467 pass
3468 def foo2():
3469 pass
3471 (goto-char (point-max))
3472 (should (equal
3473 (list
3474 (list
3475 "Foo (class)"
3476 (cons "*class definition*" (copy-marker 2))
3477 (list
3478 "foo (def)"
3479 (cons "*function definition*" (copy-marker 21))
3480 (cons "foo1 (def)" (copy-marker 40))
3481 (cons "foo2 (def)" (copy-marker 77)))))
3482 (python-imenu-create-index)))))
3484 (ert-deftest python-imenu-create-index-4 ()
3485 (python-tests-with-temp-buffer
3487 class Foo(object):
3488 class Bar(object):
3489 def __init__(self):
3490 pass
3492 def __str__(self):
3493 pass
3495 def __init__(self):
3496 pass
3498 (goto-char (point-max))
3499 (should (equal
3500 (list
3501 (list
3502 "Foo (class)"
3503 (cons "*class definition*" (copy-marker 2))
3504 (list
3505 "Bar (class)"
3506 (cons "*class definition*" (copy-marker 21))
3507 (cons "__init__ (def)" (copy-marker 44))
3508 (cons "__str__ (def)" (copy-marker 90)))
3509 (cons "__init__ (def)" (copy-marker 135))))
3510 (python-imenu-create-index)))))
3512 (ert-deftest python-imenu-create-flat-index-1 ()
3513 (python-tests-with-temp-buffer
3515 class Foo(models.Model):
3516 pass
3519 class Bar(models.Model):
3520 pass
3523 def decorator(arg1, arg2, arg3):
3524 '''print decorated function call data to stdout.
3526 Usage:
3528 @decorator('arg1', 'arg2')
3529 def func(a, b, c=True):
3530 pass
3533 def wrap(f):
3534 print ('wrap')
3535 def wrapped_f(*args):
3536 print ('wrapped_f')
3537 print ('Decorator arguments:', arg1, arg2, arg3)
3538 f(*args)
3539 print ('called f(*args)')
3540 return wrapped_f
3541 return wrap
3544 class Baz(object):
3546 def a(self):
3547 pass
3549 def b(self):
3550 pass
3552 class Frob(object):
3554 def c(self):
3555 pass
3557 (goto-char (point-max))
3558 (should (equal
3559 (list (cons "Foo" (copy-marker 2))
3560 (cons "Bar" (copy-marker 38))
3561 (cons "decorator" (copy-marker 74))
3562 (cons "decorator.wrap" (copy-marker 254))
3563 (cons "decorator.wrap.wrapped_f" (copy-marker 294))
3564 (cons "Baz" (copy-marker 519))
3565 (cons "Baz.a" (copy-marker 539))
3566 (cons "Baz.b" (copy-marker 570))
3567 (cons "Baz.Frob" (copy-marker 601))
3568 (cons "Baz.Frob.c" (copy-marker 626)))
3569 (python-imenu-create-flat-index)))))
3571 (ert-deftest python-imenu-create-flat-index-2 ()
3572 (python-tests-with-temp-buffer
3574 class Foo(object):
3575 class Bar(object):
3576 def __init__(self):
3577 pass
3579 def __str__(self):
3580 pass
3582 def __init__(self):
3583 pass
3585 (goto-char (point-max))
3586 (should (equal
3587 (list
3588 (cons "Foo" (copy-marker 2))
3589 (cons "Foo.Bar" (copy-marker 21))
3590 (cons "Foo.Bar.__init__" (copy-marker 44))
3591 (cons "Foo.Bar.__str__" (copy-marker 90))
3592 (cons "Foo.__init__" (copy-marker 135)))
3593 (python-imenu-create-flat-index)))))
3596 ;;; Misc helpers
3598 (ert-deftest python-info-current-defun-1 ()
3599 (python-tests-with-temp-buffer
3601 def foo(a, b):
3603 (forward-line 1)
3604 (should (string= "foo" (python-info-current-defun)))
3605 (should (string= "def foo" (python-info-current-defun t)))
3606 (forward-line 1)
3607 (should (not (python-info-current-defun)))
3608 (indent-for-tab-command)
3609 (should (string= "foo" (python-info-current-defun)))
3610 (should (string= "def foo" (python-info-current-defun t)))))
3612 (ert-deftest python-info-current-defun-2 ()
3613 (python-tests-with-temp-buffer
3615 class C(object):
3617 def m(self):
3618 if True:
3619 return [i for i in range(3)]
3620 else:
3621 return []
3623 def b():
3624 do_b()
3626 def a():
3627 do_a()
3629 def c(self):
3630 do_c()
3632 (forward-line 1)
3633 (should (string= "C" (python-info-current-defun)))
3634 (should (string= "class C" (python-info-current-defun t)))
3635 (python-tests-look-at "return [i for ")
3636 (should (string= "C.m" (python-info-current-defun)))
3637 (should (string= "def C.m" (python-info-current-defun t)))
3638 (python-tests-look-at "def b():")
3639 (should (string= "C.m.b" (python-info-current-defun)))
3640 (should (string= "def C.m.b" (python-info-current-defun t)))
3641 (forward-line 2)
3642 (indent-for-tab-command)
3643 (python-indent-dedent-line-backspace 1)
3644 (should (string= "C.m" (python-info-current-defun)))
3645 (should (string= "def C.m" (python-info-current-defun t)))
3646 (python-tests-look-at "def c(self):")
3647 (forward-line -1)
3648 (indent-for-tab-command)
3649 (should (string= "C.m.a" (python-info-current-defun)))
3650 (should (string= "def C.m.a" (python-info-current-defun t)))
3651 (python-indent-dedent-line-backspace 1)
3652 (should (string= "C.m" (python-info-current-defun)))
3653 (should (string= "def C.m" (python-info-current-defun t)))
3654 (python-indent-dedent-line-backspace 1)
3655 (should (string= "C" (python-info-current-defun)))
3656 (should (string= "class C" (python-info-current-defun t)))
3657 (python-tests-look-at "def c(self):")
3658 (should (string= "C.c" (python-info-current-defun)))
3659 (should (string= "def C.c" (python-info-current-defun t)))
3660 (python-tests-look-at "do_c()")
3661 (should (string= "C.c" (python-info-current-defun)))
3662 (should (string= "def C.c" (python-info-current-defun t)))))
3664 (ert-deftest python-info-current-defun-3 ()
3665 (python-tests-with-temp-buffer
3667 def decoratorFunctionWithArguments(arg1, arg2, arg3):
3668 '''print decorated function call data to stdout.
3670 Usage:
3672 @decoratorFunctionWithArguments('arg1', 'arg2')
3673 def func(a, b, c=True):
3674 pass
3677 def wwrap(f):
3678 print 'Inside wwrap()'
3679 def wrapped_f(*args):
3680 print 'Inside wrapped_f()'
3681 print 'Decorator arguments:', arg1, arg2, arg3
3682 f(*args)
3683 print 'After f(*args)'
3684 return wrapped_f
3685 return wwrap
3687 (python-tests-look-at "def wwrap(f):")
3688 (forward-line -1)
3689 (should (not (python-info-current-defun)))
3690 (indent-for-tab-command 1)
3691 (should (string= (python-info-current-defun)
3692 "decoratorFunctionWithArguments"))
3693 (should (string= (python-info-current-defun t)
3694 "def decoratorFunctionWithArguments"))
3695 (python-tests-look-at "def wrapped_f(*args):")
3696 (should (string= (python-info-current-defun)
3697 "decoratorFunctionWithArguments.wwrap.wrapped_f"))
3698 (should (string= (python-info-current-defun t)
3699 "def decoratorFunctionWithArguments.wwrap.wrapped_f"))
3700 (python-tests-look-at "return wrapped_f")
3701 (should (string= (python-info-current-defun)
3702 "decoratorFunctionWithArguments.wwrap"))
3703 (should (string= (python-info-current-defun t)
3704 "def decoratorFunctionWithArguments.wwrap"))
3705 (end-of-line 1)
3706 (python-tests-look-at "return wwrap")
3707 (should (string= (python-info-current-defun)
3708 "decoratorFunctionWithArguments"))
3709 (should (string= (python-info-current-defun t)
3710 "def decoratorFunctionWithArguments"))))
3712 (ert-deftest python-info-current-symbol-1 ()
3713 (python-tests-with-temp-buffer
3715 class C(object):
3717 def m(self):
3718 self.c()
3720 def c(self):
3721 print ('a')
3723 (python-tests-look-at "self.c()")
3724 (should (string= "self.c" (python-info-current-symbol)))
3725 (should (string= "C.c" (python-info-current-symbol t)))))
3727 (ert-deftest python-info-current-symbol-2 ()
3728 (python-tests-with-temp-buffer
3730 class C(object):
3732 class M(object):
3734 def a(self):
3735 self.c()
3737 def c(self):
3738 pass
3740 (python-tests-look-at "self.c()")
3741 (should (string= "self.c" (python-info-current-symbol)))
3742 (should (string= "C.M.c" (python-info-current-symbol t)))))
3744 (ert-deftest python-info-current-symbol-3 ()
3745 "Keywords should not be considered symbols."
3746 :expected-result :failed
3747 (python-tests-with-temp-buffer
3749 class C(object):
3750 pass
3752 ;; FIXME: keywords are not symbols.
3753 (python-tests-look-at "class C")
3754 (should (not (python-info-current-symbol)))
3755 (should (not (python-info-current-symbol t)))
3756 (python-tests-look-at "C(object)")
3757 (should (string= "C" (python-info-current-symbol)))
3758 (should (string= "class C" (python-info-current-symbol t)))))
3760 (ert-deftest python-info-statement-starts-block-p-1 ()
3761 (python-tests-with-temp-buffer
3763 def long_function_name(
3764 var_one, var_two, var_three,
3765 var_four):
3766 print (var_one)
3768 (python-tests-look-at "def long_function_name")
3769 (should (python-info-statement-starts-block-p))
3770 (python-tests-look-at "print (var_one)")
3771 (python-util-forward-comment -1)
3772 (should (python-info-statement-starts-block-p))))
3774 (ert-deftest python-info-statement-starts-block-p-2 ()
3775 (python-tests-with-temp-buffer
3777 if width == 0 and height == 0 and \\\\
3778 color == 'red' and emphasis == 'strong' or \\\\
3779 highlight > 100:
3780 raise ValueError('sorry, you lose')
3782 (python-tests-look-at "if width == 0 and")
3783 (should (python-info-statement-starts-block-p))
3784 (python-tests-look-at "raise ValueError(")
3785 (python-util-forward-comment -1)
3786 (should (python-info-statement-starts-block-p))))
3788 (ert-deftest python-info-statement-ends-block-p-1 ()
3789 (python-tests-with-temp-buffer
3791 def long_function_name(
3792 var_one, var_two, var_three,
3793 var_four):
3794 print (var_one)
3796 (python-tests-look-at "print (var_one)")
3797 (should (python-info-statement-ends-block-p))))
3799 (ert-deftest python-info-statement-ends-block-p-2 ()
3800 (python-tests-with-temp-buffer
3802 if width == 0 and height == 0 and \\\\
3803 color == 'red' and emphasis == 'strong' or \\\\
3804 highlight > 100:
3805 raise ValueError(
3806 'sorry, you lose'
3810 (python-tests-look-at "raise ValueError(")
3811 (should (python-info-statement-ends-block-p))))
3813 (ert-deftest python-info-beginning-of-statement-p-1 ()
3814 (python-tests-with-temp-buffer
3816 def long_function_name(
3817 var_one, var_two, var_three,
3818 var_four):
3819 print (var_one)
3821 (python-tests-look-at "def long_function_name")
3822 (should (python-info-beginning-of-statement-p))
3823 (forward-char 10)
3824 (should (not (python-info-beginning-of-statement-p)))
3825 (python-tests-look-at "print (var_one)")
3826 (should (python-info-beginning-of-statement-p))
3827 (goto-char (line-beginning-position))
3828 (should (not (python-info-beginning-of-statement-p)))))
3830 (ert-deftest python-info-beginning-of-statement-p-2 ()
3831 (python-tests-with-temp-buffer
3833 if width == 0 and height == 0 and \\\\
3834 color == 'red' and emphasis == 'strong' or \\\\
3835 highlight > 100:
3836 raise ValueError(
3837 'sorry, you lose'
3841 (python-tests-look-at "if width == 0 and")
3842 (should (python-info-beginning-of-statement-p))
3843 (forward-char 10)
3844 (should (not (python-info-beginning-of-statement-p)))
3845 (python-tests-look-at "raise ValueError(")
3846 (should (python-info-beginning-of-statement-p))
3847 (goto-char (line-beginning-position))
3848 (should (not (python-info-beginning-of-statement-p)))))
3850 (ert-deftest python-info-end-of-statement-p-1 ()
3851 (python-tests-with-temp-buffer
3853 def long_function_name(
3854 var_one, var_two, var_three,
3855 var_four):
3856 print (var_one)
3858 (python-tests-look-at "def long_function_name")
3859 (should (not (python-info-end-of-statement-p)))
3860 (end-of-line)
3861 (should (not (python-info-end-of-statement-p)))
3862 (python-tests-look-at "print (var_one)")
3863 (python-util-forward-comment -1)
3864 (should (python-info-end-of-statement-p))
3865 (python-tests-look-at "print (var_one)")
3866 (should (not (python-info-end-of-statement-p)))
3867 (end-of-line)
3868 (should (python-info-end-of-statement-p))))
3870 (ert-deftest python-info-end-of-statement-p-2 ()
3871 (python-tests-with-temp-buffer
3873 if width == 0 and height == 0 and \\\\
3874 color == 'red' and emphasis == 'strong' or \\\\
3875 highlight > 100:
3876 raise ValueError(
3877 'sorry, you lose'
3881 (python-tests-look-at "if width == 0 and")
3882 (should (not (python-info-end-of-statement-p)))
3883 (end-of-line)
3884 (should (not (python-info-end-of-statement-p)))
3885 (python-tests-look-at "raise ValueError(")
3886 (python-util-forward-comment -1)
3887 (should (python-info-end-of-statement-p))
3888 (python-tests-look-at "raise ValueError(")
3889 (should (not (python-info-end-of-statement-p)))
3890 (end-of-line)
3891 (should (not (python-info-end-of-statement-p)))
3892 (goto-char (point-max))
3893 (python-util-forward-comment -1)
3894 (should (python-info-end-of-statement-p))))
3896 (ert-deftest python-info-beginning-of-block-p-1 ()
3897 (python-tests-with-temp-buffer
3899 def long_function_name(
3900 var_one, var_two, var_three,
3901 var_four):
3902 print (var_one)
3904 (python-tests-look-at "def long_function_name")
3905 (should (python-info-beginning-of-block-p))
3906 (python-tests-look-at "var_one, var_two, var_three,")
3907 (should (not (python-info-beginning-of-block-p)))
3908 (python-tests-look-at "print (var_one)")
3909 (should (not (python-info-beginning-of-block-p)))))
3911 (ert-deftest python-info-beginning-of-block-p-2 ()
3912 (python-tests-with-temp-buffer
3914 if width == 0 and height == 0 and \\\\
3915 color == 'red' and emphasis == 'strong' or \\\\
3916 highlight > 100:
3917 raise ValueError(
3918 'sorry, you lose'
3922 (python-tests-look-at "if width == 0 and")
3923 (should (python-info-beginning-of-block-p))
3924 (python-tests-look-at "color == 'red' and emphasis")
3925 (should (not (python-info-beginning-of-block-p)))
3926 (python-tests-look-at "raise ValueError(")
3927 (should (not (python-info-beginning-of-block-p)))))
3929 (ert-deftest python-info-end-of-block-p-1 ()
3930 (python-tests-with-temp-buffer
3932 def long_function_name(
3933 var_one, var_two, var_three,
3934 var_four):
3935 print (var_one)
3937 (python-tests-look-at "def long_function_name")
3938 (should (not (python-info-end-of-block-p)))
3939 (python-tests-look-at "var_one, var_two, var_three,")
3940 (should (not (python-info-end-of-block-p)))
3941 (python-tests-look-at "var_four):")
3942 (end-of-line)
3943 (should (not (python-info-end-of-block-p)))
3944 (python-tests-look-at "print (var_one)")
3945 (should (not (python-info-end-of-block-p)))
3946 (end-of-line 1)
3947 (should (python-info-end-of-block-p))))
3949 (ert-deftest python-info-end-of-block-p-2 ()
3950 (python-tests-with-temp-buffer
3952 if width == 0 and height == 0 and \\\\
3953 color == 'red' and emphasis == 'strong' or \\\\
3954 highlight > 100:
3955 raise ValueError(
3956 'sorry, you lose'
3960 (python-tests-look-at "if width == 0 and")
3961 (should (not (python-info-end-of-block-p)))
3962 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
3963 (should (not (python-info-end-of-block-p)))
3964 (python-tests-look-at "highlight > 100:")
3965 (end-of-line)
3966 (should (not (python-info-end-of-block-p)))
3967 (python-tests-look-at "raise ValueError(")
3968 (should (not (python-info-end-of-block-p)))
3969 (end-of-line 1)
3970 (should (not (python-info-end-of-block-p)))
3971 (goto-char (point-max))
3972 (python-util-forward-comment -1)
3973 (should (python-info-end-of-block-p))))
3975 (ert-deftest python-info-dedenter-opening-block-position-1 ()
3976 (python-tests-with-temp-buffer
3978 if request.user.is_authenticated():
3979 try:
3980 profile = request.user.get_profile()
3981 except Profile.DoesNotExist:
3982 profile = Profile.objects.create(user=request.user)
3983 else:
3984 if profile.stats:
3985 profile.recalculate_stats()
3986 else:
3987 profile.clear_stats()
3988 finally:
3989 profile.views += 1
3990 profile.save()
3992 (python-tests-look-at "try:")
3993 (should (not (python-info-dedenter-opening-block-position)))
3994 (python-tests-look-at "except Profile.DoesNotExist:")
3995 (should (= (python-tests-look-at "try:" -1 t)
3996 (python-info-dedenter-opening-block-position)))
3997 (python-tests-look-at "else:")
3998 (should (= (python-tests-look-at "except Profile.DoesNotExist:" -1 t)
3999 (python-info-dedenter-opening-block-position)))
4000 (python-tests-look-at "if profile.stats:")
4001 (should (not (python-info-dedenter-opening-block-position)))
4002 (python-tests-look-at "else:")
4003 (should (= (python-tests-look-at "if profile.stats:" -1 t)
4004 (python-info-dedenter-opening-block-position)))
4005 (python-tests-look-at "finally:")
4006 (should (= (python-tests-look-at "else:" -2 t)
4007 (python-info-dedenter-opening-block-position)))))
4009 (ert-deftest python-info-dedenter-opening-block-position-2 ()
4010 (python-tests-with-temp-buffer
4012 if request.user.is_authenticated():
4013 profile = Profile.objects.get_or_create(user=request.user)
4014 if profile.stats:
4015 profile.recalculate_stats()
4017 data = {
4018 'else': 'do it'
4020 'else'
4022 (python-tests-look-at "'else': 'do it'")
4023 (should (not (python-info-dedenter-opening-block-position)))
4024 (python-tests-look-at "'else'")
4025 (should (not (python-info-dedenter-opening-block-position)))))
4027 (ert-deftest python-info-dedenter-opening-block-position-3 ()
4028 (python-tests-with-temp-buffer
4030 if save:
4031 try:
4032 write_to_disk(data)
4033 except IOError:
4034 msg = 'Error saving to disk'
4035 message(msg)
4036 logger.exception(msg)
4037 except Exception:
4038 if hide_details:
4039 logger.exception('Unhandled exception')
4040 else
4041 finally:
4042 data.free()
4044 (python-tests-look-at "try:")
4045 (should (not (python-info-dedenter-opening-block-position)))
4047 (python-tests-look-at "except IOError:")
4048 (should (= (python-tests-look-at "try:" -1 t)
4049 (python-info-dedenter-opening-block-position)))
4051 (python-tests-look-at "except Exception:")
4052 (should (= (python-tests-look-at "except IOError:" -1 t)
4053 (python-info-dedenter-opening-block-position)))
4055 (python-tests-look-at "if hide_details:")
4056 (should (not (python-info-dedenter-opening-block-position)))
4058 ;; check indentation modifies the detected opening block
4059 (python-tests-look-at "else")
4060 (should (= (python-tests-look-at "if hide_details:" -1 t)
4061 (python-info-dedenter-opening-block-position)))
4063 (indent-line-to 8)
4064 (should (= (python-tests-look-at "if hide_details:" -1 t)
4065 (python-info-dedenter-opening-block-position)))
4067 (indent-line-to 4)
4068 (should (= (python-tests-look-at "except Exception:" -1 t)
4069 (python-info-dedenter-opening-block-position)))
4071 (indent-line-to 0)
4072 (should (= (python-tests-look-at "if save:" -1 t)
4073 (python-info-dedenter-opening-block-position)))))
4075 (ert-deftest python-info-dedenter-opening-block-positions-1 ()
4076 (python-tests-with-temp-buffer
4078 if save:
4079 try:
4080 write_to_disk(data)
4081 except IOError:
4082 msg = 'Error saving to disk'
4083 message(msg)
4084 logger.exception(msg)
4085 except Exception:
4086 if hide_details:
4087 logger.exception('Unhandled exception')
4088 else
4089 finally:
4090 data.free()
4092 (python-tests-look-at "try:")
4093 (should (not (python-info-dedenter-opening-block-positions)))
4095 (python-tests-look-at "except IOError:")
4096 (should
4097 (equal (list
4098 (python-tests-look-at "try:" -1 t))
4099 (python-info-dedenter-opening-block-positions)))
4101 (python-tests-look-at "except Exception:")
4102 (should
4103 (equal (list
4104 (python-tests-look-at "except IOError:" -1 t))
4105 (python-info-dedenter-opening-block-positions)))
4107 (python-tests-look-at "if hide_details:")
4108 (should (not (python-info-dedenter-opening-block-positions)))
4110 ;; check indentation does not modify the detected opening blocks
4111 (python-tests-look-at "else")
4112 (should
4113 (equal (list
4114 (python-tests-look-at "if hide_details:" -1 t)
4115 (python-tests-look-at "except Exception:" -1 t)
4116 (python-tests-look-at "if save:" -1 t))
4117 (python-info-dedenter-opening-block-positions)))
4119 (indent-line-to 8)
4120 (should
4121 (equal (list
4122 (python-tests-look-at "if hide_details:" -1 t)
4123 (python-tests-look-at "except Exception:" -1 t)
4124 (python-tests-look-at "if save:" -1 t))
4125 (python-info-dedenter-opening-block-positions)))
4127 (indent-line-to 4)
4128 (should
4129 (equal (list
4130 (python-tests-look-at "if hide_details:" -1 t)
4131 (python-tests-look-at "except Exception:" -1 t)
4132 (python-tests-look-at "if save:" -1 t))
4133 (python-info-dedenter-opening-block-positions)))
4135 (indent-line-to 0)
4136 (should
4137 (equal (list
4138 (python-tests-look-at "if hide_details:" -1 t)
4139 (python-tests-look-at "except Exception:" -1 t)
4140 (python-tests-look-at "if save:" -1 t))
4141 (python-info-dedenter-opening-block-positions)))))
4143 (ert-deftest python-info-dedenter-opening-block-positions-2 ()
4144 "Test detection of opening blocks for elif."
4145 (python-tests-with-temp-buffer
4147 if var:
4148 if var2:
4149 something()
4150 elif var3:
4151 something_else()
4152 elif
4154 (python-tests-look-at "elif var3:")
4155 (should
4156 (equal (list
4157 (python-tests-look-at "if var2:" -1 t)
4158 (python-tests-look-at "if var:" -1 t))
4159 (python-info-dedenter-opening-block-positions)))
4161 (python-tests-look-at "elif\n")
4162 (should
4163 (equal (list
4164 (python-tests-look-at "elif var3:" -1 t)
4165 (python-tests-look-at "if var:" -1 t))
4166 (python-info-dedenter-opening-block-positions)))))
4168 (ert-deftest python-info-dedenter-opening-block-positions-3 ()
4169 "Test detection of opening blocks for else."
4170 (python-tests-with-temp-buffer
4172 try:
4173 something()
4174 except:
4175 if var:
4176 if var2:
4177 something()
4178 elif var3:
4179 something_else()
4180 else
4182 if var4:
4183 while var5:
4184 var4.pop()
4185 else
4187 for value in var6:
4188 if value > 0:
4189 print value
4190 else
4192 (python-tests-look-at "else\n")
4193 (should
4194 (equal (list
4195 (python-tests-look-at "elif var3:" -1 t)
4196 (python-tests-look-at "if var:" -1 t)
4197 (python-tests-look-at "except:" -1 t))
4198 (python-info-dedenter-opening-block-positions)))
4200 (python-tests-look-at "else\n")
4201 (should
4202 (equal (list
4203 (python-tests-look-at "while var5:" -1 t)
4204 (python-tests-look-at "if var4:" -1 t))
4205 (python-info-dedenter-opening-block-positions)))
4207 (python-tests-look-at "else\n")
4208 (should
4209 (equal (list
4210 (python-tests-look-at "if value > 0:" -1 t)
4211 (python-tests-look-at "for value in var6:" -1 t)
4212 (python-tests-look-at "if var4:" -1 t))
4213 (python-info-dedenter-opening-block-positions)))))
4215 (ert-deftest python-info-dedenter-opening-block-positions-4 ()
4216 "Test detection of opening blocks for except."
4217 (python-tests-with-temp-buffer
4219 try:
4220 something()
4221 except ValueError:
4222 something_else()
4223 except
4225 (python-tests-look-at "except ValueError:")
4226 (should
4227 (equal (list (python-tests-look-at "try:" -1 t))
4228 (python-info-dedenter-opening-block-positions)))
4230 (python-tests-look-at "except\n")
4231 (should
4232 (equal (list (python-tests-look-at "except ValueError:" -1 t))
4233 (python-info-dedenter-opening-block-positions)))))
4235 (ert-deftest python-info-dedenter-opening-block-positions-5 ()
4236 "Test detection of opening blocks for finally."
4237 (python-tests-with-temp-buffer
4239 try:
4240 something()
4241 finally
4243 try:
4244 something_else()
4245 except:
4246 logger.exception('something went wrong')
4247 finally
4249 try:
4250 something_else_else()
4251 except Exception:
4252 logger.exception('something else went wrong')
4253 else:
4254 print ('all good')
4255 finally
4257 (python-tests-look-at "finally\n")
4258 (should
4259 (equal (list (python-tests-look-at "try:" -1 t))
4260 (python-info-dedenter-opening-block-positions)))
4262 (python-tests-look-at "finally\n")
4263 (should
4264 (equal (list (python-tests-look-at "except:" -1 t))
4265 (python-info-dedenter-opening-block-positions)))
4267 (python-tests-look-at "finally\n")
4268 (should
4269 (equal (list (python-tests-look-at "else:" -1 t))
4270 (python-info-dedenter-opening-block-positions)))))
4272 (ert-deftest python-info-dedenter-opening-block-message-1 ()
4273 "Test dedenters inside strings are ignored."
4274 (python-tests-with-temp-buffer
4275 "'''
4276 try:
4277 something()
4278 except:
4279 logger.exception('something went wrong')
4282 (python-tests-look-at "except\n")
4283 (should (not (python-info-dedenter-opening-block-message)))))
4285 (ert-deftest python-info-dedenter-opening-block-message-2 ()
4286 "Test except keyword."
4287 (python-tests-with-temp-buffer
4289 try:
4290 something()
4291 except:
4292 logger.exception('something went wrong')
4294 (python-tests-look-at "except:")
4295 (should (string=
4296 "Closes try:"
4297 (substring-no-properties
4298 (python-info-dedenter-opening-block-message))))
4299 (end-of-line)
4300 (should (string=
4301 "Closes try:"
4302 (substring-no-properties
4303 (python-info-dedenter-opening-block-message))))))
4305 (ert-deftest python-info-dedenter-opening-block-message-3 ()
4306 "Test else keyword."
4307 (python-tests-with-temp-buffer
4309 try:
4310 something()
4311 except:
4312 logger.exception('something went wrong')
4313 else:
4314 logger.debug('all good')
4316 (python-tests-look-at "else:")
4317 (should (string=
4318 "Closes except:"
4319 (substring-no-properties
4320 (python-info-dedenter-opening-block-message))))
4321 (end-of-line)
4322 (should (string=
4323 "Closes except:"
4324 (substring-no-properties
4325 (python-info-dedenter-opening-block-message))))))
4327 (ert-deftest python-info-dedenter-opening-block-message-4 ()
4328 "Test finally keyword."
4329 (python-tests-with-temp-buffer
4331 try:
4332 something()
4333 except:
4334 logger.exception('something went wrong')
4335 else:
4336 logger.debug('all good')
4337 finally:
4338 clean()
4340 (python-tests-look-at "finally:")
4341 (should (string=
4342 "Closes else:"
4343 (substring-no-properties
4344 (python-info-dedenter-opening-block-message))))
4345 (end-of-line)
4346 (should (string=
4347 "Closes else:"
4348 (substring-no-properties
4349 (python-info-dedenter-opening-block-message))))))
4351 (ert-deftest python-info-dedenter-opening-block-message-5 ()
4352 "Test elif keyword."
4353 (python-tests-with-temp-buffer
4355 if a:
4356 something()
4357 elif b:
4359 (python-tests-look-at "elif b:")
4360 (should (string=
4361 "Closes if a:"
4362 (substring-no-properties
4363 (python-info-dedenter-opening-block-message))))
4364 (end-of-line)
4365 (should (string=
4366 "Closes if a:"
4367 (substring-no-properties
4368 (python-info-dedenter-opening-block-message))))))
4371 (ert-deftest python-info-dedenter-statement-p-1 ()
4372 "Test dedenters inside strings are ignored."
4373 (python-tests-with-temp-buffer
4374 "'''
4375 try:
4376 something()
4377 except:
4378 logger.exception('something went wrong')
4381 (python-tests-look-at "except\n")
4382 (should (not (python-info-dedenter-statement-p)))))
4384 (ert-deftest python-info-dedenter-statement-p-2 ()
4385 "Test except keyword."
4386 (python-tests-with-temp-buffer
4388 try:
4389 something()
4390 except:
4391 logger.exception('something went wrong')
4393 (python-tests-look-at "except:")
4394 (should (= (point) (python-info-dedenter-statement-p)))
4395 (end-of-line)
4396 (should (= (save-excursion
4397 (back-to-indentation)
4398 (point))
4399 (python-info-dedenter-statement-p)))))
4401 (ert-deftest python-info-dedenter-statement-p-3 ()
4402 "Test else keyword."
4403 (python-tests-with-temp-buffer
4405 try:
4406 something()
4407 except:
4408 logger.exception('something went wrong')
4409 else:
4410 logger.debug('all good')
4412 (python-tests-look-at "else:")
4413 (should (= (point) (python-info-dedenter-statement-p)))
4414 (end-of-line)
4415 (should (= (save-excursion
4416 (back-to-indentation)
4417 (point))
4418 (python-info-dedenter-statement-p)))))
4420 (ert-deftest python-info-dedenter-statement-p-4 ()
4421 "Test finally keyword."
4422 (python-tests-with-temp-buffer
4424 try:
4425 something()
4426 except:
4427 logger.exception('something went wrong')
4428 else:
4429 logger.debug('all good')
4430 finally:
4431 clean()
4433 (python-tests-look-at "finally:")
4434 (should (= (point) (python-info-dedenter-statement-p)))
4435 (end-of-line)
4436 (should (= (save-excursion
4437 (back-to-indentation)
4438 (point))
4439 (python-info-dedenter-statement-p)))))
4441 (ert-deftest python-info-dedenter-statement-p-5 ()
4442 "Test elif keyword."
4443 (python-tests-with-temp-buffer
4445 if a:
4446 something()
4447 elif b:
4449 (python-tests-look-at "elif b:")
4450 (should (= (point) (python-info-dedenter-statement-p)))
4451 (end-of-line)
4452 (should (= (save-excursion
4453 (back-to-indentation)
4454 (point))
4455 (python-info-dedenter-statement-p)))))
4457 (ert-deftest python-info-line-ends-backslash-p-1 ()
4458 (python-tests-with-temp-buffer
4460 objects = Thing.objects.all() \\\\
4461 .filter(
4462 type='toy',
4463 status='bought'
4464 ) \\\\
4465 .aggregate(
4466 Sum('amount')
4467 ) \\\\
4468 .values_list()
4470 (should (python-info-line-ends-backslash-p 2)) ; .filter(...
4471 (should (python-info-line-ends-backslash-p 3))
4472 (should (python-info-line-ends-backslash-p 4))
4473 (should (python-info-line-ends-backslash-p 5))
4474 (should (python-info-line-ends-backslash-p 6)) ; ) \...
4475 (should (python-info-line-ends-backslash-p 7))
4476 (should (python-info-line-ends-backslash-p 8))
4477 (should (python-info-line-ends-backslash-p 9))
4478 (should (not (python-info-line-ends-backslash-p 10))))) ; .values_list()...
4480 (ert-deftest python-info-beginning-of-backslash-1 ()
4481 (python-tests-with-temp-buffer
4483 objects = Thing.objects.all() \\\\
4484 .filter(
4485 type='toy',
4486 status='bought'
4487 ) \\\\
4488 .aggregate(
4489 Sum('amount')
4490 ) \\\\
4491 .values_list()
4493 (let ((first 2)
4494 (second (python-tests-look-at ".filter("))
4495 (third (python-tests-look-at ".aggregate(")))
4496 (should (= first (python-info-beginning-of-backslash 2)))
4497 (should (= second (python-info-beginning-of-backslash 3)))
4498 (should (= second (python-info-beginning-of-backslash 4)))
4499 (should (= second (python-info-beginning-of-backslash 5)))
4500 (should (= second (python-info-beginning-of-backslash 6)))
4501 (should (= third (python-info-beginning-of-backslash 7)))
4502 (should (= third (python-info-beginning-of-backslash 8)))
4503 (should (= third (python-info-beginning-of-backslash 9)))
4504 (should (not (python-info-beginning-of-backslash 10))))))
4506 (ert-deftest python-info-continuation-line-p-1 ()
4507 (python-tests-with-temp-buffer
4509 if width == 0 and height == 0 and \\\\
4510 color == 'red' and emphasis == 'strong' or \\\\
4511 highlight > 100:
4512 raise ValueError(
4513 'sorry, you lose'
4517 (python-tests-look-at "if width == 0 and height == 0 and")
4518 (should (not (python-info-continuation-line-p)))
4519 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4520 (should (python-info-continuation-line-p))
4521 (python-tests-look-at "highlight > 100:")
4522 (should (python-info-continuation-line-p))
4523 (python-tests-look-at "raise ValueError(")
4524 (should (not (python-info-continuation-line-p)))
4525 (python-tests-look-at "'sorry, you lose'")
4526 (should (python-info-continuation-line-p))
4527 (forward-line 1)
4528 (should (python-info-continuation-line-p))
4529 (python-tests-look-at ")")
4530 (should (python-info-continuation-line-p))
4531 (forward-line 1)
4532 (should (not (python-info-continuation-line-p)))))
4534 (ert-deftest python-info-block-continuation-line-p-1 ()
4535 (python-tests-with-temp-buffer
4537 if width == 0 and height == 0 and \\\\
4538 color == 'red' and emphasis == 'strong' or \\\\
4539 highlight > 100:
4540 raise ValueError(
4541 'sorry, you lose'
4545 (python-tests-look-at "if width == 0 and")
4546 (should (not (python-info-block-continuation-line-p)))
4547 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4548 (should (= (python-info-block-continuation-line-p)
4549 (python-tests-look-at "if width == 0 and" -1 t)))
4550 (python-tests-look-at "highlight > 100:")
4551 (should (not (python-info-block-continuation-line-p)))))
4553 (ert-deftest python-info-block-continuation-line-p-2 ()
4554 (python-tests-with-temp-buffer
4556 def foo(a,
4559 pass
4561 (python-tests-look-at "def foo(a,")
4562 (should (not (python-info-block-continuation-line-p)))
4563 (python-tests-look-at "b,")
4564 (should (= (python-info-block-continuation-line-p)
4565 (python-tests-look-at "def foo(a," -1 t)))
4566 (python-tests-look-at "c):")
4567 (should (not (python-info-block-continuation-line-p)))))
4569 (ert-deftest python-info-assignment-statement-p-1 ()
4570 (python-tests-with-temp-buffer
4572 data = foo(), bar() \\\\
4573 baz(), 4 \\\\
4574 5, 6
4576 (python-tests-look-at "data = foo(), bar()")
4577 (should (python-info-assignment-statement-p))
4578 (should (python-info-assignment-statement-p t))
4579 (python-tests-look-at "baz(), 4")
4580 (should (python-info-assignment-statement-p))
4581 (should (not (python-info-assignment-statement-p t)))
4582 (python-tests-look-at "5, 6")
4583 (should (python-info-assignment-statement-p))
4584 (should (not (python-info-assignment-statement-p t)))))
4586 (ert-deftest python-info-assignment-statement-p-2 ()
4587 (python-tests-with-temp-buffer
4589 data = (foo(), bar()
4590 baz(), 4
4591 5, 6)
4593 (python-tests-look-at "data = (foo(), bar()")
4594 (should (python-info-assignment-statement-p))
4595 (should (python-info-assignment-statement-p t))
4596 (python-tests-look-at "baz(), 4")
4597 (should (python-info-assignment-statement-p))
4598 (should (not (python-info-assignment-statement-p t)))
4599 (python-tests-look-at "5, 6)")
4600 (should (python-info-assignment-statement-p))
4601 (should (not (python-info-assignment-statement-p t)))))
4603 (ert-deftest python-info-assignment-statement-p-3 ()
4604 (python-tests-with-temp-buffer
4606 data '=' 42
4608 (python-tests-look-at "data '=' 42")
4609 (should (not (python-info-assignment-statement-p)))
4610 (should (not (python-info-assignment-statement-p t)))))
4612 (ert-deftest python-info-assignment-continuation-line-p-1 ()
4613 (python-tests-with-temp-buffer
4615 data = foo(), bar() \\\\
4616 baz(), 4 \\\\
4617 5, 6
4619 (python-tests-look-at "data = foo(), bar()")
4620 (should (not (python-info-assignment-continuation-line-p)))
4621 (python-tests-look-at "baz(), 4")
4622 (should (= (python-info-assignment-continuation-line-p)
4623 (python-tests-look-at "foo()," -1 t)))
4624 (python-tests-look-at "5, 6")
4625 (should (not (python-info-assignment-continuation-line-p)))))
4627 (ert-deftest python-info-assignment-continuation-line-p-2 ()
4628 (python-tests-with-temp-buffer
4630 data = (foo(), bar()
4631 baz(), 4
4632 5, 6)
4634 (python-tests-look-at "data = (foo(), bar()")
4635 (should (not (python-info-assignment-continuation-line-p)))
4636 (python-tests-look-at "baz(), 4")
4637 (should (= (python-info-assignment-continuation-line-p)
4638 (python-tests-look-at "(foo()," -1 t)))
4639 (python-tests-look-at "5, 6)")
4640 (should (not (python-info-assignment-continuation-line-p)))))
4642 (ert-deftest python-info-looking-at-beginning-of-defun-1 ()
4643 (python-tests-with-temp-buffer
4645 def decorat0r(deff):
4646 '''decorates stuff.
4648 @decorat0r
4649 def foo(arg):
4652 def wrap():
4653 deff()
4654 return wwrap
4656 (python-tests-look-at "def decorat0r(deff):")
4657 (should (python-info-looking-at-beginning-of-defun))
4658 (python-tests-look-at "def foo(arg):")
4659 (should (not (python-info-looking-at-beginning-of-defun)))
4660 (python-tests-look-at "def wrap():")
4661 (should (python-info-looking-at-beginning-of-defun))
4662 (python-tests-look-at "deff()")
4663 (should (not (python-info-looking-at-beginning-of-defun)))))
4665 (ert-deftest python-info-current-line-comment-p-1 ()
4666 (python-tests-with-temp-buffer
4668 # this is a comment
4669 foo = True # another comment
4670 '#this is a string'
4671 if foo:
4672 # more comments
4673 print ('bar') # print bar
4675 (python-tests-look-at "# this is a comment")
4676 (should (python-info-current-line-comment-p))
4677 (python-tests-look-at "foo = True # another comment")
4678 (should (not (python-info-current-line-comment-p)))
4679 (python-tests-look-at "'#this is a string'")
4680 (should (not (python-info-current-line-comment-p)))
4681 (python-tests-look-at "# more comments")
4682 (should (python-info-current-line-comment-p))
4683 (python-tests-look-at "print ('bar') # print bar")
4684 (should (not (python-info-current-line-comment-p)))))
4686 (ert-deftest python-info-current-line-empty-p ()
4687 (python-tests-with-temp-buffer
4689 # this is a comment
4691 foo = True # another comment
4693 (should (python-info-current-line-empty-p))
4694 (python-tests-look-at "# this is a comment")
4695 (should (not (python-info-current-line-empty-p)))
4696 (forward-line 1)
4697 (should (python-info-current-line-empty-p))))
4699 (ert-deftest python-info-docstring-p-1 ()
4700 "Test module docstring detection."
4701 (python-tests-with-temp-buffer
4702 "# -*- coding: utf-8 -*-
4703 #!/usr/bin/python
4706 Module Docstring Django style.
4708 u'''Additional module docstring.'''
4709 '''Not a module docstring.'''
4711 (python-tests-look-at "Module Docstring Django style.")
4712 (should (python-info-docstring-p))
4713 (python-tests-look-at "u'''Additional module docstring.'''")
4714 (should (python-info-docstring-p))
4715 (python-tests-look-at "'''Not a module docstring.'''")
4716 (should (not (python-info-docstring-p)))))
4718 (ert-deftest python-info-docstring-p-2 ()
4719 "Test variable docstring detection."
4720 (python-tests-with-temp-buffer
4722 variable = 42
4723 U'''Variable docstring.'''
4724 '''Additional variable docstring.'''
4725 '''Not a variable docstring.'''
4727 (python-tests-look-at "Variable docstring.")
4728 (should (python-info-docstring-p))
4729 (python-tests-look-at "u'''Additional variable docstring.'''")
4730 (should (python-info-docstring-p))
4731 (python-tests-look-at "'''Not a variable docstring.'''")
4732 (should (not (python-info-docstring-p)))))
4734 (ert-deftest python-info-docstring-p-3 ()
4735 "Test function docstring detection."
4736 (python-tests-with-temp-buffer
4738 def func(a, b):
4739 r'''
4740 Function docstring.
4742 onetwo style.
4744 R'''Additional function docstring.'''
4745 '''Not a function docstring.'''
4746 return a + b
4748 (python-tests-look-at "Function docstring.")
4749 (should (python-info-docstring-p))
4750 (python-tests-look-at "R'''Additional function docstring.'''")
4751 (should (python-info-docstring-p))
4752 (python-tests-look-at "'''Not a function docstring.'''")
4753 (should (not (python-info-docstring-p)))))
4755 (ert-deftest python-info-docstring-p-4 ()
4756 "Test class docstring detection."
4757 (python-tests-with-temp-buffer
4759 class Class:
4760 ur'''
4761 Class docstring.
4763 symmetric style.
4765 uR'''
4766 Additional class docstring.
4768 '''Not a class docstring.'''
4769 pass
4771 (python-tests-look-at "Class docstring.")
4772 (should (python-info-docstring-p))
4773 (python-tests-look-at "uR'''") ;; Additional class docstring
4774 (should (python-info-docstring-p))
4775 (python-tests-look-at "'''Not a class docstring.'''")
4776 (should (not (python-info-docstring-p)))))
4778 (ert-deftest python-info-docstring-p-5 ()
4779 "Test class attribute docstring detection."
4780 (python-tests-with-temp-buffer
4782 class Class:
4783 attribute = 42
4784 Ur'''
4785 Class attribute docstring.
4787 pep-257 style.
4790 UR'''
4791 Additional class attribute docstring.
4793 '''Not a class attribute docstring.'''
4794 pass
4796 (python-tests-look-at "Class attribute docstring.")
4797 (should (python-info-docstring-p))
4798 (python-tests-look-at "UR'''") ;; Additional class attr docstring
4799 (should (python-info-docstring-p))
4800 (python-tests-look-at "'''Not a class attribute docstring.'''")
4801 (should (not (python-info-docstring-p)))))
4803 (ert-deftest python-info-docstring-p-6 ()
4804 "Test class method docstring detection."
4805 (python-tests-with-temp-buffer
4807 class Class:
4809 def __init__(self, a, b):
4810 self.a = a
4811 self.b = b
4813 def __call__(self):
4814 '''Method docstring.
4816 pep-257-nn style.
4818 '''Additional method docstring.'''
4819 '''Not a method docstring.'''
4820 return self.a + self.b
4822 (python-tests-look-at "Method docstring.")
4823 (should (python-info-docstring-p))
4824 (python-tests-look-at "'''Additional method docstring.'''")
4825 (should (python-info-docstring-p))
4826 (python-tests-look-at "'''Not a method docstring.'''")
4827 (should (not (python-info-docstring-p)))))
4829 (ert-deftest python-info-encoding-from-cookie-1 ()
4830 "Should detect it on first line."
4831 (python-tests-with-temp-buffer
4832 "# coding=latin-1
4834 foo = True # another comment
4836 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4838 (ert-deftest python-info-encoding-from-cookie-2 ()
4839 "Should detect it on second line."
4840 (python-tests-with-temp-buffer
4842 # coding=latin-1
4844 foo = True # another comment
4846 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4848 (ert-deftest python-info-encoding-from-cookie-3 ()
4849 "Should not be detected on third line (and following ones)."
4850 (python-tests-with-temp-buffer
4853 # coding=latin-1
4854 foo = True # another comment
4856 (should (not (python-info-encoding-from-cookie)))))
4858 (ert-deftest python-info-encoding-from-cookie-4 ()
4859 "Should detect Emacs style."
4860 (python-tests-with-temp-buffer
4861 "# -*- coding: latin-1 -*-
4863 foo = True # another comment"
4864 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4866 (ert-deftest python-info-encoding-from-cookie-5 ()
4867 "Should detect Vim style."
4868 (python-tests-with-temp-buffer
4869 "# vim: set fileencoding=latin-1 :
4871 foo = True # another comment"
4872 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4874 (ert-deftest python-info-encoding-from-cookie-6 ()
4875 "First cookie wins."
4876 (python-tests-with-temp-buffer
4877 "# -*- coding: iso-8859-1 -*-
4878 # vim: set fileencoding=latin-1 :
4880 foo = True # another comment"
4881 (should (eq (python-info-encoding-from-cookie) 'iso-8859-1))))
4883 (ert-deftest python-info-encoding-from-cookie-7 ()
4884 "First cookie wins."
4885 (python-tests-with-temp-buffer
4886 "# vim: set fileencoding=latin-1 :
4887 # -*- coding: iso-8859-1 -*-
4889 foo = True # another comment"
4890 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4892 (ert-deftest python-info-encoding-1 ()
4893 "Should return the detected encoding from cookie."
4894 (python-tests-with-temp-buffer
4895 "# vim: set fileencoding=latin-1 :
4897 foo = True # another comment"
4898 (should (eq (python-info-encoding) 'latin-1))))
4900 (ert-deftest python-info-encoding-2 ()
4901 "Should default to utf-8."
4902 (python-tests-with-temp-buffer
4903 "# No encoding for you
4905 foo = True # another comment"
4906 (should (eq (python-info-encoding) 'utf-8))))
4909 ;;; Utility functions
4911 (ert-deftest python-util-goto-line-1 ()
4912 (python-tests-with-temp-buffer
4913 (concat
4914 "# a comment
4915 # another comment
4916 def foo(a, b, c):
4917 pass" (make-string 20 ?\n))
4918 (python-util-goto-line 10)
4919 (should (= (line-number-at-pos) 10))
4920 (python-util-goto-line 20)
4921 (should (= (line-number-at-pos) 20))))
4923 (ert-deftest python-util-clone-local-variables-1 ()
4924 (let ((buffer (generate-new-buffer
4925 "python-util-clone-local-variables-1"))
4926 (varcons
4927 '((python-fill-docstring-style . django)
4928 (python-shell-interpreter . "python")
4929 (python-shell-interpreter-args . "manage.py shell")
4930 (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
4931 (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
4932 (python-shell-extra-pythonpaths "/home/user/pylib/")
4933 (python-shell-completion-setup-code
4934 . "from IPython.core.completerlib import module_completion")
4935 (python-shell-completion-string-code
4936 . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
4937 (python-shell-virtualenv-root
4938 . "/home/user/.virtualenvs/project"))))
4939 (with-current-buffer buffer
4940 (kill-all-local-variables)
4941 (dolist (ccons varcons)
4942 (set (make-local-variable (car ccons)) (cdr ccons))))
4943 (python-tests-with-temp-buffer
4945 (python-util-clone-local-variables buffer)
4946 (dolist (ccons varcons)
4947 (should
4948 (equal (symbol-value (car ccons)) (cdr ccons)))))
4949 (kill-buffer buffer)))
4951 (ert-deftest python-util-strip-string-1 ()
4952 (should (string= (python-util-strip-string "\t\r\n str") "str"))
4953 (should (string= (python-util-strip-string "str \n\r") "str"))
4954 (should (string= (python-util-strip-string "\t\r\n str \n\r ") "str"))
4955 (should
4956 (string= (python-util-strip-string "\n str \nin \tg \n\r") "str \nin \tg"))
4957 (should (string= (python-util-strip-string "\n \t \n\r ") ""))
4958 (should (string= (python-util-strip-string "") "")))
4960 (ert-deftest python-util-forward-comment-1 ()
4961 (python-tests-with-temp-buffer
4962 (concat
4963 "# a comment
4964 # another comment
4965 # bad indented comment
4966 # more comments" (make-string 9999 ?\n))
4967 (python-util-forward-comment 1)
4968 (should (= (point) (point-max)))
4969 (python-util-forward-comment -1)
4970 (should (= (point) (point-min)))))
4972 (ert-deftest python-util-valid-regexp-p-1 ()
4973 (should (python-util-valid-regexp-p ""))
4974 (should (python-util-valid-regexp-p python-shell-prompt-regexp))
4975 (should (not (python-util-valid-regexp-p "\\("))))
4978 ;;; Electricity
4980 (ert-deftest python-parens-electric-indent-1 ()
4981 (let ((eim electric-indent-mode))
4982 (unwind-protect
4983 (progn
4984 (python-tests-with-temp-buffer
4986 from django.conf.urls import patterns, include, url
4988 from django.contrib import admin
4990 from myapp import views
4993 urlpatterns = patterns('',
4994 url(r'^$', views.index
4997 (electric-indent-mode 1)
4998 (python-tests-look-at "views.index")
4999 (end-of-line)
5001 ;; Inserting commas within the same line should leave
5002 ;; indentation unchanged.
5003 (python-tests-self-insert ",")
5004 (should (= (current-indentation) 4))
5006 ;; As well as any other input happening within the same
5007 ;; set of parens.
5008 (python-tests-self-insert " name='index')")
5009 (should (= (current-indentation) 4))
5011 ;; But a comma outside it, should trigger indentation.
5012 (python-tests-self-insert ",")
5013 (should (= (current-indentation) 23))
5015 ;; Newline indents to the first argument column
5016 (python-tests-self-insert "\n")
5017 (should (= (current-indentation) 23))
5019 ;; All this input must not change indentation
5020 (indent-line-to 4)
5021 (python-tests-self-insert "url(r'^/login$', views.login)")
5022 (should (= (current-indentation) 4))
5024 ;; But this comma does
5025 (python-tests-self-insert ",")
5026 (should (= (current-indentation) 23))))
5027 (or eim (electric-indent-mode -1)))))
5029 (ert-deftest python-triple-quote-pairing ()
5030 (let ((epm electric-pair-mode))
5031 (unwind-protect
5032 (progn
5033 (python-tests-with-temp-buffer
5034 "\"\"\n"
5035 (or epm (electric-pair-mode 1))
5036 (goto-char (1- (point-max)))
5037 (python-tests-self-insert ?\")
5038 (should (string= (buffer-string)
5039 "\"\"\"\"\"\"\n"))
5040 (should (= (point) 4)))
5041 (python-tests-with-temp-buffer
5042 "\n"
5043 (python-tests-self-insert (list ?\" ?\" ?\"))
5044 (should (string= (buffer-string)
5045 "\"\"\"\"\"\"\n"))
5046 (should (= (point) 4)))
5047 (python-tests-with-temp-buffer
5048 "\"\n\"\"\n"
5049 (goto-char (1- (point-max)))
5050 (python-tests-self-insert ?\")
5051 (should (= (point) (1- (point-max))))
5052 (should (string= (buffer-string)
5053 "\"\n\"\"\"\n"))))
5054 (or epm (electric-pair-mode -1)))))
5057 ;;; Hideshow support
5059 (ert-deftest python-hideshow-hide-levels-1 ()
5060 "Should hide all methods when called after class start."
5061 (let ((enabled hs-minor-mode))
5062 (unwind-protect
5063 (progn
5064 (python-tests-with-temp-buffer
5066 class SomeClass:
5068 def __init__(self, arg, kwarg=1):
5069 self.arg = arg
5070 self.kwarg = kwarg
5072 def filter(self, nums):
5073 def fn(item):
5074 return item in [self.arg, self.kwarg]
5075 return filter(fn, nums)
5077 def __str__(self):
5078 return '%s-%s' % (self.arg, self.kwarg)
5080 (hs-minor-mode 1)
5081 (python-tests-look-at "class SomeClass:")
5082 (forward-line)
5083 (hs-hide-level 1)
5084 (should
5085 (string=
5086 (python-tests-visible-string)
5088 class SomeClass:
5090 def __init__(self, arg, kwarg=1):
5091 def filter(self, nums):
5092 def __str__(self):"))))
5093 (or enabled (hs-minor-mode -1)))))
5095 (ert-deftest python-hideshow-hide-levels-2 ()
5096 "Should hide nested methods and parens at end of defun."
5097 (let ((enabled hs-minor-mode))
5098 (unwind-protect
5099 (progn
5100 (python-tests-with-temp-buffer
5102 class SomeClass:
5104 def __init__(self, arg, kwarg=1):
5105 self.arg = arg
5106 self.kwarg = kwarg
5108 def filter(self, nums):
5109 def fn(item):
5110 return item in [self.arg, self.kwarg]
5111 return filter(fn, nums)
5113 def __str__(self):
5114 return '%s-%s' % (self.arg, self.kwarg)
5116 (hs-minor-mode 1)
5117 (python-tests-look-at "def fn(item):")
5118 (hs-hide-block)
5119 (should
5120 (string=
5121 (python-tests-visible-string)
5123 class SomeClass:
5125 def __init__(self, arg, kwarg=1):
5126 self.arg = arg
5127 self.kwarg = kwarg
5129 def filter(self, nums):
5130 def fn(item):
5131 return filter(fn, nums)
5133 def __str__(self):
5134 return '%s-%s' % (self.arg, self.kwarg)
5135 "))))
5136 (or enabled (hs-minor-mode -1)))))
5140 (provide 'python-tests)
5142 ;; Local Variables:
5143 ;; coding: utf-8
5144 ;; indent-tabs-mode: nil
5145 ;; End:
5147 ;;; python-tests.el ends here