Improve treatment of Fortran's "class is"
[emacs.git] / test / automated / python-tests.el
blobf6564dd58cc6d9af23ced2c1b7b2dad3f7b1e7ad
1 ;;; python-tests.el --- Test suite for python.el
3 ;; Copyright (C) 2013-2016 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 (let ((python-indent-guess-indent-offset nil))
40 (python-mode)
41 (insert ,contents)
42 (goto-char (point-min))
43 ,@body)))
45 (defmacro python-tests-with-temp-file (contents &rest body)
46 "Create a `python-mode' enabled file with CONTENTS.
47 BODY is code to be executed within the temp buffer. Point is
48 always located at the beginning of buffer."
49 (declare (indent 1) (debug t))
50 ;; temp-file never actually used for anything?
51 `(let* ((temp-file (make-temp-file "python-tests" nil ".py"))
52 (buffer (find-file-noselect temp-file))
53 (python-indent-guess-indent-offset nil))
54 (unwind-protect
55 (with-current-buffer buffer
56 (python-mode)
57 (insert ,contents)
58 (goto-char (point-min))
59 ,@body)
60 (and buffer (kill-buffer buffer))
61 (delete-file temp-file))))
63 (defun python-tests-look-at (string &optional num restore-point)
64 "Move point at beginning of STRING in the current buffer.
65 Optional argument NUM defaults to 1 and is an integer indicating
66 how many occurrences must be found, when positive the search is
67 done forwards, otherwise backwards. When RESTORE-POINT is
68 non-nil the point is not moved but the position found is still
69 returned. When searching forward and point is already looking at
70 STRING, it is skipped so the next STRING occurrence is selected."
71 (let* ((num (or num 1))
72 (starting-point (point))
73 (string (regexp-quote string))
74 (search-fn (if (> num 0) #'re-search-forward #'re-search-backward))
75 (deinc-fn (if (> num 0) #'1- #'1+))
76 (found-point))
77 (prog2
78 (catch 'exit
79 (while (not (= num 0))
80 (when (and (> num 0)
81 (looking-at string))
82 ;; Moving forward and already looking at STRING, skip it.
83 (forward-char (length (match-string-no-properties 0))))
84 (and (not (funcall search-fn string nil t))
85 (throw 'exit t))
86 (when (> num 0)
87 ;; `re-search-forward' leaves point at the end of the
88 ;; occurrence, move back so point is at the beginning
89 ;; instead.
90 (forward-char (- (length (match-string-no-properties 0)))))
91 (setq
92 num (funcall deinc-fn num)
93 found-point (point))))
94 found-point
95 (and restore-point (goto-char starting-point)))))
97 (defun python-tests-self-insert (char-or-str)
98 "Call `self-insert-command' for chars in CHAR-OR-STR."
99 (let ((chars
100 (cond
101 ((characterp char-or-str)
102 (list char-or-str))
103 ((stringp char-or-str)
104 (string-to-list char-or-str))
105 ((not
106 (cl-remove-if #'characterp char-or-str))
107 char-or-str)
108 (t (error "CHAR-OR-STR must be a char, string, or list of char")))))
109 (mapc
110 (lambda (char)
111 (let ((last-command-event char))
112 (call-interactively 'self-insert-command)))
113 chars)))
115 (defun python-tests-visible-string (&optional min max)
116 "Return the buffer string excluding invisible overlays.
117 Argument MIN and MAX delimit the region to be returned and
118 default to `point-min' and `point-max' respectively."
119 (let* ((min (or min (point-min)))
120 (max (or max (point-max)))
121 (buffer (current-buffer))
122 (buffer-contents (buffer-substring-no-properties min max))
123 (overlays
124 (sort (overlays-in min max)
125 (lambda (a b)
126 (let ((overlay-end-a (overlay-end a))
127 (overlay-end-b (overlay-end b)))
128 (> overlay-end-a overlay-end-b))))))
129 (with-temp-buffer
130 (insert buffer-contents)
131 (dolist (overlay overlays)
132 (if (overlay-get overlay 'invisible)
133 (delete-region (overlay-start overlay)
134 (overlay-end overlay))))
135 (buffer-substring-no-properties (point-min) (point-max)))))
138 ;;; Tests for your tests, so you can test while you test.
140 (ert-deftest python-tests-look-at-1 ()
141 "Test forward movement."
142 (python-tests-with-temp-buffer
143 "Lorem ipsum dolor sit amet, consectetur adipisicing elit,
144 sed do eiusmod tempor incididunt ut labore et dolore magna
145 aliqua."
146 (let ((expected (save-excursion
147 (dotimes (i 3)
148 (re-search-forward "et" nil t))
149 (forward-char -2)
150 (point))))
151 (should (= (python-tests-look-at "et" 3 t) expected))
152 ;; Even if NUM is bigger than found occurrences the point of last
153 ;; one should be returned.
154 (should (= (python-tests-look-at "et" 6 t) expected))
155 ;; If already looking at STRING, it should skip it.
156 (dotimes (i 2) (re-search-forward "et"))
157 (forward-char -2)
158 (should (= (python-tests-look-at "et") expected)))))
160 (ert-deftest python-tests-look-at-2 ()
161 "Test backward movement."
162 (python-tests-with-temp-buffer
163 "Lorem ipsum dolor sit amet, consectetur adipisicing elit,
164 sed do eiusmod tempor incididunt ut labore et dolore magna
165 aliqua."
166 (let ((expected
167 (save-excursion
168 (re-search-forward "et" nil t)
169 (forward-char -2)
170 (point))))
171 (dotimes (i 3)
172 (re-search-forward "et" nil t))
173 (should (= (python-tests-look-at "et" -3 t) expected))
174 (should (= (python-tests-look-at "et" -6 t) expected)))))
177 ;;; Bindings
180 ;;; Python specialized rx
183 ;;; Font-lock and syntax
185 (ert-deftest python-syntax-after-python-backspace ()
186 ;; `python-indent-dedent-line-backspace' garbles syntax
187 :expected-result :failed
188 (python-tests-with-temp-buffer
189 "\"\"\""
190 (goto-char (point-max))
191 (python-indent-dedent-line-backspace 1)
192 (should (string= (buffer-string) "\"\""))
193 (should (null (nth 3 (syntax-ppss))))))
196 ;;; Indentation
198 ;; See: http://www.python.org/dev/peps/pep-0008/#indentation
200 (ert-deftest python-indent-pep8-1 ()
201 "First pep8 case."
202 (python-tests-with-temp-buffer
203 "# Aligned with opening delimiter
204 foo = long_function_name(var_one, var_two,
205 var_three, var_four)
207 (should (eq (car (python-indent-context)) :no-indent))
208 (should (= (python-indent-calculate-indentation) 0))
209 (python-tests-look-at "foo = long_function_name(var_one, var_two,")
210 (should (eq (car (python-indent-context)) :after-comment))
211 (should (= (python-indent-calculate-indentation) 0))
212 (python-tests-look-at "var_three, var_four)")
213 (should (eq (car (python-indent-context)) :inside-paren))
214 (should (= (python-indent-calculate-indentation) 25))))
216 (ert-deftest python-indent-pep8-2 ()
217 "Second pep8 case."
218 (python-tests-with-temp-buffer
219 "# More indentation included to distinguish this from the rest.
220 def long_function_name(
221 var_one, var_two, var_three,
222 var_four):
223 print (var_one)
225 (should (eq (car (python-indent-context)) :no-indent))
226 (should (= (python-indent-calculate-indentation) 0))
227 (python-tests-look-at "def long_function_name(")
228 (should (eq (car (python-indent-context)) :after-comment))
229 (should (= (python-indent-calculate-indentation) 0))
230 (python-tests-look-at "var_one, var_two, var_three,")
231 (should (eq (car (python-indent-context))
232 :inside-paren-newline-start-from-block))
233 (should (= (python-indent-calculate-indentation) 8))
234 (python-tests-look-at "var_four):")
235 (should (eq (car (python-indent-context))
236 :inside-paren-newline-start-from-block))
237 (should (= (python-indent-calculate-indentation) 8))
238 (python-tests-look-at "print (var_one)")
239 (should (eq (car (python-indent-context))
240 :after-block-start))
241 (should (= (python-indent-calculate-indentation) 4))))
243 (ert-deftest python-indent-pep8-3 ()
244 "Third pep8 case."
245 (python-tests-with-temp-buffer
246 "# Extra indentation is not necessary.
247 foo = long_function_name(
248 var_one, var_two,
249 var_three, var_four)
251 (should (eq (car (python-indent-context)) :no-indent))
252 (should (= (python-indent-calculate-indentation) 0))
253 (python-tests-look-at "foo = long_function_name(")
254 (should (eq (car (python-indent-context)) :after-comment))
255 (should (= (python-indent-calculate-indentation) 0))
256 (python-tests-look-at "var_one, var_two,")
257 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
258 (should (= (python-indent-calculate-indentation) 4))
259 (python-tests-look-at "var_three, var_four)")
260 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
261 (should (= (python-indent-calculate-indentation) 4))))
263 (ert-deftest python-indent-base-case ()
264 "Check base case does not trigger errors."
265 (python-tests-with-temp-buffer
269 (goto-char (point-min))
270 (should (eq (car (python-indent-context)) :no-indent))
271 (should (= (python-indent-calculate-indentation) 0))
272 (forward-line 1)
273 (should (eq (car (python-indent-context)) :no-indent))
274 (should (= (python-indent-calculate-indentation) 0))
275 (forward-line 1)
276 (should (eq (car (python-indent-context)) :no-indent))
277 (should (= (python-indent-calculate-indentation) 0))))
279 (ert-deftest python-indent-after-comment-1 ()
280 "The most simple after-comment case that shouldn't fail."
281 (python-tests-with-temp-buffer
282 "# Contents will be modified to correct indentation
283 class Blag(object):
284 def _on_child_complete(self, child_future):
285 if self.in_terminal_state():
286 pass
287 # We only complete when all our async children have entered a
288 # terminal state. At that point, if any child failed, we fail
289 # with the exception with which the first child failed.
291 (python-tests-look-at "# We only complete")
292 (should (eq (car (python-indent-context)) :after-block-end))
293 (should (= (python-indent-calculate-indentation) 8))
294 (python-tests-look-at "# terminal state")
295 (should (eq (car (python-indent-context)) :after-comment))
296 (should (= (python-indent-calculate-indentation) 8))
297 (python-tests-look-at "# with the exception")
298 (should (eq (car (python-indent-context)) :after-comment))
299 ;; This one indents relative to previous block, even given the fact
300 ;; that it was under-indented.
301 (should (= (python-indent-calculate-indentation) 4))
302 (python-tests-look-at "# terminal state" -1)
303 ;; It doesn't hurt to check again.
304 (should (eq (car (python-indent-context)) :after-comment))
305 (python-indent-line)
306 (should (= (current-indentation) 8))
307 (python-tests-look-at "# with the exception")
308 (should (eq (car (python-indent-context)) :after-comment))
309 ;; Now everything should be lined up.
310 (should (= (python-indent-calculate-indentation) 8))))
312 (ert-deftest python-indent-after-comment-2 ()
313 "Test after-comment in weird cases."
314 (python-tests-with-temp-buffer
315 "# Contents will be modified to correct indentation
316 def func(arg):
317 # I don't do much
318 return arg
319 # This comment is badly indented because the user forced so.
320 # At this line python.el wont dedent, user is always right.
322 comment_wins_over_ender = True
324 # yeah, that.
326 (python-tests-look-at "# I don't do much")
327 (should (eq (car (python-indent-context)) :after-block-start))
328 (should (= (python-indent-calculate-indentation) 4))
329 (python-tests-look-at "return arg")
330 ;; Comment here just gets ignored, this line is not a comment so
331 ;; the rules won't apply here.
332 (should (eq (car (python-indent-context)) :after-block-start))
333 (should (= (python-indent-calculate-indentation) 4))
334 (python-tests-look-at "# This comment is badly indented")
335 (should (eq (car (python-indent-context)) :after-block-end))
336 ;; The return keyword do make indentation lose a level...
337 (should (= (python-indent-calculate-indentation) 0))
338 ;; ...but the current indentation was forced by the user.
339 (python-tests-look-at "# At this line python.el wont dedent")
340 (should (eq (car (python-indent-context)) :after-comment))
341 (should (= (python-indent-calculate-indentation) 4))
342 ;; Should behave the same for blank lines: potentially a comment.
343 (forward-line 1)
344 (should (eq (car (python-indent-context)) :after-comment))
345 (should (= (python-indent-calculate-indentation) 4))
346 (python-tests-look-at "comment_wins_over_ender")
347 ;; The comment won over the ender because the user said so.
348 (should (eq (car (python-indent-context)) :after-comment))
349 (should (= (python-indent-calculate-indentation) 4))
350 ;; The indentation calculated fine for the assignment, but the user
351 ;; choose to force it back to the first column. Next line should
352 ;; be aware of that.
353 (python-tests-look-at "# yeah, that.")
354 (should (eq (car (python-indent-context)) :after-line))
355 (should (= (python-indent-calculate-indentation) 0))))
357 (ert-deftest python-indent-after-comment-3 ()
358 "Test after-comment in buggy case."
359 (python-tests-with-temp-buffer
361 class A(object):
363 def something(self, arg):
364 if True:
365 return arg
367 # A comment
369 @adecorator
370 def method(self, a, b):
371 pass
373 (python-tests-look-at "@adecorator")
374 (should (eq (car (python-indent-context)) :after-comment))
375 (should (= (python-indent-calculate-indentation) 4))))
377 (ert-deftest python-indent-inside-paren-1 ()
378 "The most simple inside-paren case that shouldn't fail."
379 (python-tests-with-temp-buffer
381 data = {
382 'key':
384 'objlist': [
386 'pk': 1,
387 'name': 'first',
390 'pk': 2,
391 'name': 'second',
397 (python-tests-look-at "data = {")
398 (should (eq (car (python-indent-context)) :no-indent))
399 (should (= (python-indent-calculate-indentation) 0))
400 (python-tests-look-at "'key':")
401 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
402 (should (= (python-indent-calculate-indentation) 4))
403 (python-tests-look-at "{")
404 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
405 (should (= (python-indent-calculate-indentation) 4))
406 (python-tests-look-at "'objlist': [")
407 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
408 (should (= (python-indent-calculate-indentation) 8))
409 (python-tests-look-at "{")
410 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
411 (should (= (python-indent-calculate-indentation) 12))
412 (python-tests-look-at "'pk': 1,")
413 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
414 (should (= (python-indent-calculate-indentation) 16))
415 (python-tests-look-at "'name': 'first',")
416 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
417 (should (= (python-indent-calculate-indentation) 16))
418 (python-tests-look-at "},")
419 (should (eq (car (python-indent-context))
420 :inside-paren-at-closing-nested-paren))
421 (should (= (python-indent-calculate-indentation) 12))
422 (python-tests-look-at "{")
423 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
424 (should (= (python-indent-calculate-indentation) 12))
425 (python-tests-look-at "'pk': 2,")
426 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
427 (should (= (python-indent-calculate-indentation) 16))
428 (python-tests-look-at "'name': 'second',")
429 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
430 (should (= (python-indent-calculate-indentation) 16))
431 (python-tests-look-at "}")
432 (should (eq (car (python-indent-context))
433 :inside-paren-at-closing-nested-paren))
434 (should (= (python-indent-calculate-indentation) 12))
435 (python-tests-look-at "]")
436 (should (eq (car (python-indent-context))
437 :inside-paren-at-closing-nested-paren))
438 (should (= (python-indent-calculate-indentation) 8))
439 (python-tests-look-at "}")
440 (should (eq (car (python-indent-context))
441 :inside-paren-at-closing-nested-paren))
442 (should (= (python-indent-calculate-indentation) 4))
443 (python-tests-look-at "}")
444 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
445 (should (= (python-indent-calculate-indentation) 0))))
447 (ert-deftest python-indent-inside-paren-2 ()
448 "Another more compact paren group style."
449 (python-tests-with-temp-buffer
451 data = {'key': {
452 'objlist': [
453 {'pk': 1,
454 'name': 'first'},
455 {'pk': 2,
456 'name': 'second'}
460 (python-tests-look-at "data = {")
461 (should (eq (car (python-indent-context)) :no-indent))
462 (should (= (python-indent-calculate-indentation) 0))
463 (python-tests-look-at "'objlist': [")
464 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
465 (should (= (python-indent-calculate-indentation) 4))
466 (python-tests-look-at "{'pk': 1,")
467 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
468 (should (= (python-indent-calculate-indentation) 8))
469 (python-tests-look-at "'name': 'first'},")
470 (should (eq (car (python-indent-context)) :inside-paren))
471 (should (= (python-indent-calculate-indentation) 9))
472 (python-tests-look-at "{'pk': 2,")
473 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
474 (should (= (python-indent-calculate-indentation) 8))
475 (python-tests-look-at "'name': 'second'}")
476 (should (eq (car (python-indent-context)) :inside-paren))
477 (should (= (python-indent-calculate-indentation) 9))
478 (python-tests-look-at "]")
479 (should (eq (car (python-indent-context))
480 :inside-paren-at-closing-nested-paren))
481 (should (= (python-indent-calculate-indentation) 4))
482 (python-tests-look-at "}}")
483 (should (eq (car (python-indent-context))
484 :inside-paren-at-closing-nested-paren))
485 (should (= (python-indent-calculate-indentation) 0))
486 (python-tests-look-at "}")
487 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
488 (should (= (python-indent-calculate-indentation) 0))))
490 (ert-deftest python-indent-inside-paren-3 ()
491 "The simplest case possible."
492 (python-tests-with-temp-buffer
494 data = ('these',
495 'are',
496 'the',
497 'tokens')
499 (python-tests-look-at "data = ('these',")
500 (should (eq (car (python-indent-context)) :no-indent))
501 (should (= (python-indent-calculate-indentation) 0))
502 (forward-line 1)
503 (should (eq (car (python-indent-context)) :inside-paren))
504 (should (= (python-indent-calculate-indentation) 8))
505 (forward-line 1)
506 (should (eq (car (python-indent-context)) :inside-paren))
507 (should (= (python-indent-calculate-indentation) 8))
508 (forward-line 1)
509 (should (eq (car (python-indent-context)) :inside-paren))
510 (should (= (python-indent-calculate-indentation) 8))))
512 (ert-deftest python-indent-inside-paren-4 ()
513 "Respect indentation of first column."
514 (python-tests-with-temp-buffer
516 data = [ [ 'these', 'are'],
517 ['the', 'tokens' ] ]
519 (python-tests-look-at "data = [ [ 'these', 'are'],")
520 (should (eq (car (python-indent-context)) :no-indent))
521 (should (= (python-indent-calculate-indentation) 0))
522 (forward-line 1)
523 (should (eq (car (python-indent-context)) :inside-paren))
524 (should (= (python-indent-calculate-indentation) 9))))
526 (ert-deftest python-indent-inside-paren-5 ()
527 "Test when :inside-paren initial parens are skipped in context start."
528 (python-tests-with-temp-buffer
530 while ((not some_condition) and
531 another_condition):
532 do_something_interesting(
533 with_some_arg)
535 (python-tests-look-at "while ((not some_condition) and")
536 (should (eq (car (python-indent-context)) :no-indent))
537 (should (= (python-indent-calculate-indentation) 0))
538 (forward-line 1)
539 (should (eq (car (python-indent-context)) :inside-paren))
540 (should (= (python-indent-calculate-indentation) 7))
541 (forward-line 1)
542 (should (eq (car (python-indent-context)) :after-block-start))
543 (should (= (python-indent-calculate-indentation) 4))
544 (forward-line 1)
545 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
546 (should (= (python-indent-calculate-indentation) 8))))
548 (ert-deftest python-indent-inside-paren-6 ()
549 "This should be aligned.."
550 (python-tests-with-temp-buffer
552 CHOICES = (('some', 'choice'),
553 ('another', 'choice'),
554 ('more', 'choices'))
556 (python-tests-look-at "CHOICES = (('some', 'choice'),")
557 (should (eq (car (python-indent-context)) :no-indent))
558 (should (= (python-indent-calculate-indentation) 0))
559 (forward-line 1)
560 (should (eq (car (python-indent-context)) :inside-paren))
561 (should (= (python-indent-calculate-indentation) 11))
562 (forward-line 1)
563 (should (eq (car (python-indent-context)) :inside-paren))
564 (should (= (python-indent-calculate-indentation) 11))))
566 (ert-deftest python-indent-inside-paren-7 ()
567 "Test for Bug#21762."
568 (python-tests-with-temp-buffer
569 "import re as myre\nvar = [\n"
570 (goto-char (point-max))
571 ;; This signals an error if the test fails
572 (should (eq (car (python-indent-context)) :inside-paren-newline-start))))
574 (ert-deftest python-indent-after-block-1 ()
575 "The most simple after-block case that shouldn't fail."
576 (python-tests-with-temp-buffer
578 def foo(a, b, c=True):
580 (should (eq (car (python-indent-context)) :no-indent))
581 (should (= (python-indent-calculate-indentation) 0))
582 (goto-char (point-max))
583 (should (eq (car (python-indent-context)) :after-block-start))
584 (should (= (python-indent-calculate-indentation) 4))))
586 (ert-deftest python-indent-after-block-2 ()
587 "A weird (malformed) multiline block statement."
588 (python-tests-with-temp-buffer
590 def foo(a, b, c={
591 'a':
594 (goto-char (point-max))
595 (should (eq (car (python-indent-context)) :after-block-start))
596 (should (= (python-indent-calculate-indentation) 4))))
598 (ert-deftest python-indent-after-block-3 ()
599 "A weird (malformed) sample, usually found in python shells."
600 (python-tests-with-temp-buffer
602 In [1]:
603 def func():
604 pass
606 In [2]:
607 something
609 (python-tests-look-at "pass")
610 (should (eq (car (python-indent-context)) :after-block-start))
611 (should (= (python-indent-calculate-indentation) 4))
612 (python-tests-look-at "something")
613 (end-of-line)
614 (should (eq (car (python-indent-context)) :after-line))
615 (should (= (python-indent-calculate-indentation) 0))))
617 (ert-deftest python-indent-after-async-block-1 ()
618 "Test PEP492 async def."
619 (python-tests-with-temp-buffer
621 async def foo(a, b, c=True):
623 (should (eq (car (python-indent-context)) :no-indent))
624 (should (= (python-indent-calculate-indentation) 0))
625 (goto-char (point-max))
626 (should (eq (car (python-indent-context)) :after-block-start))
627 (should (= (python-indent-calculate-indentation) 4))))
629 (ert-deftest python-indent-after-async-block-2 ()
630 "Test PEP492 async with."
631 (python-tests-with-temp-buffer
633 async with foo(a) as mgr:
635 (should (eq (car (python-indent-context)) :no-indent))
636 (should (= (python-indent-calculate-indentation) 0))
637 (goto-char (point-max))
638 (should (eq (car (python-indent-context)) :after-block-start))
639 (should (= (python-indent-calculate-indentation) 4))))
641 (ert-deftest python-indent-after-async-block-3 ()
642 "Test PEP492 async for."
643 (python-tests-with-temp-buffer
645 async for a in sequencer():
647 (should (eq (car (python-indent-context)) :no-indent))
648 (should (= (python-indent-calculate-indentation) 0))
649 (goto-char (point-max))
650 (should (eq (car (python-indent-context)) :after-block-start))
651 (should (= (python-indent-calculate-indentation) 4))))
653 (ert-deftest python-indent-after-backslash-1 ()
654 "The most common case."
655 (python-tests-with-temp-buffer
657 from foo.bar.baz import something, something_1 \\\\
658 something_2 something_3, \\\\
659 something_4, something_5
661 (python-tests-look-at "from foo.bar.baz import something, something_1")
662 (should (eq (car (python-indent-context)) :no-indent))
663 (should (= (python-indent-calculate-indentation) 0))
664 (python-tests-look-at "something_2 something_3,")
665 (should (eq (car (python-indent-context)) :after-backslash-first-line))
666 (should (= (python-indent-calculate-indentation) 4))
667 (python-tests-look-at "something_4, something_5")
668 (should (eq (car (python-indent-context)) :after-backslash))
669 (should (= (python-indent-calculate-indentation) 4))
670 (goto-char (point-max))
671 (should (eq (car (python-indent-context)) :after-line))
672 (should (= (python-indent-calculate-indentation) 0))))
674 (ert-deftest python-indent-after-backslash-2 ()
675 "A pretty extreme complicated case."
676 (python-tests-with-temp-buffer
678 objects = Thing.objects.all() \\\\
679 .filter(
680 type='toy',
681 status='bought'
682 ) \\\\
683 .aggregate(
684 Sum('amount')
685 ) \\\\
686 .values_list()
688 (python-tests-look-at "objects = Thing.objects.all()")
689 (should (eq (car (python-indent-context)) :no-indent))
690 (should (= (python-indent-calculate-indentation) 0))
691 (python-tests-look-at ".filter(")
692 (should (eq (car (python-indent-context))
693 :after-backslash-dotted-continuation))
694 (should (= (python-indent-calculate-indentation) 23))
695 (python-tests-look-at "type='toy',")
696 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
697 (should (= (python-indent-calculate-indentation) 27))
698 (python-tests-look-at "status='bought'")
699 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
700 (should (= (python-indent-calculate-indentation) 27))
701 (python-tests-look-at ") \\\\")
702 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
703 (should (= (python-indent-calculate-indentation) 23))
704 (python-tests-look-at ".aggregate(")
705 (should (eq (car (python-indent-context))
706 :after-backslash-dotted-continuation))
707 (should (= (python-indent-calculate-indentation) 23))
708 (python-tests-look-at "Sum('amount')")
709 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
710 (should (= (python-indent-calculate-indentation) 27))
711 (python-tests-look-at ") \\\\")
712 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
713 (should (= (python-indent-calculate-indentation) 23))
714 (python-tests-look-at ".values_list()")
715 (should (eq (car (python-indent-context))
716 :after-backslash-dotted-continuation))
717 (should (= (python-indent-calculate-indentation) 23))
718 (forward-line 1)
719 (should (eq (car (python-indent-context)) :after-line))
720 (should (= (python-indent-calculate-indentation) 0))))
722 (ert-deftest python-indent-after-backslash-3 ()
723 "Backslash continuation from block start."
724 (python-tests-with-temp-buffer
726 with open('/path/to/some/file/you/want/to/read') as file_1, \\\\
727 open('/path/to/some/file/being/written', 'w') as file_2:
728 file_2.write(file_1.read())
730 (python-tests-look-at
731 "with open('/path/to/some/file/you/want/to/read') as file_1, \\\\")
732 (should (eq (car (python-indent-context)) :no-indent))
733 (should (= (python-indent-calculate-indentation) 0))
734 (python-tests-look-at
735 "open('/path/to/some/file/being/written', 'w') as file_2")
736 (should (eq (car (python-indent-context))
737 :after-backslash-block-continuation))
738 (should (= (python-indent-calculate-indentation) 5))
739 (python-tests-look-at "file_2.write(file_1.read())")
740 (should (eq (car (python-indent-context)) :after-block-start))
741 (should (= (python-indent-calculate-indentation) 4))))
743 (ert-deftest python-indent-after-backslash-4 ()
744 "Backslash continuation from assignment."
745 (python-tests-with-temp-buffer
747 super_awful_assignment = some_calculation() and \\\\
748 another_calculation() and \\\\
749 some_final_calculation()
751 (python-tests-look-at
752 "super_awful_assignment = some_calculation() and \\\\")
753 (should (eq (car (python-indent-context)) :no-indent))
754 (should (= (python-indent-calculate-indentation) 0))
755 (python-tests-look-at "another_calculation() and \\\\")
756 (should (eq (car (python-indent-context))
757 :after-backslash-assignment-continuation))
758 (should (= (python-indent-calculate-indentation) 25))
759 (python-tests-look-at "some_final_calculation()")
760 (should (eq (car (python-indent-context)) :after-backslash))
761 (should (= (python-indent-calculate-indentation) 25))))
763 (ert-deftest python-indent-after-backslash-5 ()
764 "Dotted continuation bizarre example."
765 (python-tests-with-temp-buffer
767 def delete_all_things():
768 Thing \\\\
769 .objects.all() \\\\
770 .delete()
772 (python-tests-look-at "Thing \\\\")
773 (should (eq (car (python-indent-context)) :after-block-start))
774 (should (= (python-indent-calculate-indentation) 4))
775 (python-tests-look-at ".objects.all() \\\\")
776 (should (eq (car (python-indent-context)) :after-backslash-first-line))
777 (should (= (python-indent-calculate-indentation) 8))
778 (python-tests-look-at ".delete()")
779 (should (eq (car (python-indent-context))
780 :after-backslash-dotted-continuation))
781 (should (= (python-indent-calculate-indentation) 16))))
783 (ert-deftest python-indent-block-enders-1 ()
784 "Test de-indentation for pass keyword."
785 (python-tests-with-temp-buffer
787 Class foo(object):
789 def bar(self):
790 if self.baz:
791 return (1,
795 else:
796 pass
798 (python-tests-look-at "3)")
799 (forward-line 1)
800 (should (= (python-indent-calculate-indentation) 8))
801 (python-tests-look-at "pass")
802 (forward-line 1)
803 (should (eq (car (python-indent-context)) :after-block-end))
804 (should (= (python-indent-calculate-indentation) 8))))
806 (ert-deftest python-indent-block-enders-2 ()
807 "Test de-indentation for return keyword."
808 (python-tests-with-temp-buffer
810 Class foo(object):
811 '''raise lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
813 eiusmod tempor incididunt ut labore et dolore magna aliqua.
815 def bar(self):
816 \"return (1, 2, 3).\"
817 if self.baz:
818 return (1,
822 (python-tests-look-at "def")
823 (should (= (python-indent-calculate-indentation) 4))
824 (python-tests-look-at "if")
825 (should (= (python-indent-calculate-indentation) 8))
826 (python-tests-look-at "return")
827 (should (= (python-indent-calculate-indentation) 12))
828 (goto-char (point-max))
829 (should (eq (car (python-indent-context)) :after-block-end))
830 (should (= (python-indent-calculate-indentation) 8))))
832 (ert-deftest python-indent-block-enders-3 ()
833 "Test de-indentation for continue keyword."
834 (python-tests-with-temp-buffer
836 for element in lst:
837 if element is None:
838 continue
840 (python-tests-look-at "if")
841 (should (= (python-indent-calculate-indentation) 4))
842 (python-tests-look-at "continue")
843 (should (= (python-indent-calculate-indentation) 8))
844 (forward-line 1)
845 (should (eq (car (python-indent-context)) :after-block-end))
846 (should (= (python-indent-calculate-indentation) 4))))
848 (ert-deftest python-indent-block-enders-4 ()
849 "Test de-indentation for break keyword."
850 (python-tests-with-temp-buffer
852 for element in lst:
853 if element is None:
854 break
856 (python-tests-look-at "if")
857 (should (= (python-indent-calculate-indentation) 4))
858 (python-tests-look-at "break")
859 (should (= (python-indent-calculate-indentation) 8))
860 (forward-line 1)
861 (should (eq (car (python-indent-context)) :after-block-end))
862 (should (= (python-indent-calculate-indentation) 4))))
864 (ert-deftest python-indent-block-enders-5 ()
865 "Test de-indentation for raise keyword."
866 (python-tests-with-temp-buffer
868 for element in lst:
869 if element is None:
870 raise ValueError('Element cannot be None')
872 (python-tests-look-at "if")
873 (should (= (python-indent-calculate-indentation) 4))
874 (python-tests-look-at "raise")
875 (should (= (python-indent-calculate-indentation) 8))
876 (forward-line 1)
877 (should (eq (car (python-indent-context)) :after-block-end))
878 (should (= (python-indent-calculate-indentation) 4))))
880 (ert-deftest python-indent-dedenters-1 ()
881 "Test de-indentation for the elif keyword."
882 (python-tests-with-temp-buffer
884 if save:
885 try:
886 write_to_disk(data)
887 finally:
888 cleanup()
889 elif
891 (python-tests-look-at "elif\n")
892 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
893 (should (= (python-indent-calculate-indentation) 0))
894 (should (= (python-indent-calculate-indentation t) 0))))
896 (ert-deftest python-indent-dedenters-2 ()
897 "Test de-indentation for the else keyword."
898 (python-tests-with-temp-buffer
900 if save:
901 try:
902 write_to_disk(data)
903 except IOError:
904 msg = 'Error saving to disk'
905 message(msg)
906 logger.exception(msg)
907 except Exception:
908 if hide_details:
909 logger.exception('Unhandled exception')
910 else
911 finally:
912 data.free()
914 (python-tests-look-at "else\n")
915 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
916 (should (= (python-indent-calculate-indentation) 8))
917 (python-indent-line t)
918 (should (= (python-indent-calculate-indentation t) 4))
919 (python-indent-line t)
920 (should (= (python-indent-calculate-indentation t) 0))
921 (python-indent-line t)
922 (should (= (python-indent-calculate-indentation t) 8))))
924 (ert-deftest python-indent-dedenters-3 ()
925 "Test de-indentation for the except keyword."
926 (python-tests-with-temp-buffer
928 if save:
929 try:
930 write_to_disk(data)
931 except
933 (python-tests-look-at "except\n")
934 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
935 (should (= (python-indent-calculate-indentation) 4))
936 (python-indent-line t)
937 (should (= (python-indent-calculate-indentation t) 4))))
939 (ert-deftest python-indent-dedenters-4 ()
940 "Test de-indentation for the finally keyword."
941 (python-tests-with-temp-buffer
943 if save:
944 try:
945 write_to_disk(data)
946 finally
948 (python-tests-look-at "finally\n")
949 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
950 (should (= (python-indent-calculate-indentation) 4))
951 (python-indent-line t)
952 (should (= (python-indent-calculate-indentation) 4))))
954 (ert-deftest python-indent-dedenters-5 ()
955 "Test invalid levels are skipped in a complex example."
956 (python-tests-with-temp-buffer
958 if save:
959 try:
960 write_to_disk(data)
961 except IOError:
962 msg = 'Error saving to disk'
963 message(msg)
964 logger.exception(msg)
965 finally:
966 if cleanup:
967 do_cleanup()
968 else
970 (python-tests-look-at "else\n")
971 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
972 (should (= (python-indent-calculate-indentation) 8))
973 (should (= (python-indent-calculate-indentation t) 0))
974 (python-indent-line t)
975 (should (= (python-indent-calculate-indentation t) 8))))
977 (ert-deftest python-indent-dedenters-6 ()
978 "Test indentation is zero when no opening block for dedenter."
979 (python-tests-with-temp-buffer
981 try:
982 # if save:
983 write_to_disk(data)
984 else
986 (python-tests-look-at "else\n")
987 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
988 (should (= (python-indent-calculate-indentation) 0))
989 (should (= (python-indent-calculate-indentation t) 0))))
991 (ert-deftest python-indent-dedenters-7 ()
992 "Test indentation case from Bug#15163."
993 (python-tests-with-temp-buffer
995 if a:
996 if b:
997 pass
998 else:
999 pass
1000 else:
1002 (python-tests-look-at "else:" 2)
1003 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
1004 (should (= (python-indent-calculate-indentation) 0))
1005 (should (= (python-indent-calculate-indentation t) 0))))
1007 (ert-deftest python-indent-dedenters-8 ()
1008 "Test indentation for Bug#18432."
1009 (python-tests-with-temp-buffer
1011 if (a == 1 or
1012 a == 2):
1013 pass
1014 elif (a == 3 or
1015 a == 4):
1017 (python-tests-look-at "elif (a == 3 or")
1018 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
1019 (should (= (python-indent-calculate-indentation) 0))
1020 (should (= (python-indent-calculate-indentation t) 0))
1021 (python-tests-look-at "a == 4):\n")
1022 (should (eq (car (python-indent-context)) :inside-paren))
1023 (should (= (python-indent-calculate-indentation) 6))
1024 (python-indent-line)
1025 (should (= (python-indent-calculate-indentation t) 4))
1026 (python-indent-line t)
1027 (should (= (python-indent-calculate-indentation t) 0))
1028 (python-indent-line t)
1029 (should (= (python-indent-calculate-indentation t) 6))))
1031 (ert-deftest python-indent-inside-string-1 ()
1032 "Test indentation for strings."
1033 (python-tests-with-temp-buffer
1035 multiline = '''
1036 bunch
1038 lines
1041 (python-tests-look-at "multiline = '''")
1042 (should (eq (car (python-indent-context)) :no-indent))
1043 (should (= (python-indent-calculate-indentation) 0))
1044 (python-tests-look-at "bunch")
1045 (should (eq (car (python-indent-context)) :inside-string))
1046 (should (= (python-indent-calculate-indentation) 0))
1047 (python-tests-look-at "of")
1048 (should (eq (car (python-indent-context)) :inside-string))
1049 (should (= (python-indent-calculate-indentation) 0))
1050 (python-tests-look-at "lines")
1051 (should (eq (car (python-indent-context)) :inside-string))
1052 (should (= (python-indent-calculate-indentation) 0))
1053 (python-tests-look-at "'''")
1054 (should (eq (car (python-indent-context)) :inside-string))
1055 (should (= (python-indent-calculate-indentation) 0))))
1057 (ert-deftest python-indent-inside-string-2 ()
1058 "Test indentation for docstrings."
1059 (python-tests-with-temp-buffer
1061 def fn(a, b, c=True):
1062 '''docstring
1063 bunch
1065 lines
1068 (python-tests-look-at "'''docstring")
1069 (should (eq (car (python-indent-context)) :after-block-start))
1070 (should (= (python-indent-calculate-indentation) 4))
1071 (python-tests-look-at "bunch")
1072 (should (eq (car (python-indent-context)) :inside-docstring))
1073 (should (= (python-indent-calculate-indentation) 4))
1074 (python-tests-look-at "of")
1075 (should (eq (car (python-indent-context)) :inside-docstring))
1076 ;; Any indentation deeper than the base-indent must remain unmodified.
1077 (should (= (python-indent-calculate-indentation) 8))
1078 (python-tests-look-at "lines")
1079 (should (eq (car (python-indent-context)) :inside-docstring))
1080 (should (= (python-indent-calculate-indentation) 4))
1081 (python-tests-look-at "'''")
1082 (should (eq (car (python-indent-context)) :inside-docstring))
1083 (should (= (python-indent-calculate-indentation) 4))))
1085 (ert-deftest python-indent-inside-string-3 ()
1086 "Test indentation for nested strings."
1087 (python-tests-with-temp-buffer
1089 def fn(a, b, c=True):
1090 some_var = '''
1091 bunch
1093 lines
1096 (python-tests-look-at "some_var = '''")
1097 (should (eq (car (python-indent-context)) :after-block-start))
1098 (should (= (python-indent-calculate-indentation) 4))
1099 (python-tests-look-at "bunch")
1100 (should (eq (car (python-indent-context)) :inside-string))
1101 (should (= (python-indent-calculate-indentation) 4))
1102 (python-tests-look-at "of")
1103 (should (eq (car (python-indent-context)) :inside-string))
1104 (should (= (python-indent-calculate-indentation) 4))
1105 (python-tests-look-at "lines")
1106 (should (eq (car (python-indent-context)) :inside-string))
1107 (should (= (python-indent-calculate-indentation) 4))
1108 (python-tests-look-at "'''")
1109 (should (eq (car (python-indent-context)) :inside-string))
1110 (should (= (python-indent-calculate-indentation) 4))))
1112 (ert-deftest python-indent-electric-colon-1 ()
1113 "Test indentation case from Bug#18228."
1114 (python-tests-with-temp-buffer
1116 def a():
1117 pass
1119 def b()
1121 (python-tests-look-at "def b()")
1122 (goto-char (line-end-position))
1123 (python-tests-self-insert ":")
1124 (should (= (current-indentation) 0))))
1126 (ert-deftest python-indent-electric-colon-2 ()
1127 "Test indentation case for dedenter."
1128 (python-tests-with-temp-buffer
1130 if do:
1131 something()
1132 else
1134 (python-tests-look-at "else")
1135 (goto-char (line-end-position))
1136 (python-tests-self-insert ":")
1137 (should (= (current-indentation) 0))))
1139 (ert-deftest python-indent-electric-colon-3 ()
1140 "Test indentation case for multi-line dedenter."
1141 (python-tests-with-temp-buffer
1143 if do:
1144 something()
1145 elif (this
1147 that)
1149 (python-tests-look-at "that)")
1150 (goto-char (line-end-position))
1151 (python-tests-self-insert ":")
1152 (python-tests-look-at "elif" -1)
1153 (should (= (current-indentation) 0))
1154 (python-tests-look-at "and")
1155 (should (= (current-indentation) 6))
1156 (python-tests-look-at "that)")
1157 (should (= (current-indentation) 6))))
1159 (ert-deftest python-indent-region-1 ()
1160 "Test indentation case from Bug#18843."
1161 (let ((contents "
1162 def foo ():
1163 try:
1164 pass
1165 except:
1166 pass
1168 (python-tests-with-temp-buffer
1169 contents
1170 (python-indent-region (point-min) (point-max))
1171 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1172 contents)))))
1174 (ert-deftest python-indent-region-2 ()
1175 "Test region indentation on comments."
1176 (let ((contents "
1177 def f():
1178 if True:
1179 pass
1181 # This is
1182 # some multiline
1183 # comment
1185 (python-tests-with-temp-buffer
1186 contents
1187 (python-indent-region (point-min) (point-max))
1188 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1189 contents)))))
1191 (ert-deftest python-indent-region-3 ()
1192 "Test region indentation on comments."
1193 (let ((contents "
1194 def f():
1195 if True:
1196 pass
1197 # This is
1198 # some multiline
1199 # comment
1201 (expected "
1202 def f():
1203 if True:
1204 pass
1205 # This is
1206 # some multiline
1207 # comment
1209 (python-tests-with-temp-buffer
1210 contents
1211 (python-indent-region (point-min) (point-max))
1212 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1213 expected)))))
1215 (ert-deftest python-indent-region-4 ()
1216 "Test region indentation block starts, dedenters and enders."
1217 (let ((contents "
1218 def f():
1219 if True:
1220 a = 5
1221 else:
1222 a = 10
1223 return a
1225 (expected "
1226 def f():
1227 if True:
1228 a = 5
1229 else:
1230 a = 10
1231 return a
1233 (python-tests-with-temp-buffer
1234 contents
1235 (python-indent-region (point-min) (point-max))
1236 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1237 expected)))))
1239 (ert-deftest python-indent-region-5 ()
1240 "Test region indentation for docstrings."
1241 (let ((contents "
1242 def f():
1244 this is
1245 a multiline
1246 string
1248 x = \\
1250 this is an arbitrarily
1251 indented multiline
1252 string
1255 (expected "
1256 def f():
1258 this is
1259 a multiline
1260 string
1262 x = \\
1264 this is an arbitrarily
1265 indented multiline
1266 string
1269 (python-tests-with-temp-buffer
1270 contents
1271 (python-indent-region (point-min) (point-max))
1272 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1273 expected)))))
1276 ;;; Mark
1278 (ert-deftest python-mark-defun-1 ()
1279 """Test `python-mark-defun' with point at defun symbol start."""
1280 (python-tests-with-temp-buffer
1282 def foo(x):
1283 return x
1285 class A:
1286 pass
1288 class B:
1290 def __init__(self):
1291 self.b = 'b'
1293 def fun(self):
1294 return self.b
1296 class C:
1297 '''docstring'''
1299 (let ((expected-mark-beginning-position
1300 (progn
1301 (python-tests-look-at "class A:")
1302 (1- (point))))
1303 (expected-mark-end-position-1
1304 (save-excursion
1305 (python-tests-look-at "pass")
1306 (forward-line)
1307 (point)))
1308 (expected-mark-end-position-2
1309 (save-excursion
1310 (python-tests-look-at "return self.b")
1311 (forward-line)
1312 (point)))
1313 (expected-mark-end-position-3
1314 (save-excursion
1315 (python-tests-look-at "'''docstring'''")
1316 (forward-line)
1317 (point))))
1318 ;; Select class A only, with point at bol.
1319 (python-mark-defun 1)
1320 (should (= (point) expected-mark-beginning-position))
1321 (should (= (marker-position (mark-marker))
1322 expected-mark-end-position-1))
1323 ;; expand to class B, start position should remain the same.
1324 (python-mark-defun 1)
1325 (should (= (point) expected-mark-beginning-position))
1326 (should (= (marker-position (mark-marker))
1327 expected-mark-end-position-2))
1328 ;; expand to class C, start position should remain the same.
1329 (python-mark-defun 1)
1330 (should (= (point) expected-mark-beginning-position))
1331 (should (= (marker-position (mark-marker))
1332 expected-mark-end-position-3)))))
1334 (ert-deftest python-mark-defun-2 ()
1335 """Test `python-mark-defun' with point at nested defun symbol start."""
1336 (python-tests-with-temp-buffer
1338 def foo(x):
1339 return x
1341 class A:
1342 pass
1344 class B:
1346 def __init__(self):
1347 self.b = 'b'
1349 def fun(self):
1350 return self.b
1352 class C:
1353 '''docstring'''
1355 (let ((expected-mark-beginning-position
1356 (progn
1357 (python-tests-look-at "def __init__(self):")
1358 (1- (line-beginning-position))))
1359 (expected-mark-end-position-1
1360 (save-excursion
1361 (python-tests-look-at "self.b = 'b'")
1362 (forward-line)
1363 (point)))
1364 (expected-mark-end-position-2
1365 (save-excursion
1366 (python-tests-look-at "return self.b")
1367 (forward-line)
1368 (point)))
1369 (expected-mark-end-position-3
1370 (save-excursion
1371 (python-tests-look-at "'''docstring'''")
1372 (forward-line)
1373 (point))))
1374 ;; Select B.__init only, with point at its start.
1375 (python-mark-defun 1)
1376 (should (= (point) expected-mark-beginning-position))
1377 (should (= (marker-position (mark-marker))
1378 expected-mark-end-position-1))
1379 ;; expand to B.fun, start position should remain the same.
1380 (python-mark-defun 1)
1381 (should (= (point) expected-mark-beginning-position))
1382 (should (= (marker-position (mark-marker))
1383 expected-mark-end-position-2))
1384 ;; expand to class C, start position should remain the same.
1385 (python-mark-defun 1)
1386 (should (= (point) expected-mark-beginning-position))
1387 (should (= (marker-position (mark-marker))
1388 expected-mark-end-position-3)))))
1390 (ert-deftest python-mark-defun-3 ()
1391 """Test `python-mark-defun' with point inside defun symbol."""
1392 (python-tests-with-temp-buffer
1394 def foo(x):
1395 return x
1397 class A:
1398 pass
1400 class B:
1402 def __init__(self):
1403 self.b = 'b'
1405 def fun(self):
1406 return self.b
1408 class C:
1409 '''docstring'''
1411 (let ((expected-mark-beginning-position
1412 (progn
1413 (python-tests-look-at "def fun(self):")
1414 (python-tests-look-at "(self):")
1415 (1- (line-beginning-position))))
1416 (expected-mark-end-position
1417 (save-excursion
1418 (python-tests-look-at "return self.b")
1419 (forward-line)
1420 (point))))
1421 ;; Should select B.fun, despite point is inside the defun symbol.
1422 (python-mark-defun 1)
1423 (should (= (point) expected-mark-beginning-position))
1424 (should (= (marker-position (mark-marker))
1425 expected-mark-end-position)))))
1428 ;;; Navigation
1430 (ert-deftest python-nav-beginning-of-defun-1 ()
1431 (python-tests-with-temp-buffer
1433 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1434 '''print decorated function call data to stdout.
1436 Usage:
1438 @decoratorFunctionWithArguments('arg1', 'arg2')
1439 def func(a, b, c=True):
1440 pass
1443 def wwrap(f):
1444 print 'Inside wwrap()'
1445 def wrapped_f(*args):
1446 print 'Inside wrapped_f()'
1447 print 'Decorator arguments:', arg1, arg2, arg3
1448 f(*args)
1449 print 'After f(*args)'
1450 return wrapped_f
1451 return wwrap
1453 (python-tests-look-at "return wrap")
1454 (should (= (save-excursion
1455 (python-nav-beginning-of-defun)
1456 (point))
1457 (save-excursion
1458 (python-tests-look-at "def wrapped_f(*args):" -1)
1459 (beginning-of-line)
1460 (point))))
1461 (python-tests-look-at "def wrapped_f(*args):" -1)
1462 (should (= (save-excursion
1463 (python-nav-beginning-of-defun)
1464 (point))
1465 (save-excursion
1466 (python-tests-look-at "def wwrap(f):" -1)
1467 (beginning-of-line)
1468 (point))))
1469 (python-tests-look-at "def wwrap(f):" -1)
1470 (should (= (save-excursion
1471 (python-nav-beginning-of-defun)
1472 (point))
1473 (save-excursion
1474 (python-tests-look-at "def decoratorFunctionWithArguments" -1)
1475 (beginning-of-line)
1476 (point))))))
1478 (ert-deftest python-nav-beginning-of-defun-2 ()
1479 (python-tests-with-temp-buffer
1481 class C(object):
1483 def m(self):
1484 self.c()
1486 def b():
1487 pass
1489 def a():
1490 pass
1492 def c(self):
1493 pass
1495 ;; Nested defuns, are handled with care.
1496 (python-tests-look-at "def c(self):")
1497 (should (= (save-excursion
1498 (python-nav-beginning-of-defun)
1499 (point))
1500 (save-excursion
1501 (python-tests-look-at "def m(self):" -1)
1502 (beginning-of-line)
1503 (point))))
1504 ;; Defuns on same levels should be respected.
1505 (python-tests-look-at "def a():" -1)
1506 (should (= (save-excursion
1507 (python-nav-beginning-of-defun)
1508 (point))
1509 (save-excursion
1510 (python-tests-look-at "def b():" -1)
1511 (beginning-of-line)
1512 (point))))
1513 ;; Jump to a top level defun.
1514 (python-tests-look-at "def b():" -1)
1515 (should (= (save-excursion
1516 (python-nav-beginning-of-defun)
1517 (point))
1518 (save-excursion
1519 (python-tests-look-at "def m(self):" -1)
1520 (beginning-of-line)
1521 (point))))
1522 ;; Jump to a top level defun again.
1523 (python-tests-look-at "def m(self):" -1)
1524 (should (= (save-excursion
1525 (python-nav-beginning-of-defun)
1526 (point))
1527 (save-excursion
1528 (python-tests-look-at "class C(object):" -1)
1529 (beginning-of-line)
1530 (point))))))
1532 (ert-deftest python-nav-beginning-of-defun-3 ()
1533 (python-tests-with-temp-buffer
1535 class C(object):
1537 async def m(self):
1538 return await self.c()
1540 async def c(self):
1541 pass
1543 (python-tests-look-at "self.c()")
1544 (should (= (save-excursion
1545 (python-nav-beginning-of-defun)
1546 (point))
1547 (save-excursion
1548 (python-tests-look-at "async def m" -1)
1549 (beginning-of-line)
1550 (point))))))
1552 (ert-deftest python-nav-end-of-defun-1 ()
1553 (python-tests-with-temp-buffer
1555 class C(object):
1557 def m(self):
1558 self.c()
1560 def b():
1561 pass
1563 def a():
1564 pass
1566 def c(self):
1567 pass
1569 (should (= (save-excursion
1570 (python-tests-look-at "class C(object):")
1571 (python-nav-end-of-defun)
1572 (point))
1573 (save-excursion
1574 (point-max))))
1575 (should (= (save-excursion
1576 (python-tests-look-at "def m(self):")
1577 (python-nav-end-of-defun)
1578 (point))
1579 (save-excursion
1580 (python-tests-look-at "def c(self):")
1581 (forward-line -1)
1582 (point))))
1583 (should (= (save-excursion
1584 (python-tests-look-at "def b():")
1585 (python-nav-end-of-defun)
1586 (point))
1587 (save-excursion
1588 (python-tests-look-at "def b():")
1589 (forward-line 2)
1590 (point))))
1591 (should (= (save-excursion
1592 (python-tests-look-at "def c(self):")
1593 (python-nav-end-of-defun)
1594 (point))
1595 (save-excursion
1596 (point-max))))))
1598 (ert-deftest python-nav-end-of-defun-2 ()
1599 (python-tests-with-temp-buffer
1601 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1602 '''print decorated function call data to stdout.
1604 Usage:
1606 @decoratorFunctionWithArguments('arg1', 'arg2')
1607 def func(a, b, c=True):
1608 pass
1611 def wwrap(f):
1612 print 'Inside wwrap()'
1613 def wrapped_f(*args):
1614 print 'Inside wrapped_f()'
1615 print 'Decorator arguments:', arg1, arg2, arg3
1616 f(*args)
1617 print 'After f(*args)'
1618 return wrapped_f
1619 return wwrap
1621 (should (= (save-excursion
1622 (python-tests-look-at "def decoratorFunctionWithArguments")
1623 (python-nav-end-of-defun)
1624 (point))
1625 (save-excursion
1626 (point-max))))
1627 (should (= (save-excursion
1628 (python-tests-look-at "@decoratorFunctionWithArguments")
1629 (python-nav-end-of-defun)
1630 (point))
1631 (save-excursion
1632 (point-max))))
1633 (should (= (save-excursion
1634 (python-tests-look-at "def wwrap(f):")
1635 (python-nav-end-of-defun)
1636 (point))
1637 (save-excursion
1638 (python-tests-look-at "return wwrap")
1639 (line-beginning-position))))
1640 (should (= (save-excursion
1641 (python-tests-look-at "def wrapped_f(*args):")
1642 (python-nav-end-of-defun)
1643 (point))
1644 (save-excursion
1645 (python-tests-look-at "return wrapped_f")
1646 (line-beginning-position))))
1647 (should (= (save-excursion
1648 (python-tests-look-at "f(*args)")
1649 (python-nav-end-of-defun)
1650 (point))
1651 (save-excursion
1652 (python-tests-look-at "return wrapped_f")
1653 (line-beginning-position))))))
1655 (ert-deftest python-nav-backward-defun-1 ()
1656 (python-tests-with-temp-buffer
1658 class A(object): # A
1660 def a(self): # a
1661 pass
1663 def b(self): # b
1664 pass
1666 class B(object): # B
1668 class C(object): # C
1670 def d(self): # d
1671 pass
1673 # def e(self): # e
1674 # pass
1676 def c(self): # c
1677 pass
1679 # def d(self): # d
1680 # pass
1682 (goto-char (point-max))
1683 (should (= (save-excursion (python-nav-backward-defun))
1684 (python-tests-look-at " def c(self): # c" -1)))
1685 (should (= (save-excursion (python-nav-backward-defun))
1686 (python-tests-look-at " def d(self): # d" -1)))
1687 (should (= (save-excursion (python-nav-backward-defun))
1688 (python-tests-look-at " class C(object): # C" -1)))
1689 (should (= (save-excursion (python-nav-backward-defun))
1690 (python-tests-look-at " class B(object): # B" -1)))
1691 (should (= (save-excursion (python-nav-backward-defun))
1692 (python-tests-look-at " def b(self): # b" -1)))
1693 (should (= (save-excursion (python-nav-backward-defun))
1694 (python-tests-look-at " def a(self): # a" -1)))
1695 (should (= (save-excursion (python-nav-backward-defun))
1696 (python-tests-look-at "class A(object): # A" -1)))
1697 (should (not (python-nav-backward-defun)))))
1699 (ert-deftest python-nav-backward-defun-2 ()
1700 (python-tests-with-temp-buffer
1702 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1703 '''print decorated function call data to stdout.
1705 Usage:
1707 @decoratorFunctionWithArguments('arg1', 'arg2')
1708 def func(a, b, c=True):
1709 pass
1712 def wwrap(f):
1713 print 'Inside wwrap()'
1714 def wrapped_f(*args):
1715 print 'Inside wrapped_f()'
1716 print 'Decorator arguments:', arg1, arg2, arg3
1717 f(*args)
1718 print 'After f(*args)'
1719 return wrapped_f
1720 return wwrap
1722 (goto-char (point-max))
1723 (should (= (save-excursion (python-nav-backward-defun))
1724 (python-tests-look-at " def wrapped_f(*args):" -1)))
1725 (should (= (save-excursion (python-nav-backward-defun))
1726 (python-tests-look-at " def wwrap(f):" -1)))
1727 (should (= (save-excursion (python-nav-backward-defun))
1728 (python-tests-look-at "def decoratorFunctionWithArguments(arg1, arg2, arg3):" -1)))
1729 (should (not (python-nav-backward-defun)))))
1731 (ert-deftest python-nav-backward-defun-3 ()
1732 (python-tests-with-temp-buffer
1735 def u(self):
1736 pass
1738 def v(self):
1739 pass
1741 def w(self):
1742 pass
1745 class A(object):
1746 pass
1748 (goto-char (point-min))
1749 (let ((point (python-tests-look-at "class A(object):")))
1750 (should (not (python-nav-backward-defun)))
1751 (should (= point (point))))))
1753 (ert-deftest python-nav-forward-defun-1 ()
1754 (python-tests-with-temp-buffer
1756 class A(object): # A
1758 def a(self): # a
1759 pass
1761 def b(self): # b
1762 pass
1764 class B(object): # B
1766 class C(object): # C
1768 def d(self): # d
1769 pass
1771 # def e(self): # e
1772 # pass
1774 def c(self): # c
1775 pass
1777 # def d(self): # d
1778 # pass
1780 (goto-char (point-min))
1781 (should (= (save-excursion (python-nav-forward-defun))
1782 (python-tests-look-at "(object): # A")))
1783 (should (= (save-excursion (python-nav-forward-defun))
1784 (python-tests-look-at "(self): # a")))
1785 (should (= (save-excursion (python-nav-forward-defun))
1786 (python-tests-look-at "(self): # b")))
1787 (should (= (save-excursion (python-nav-forward-defun))
1788 (python-tests-look-at "(object): # B")))
1789 (should (= (save-excursion (python-nav-forward-defun))
1790 (python-tests-look-at "(object): # C")))
1791 (should (= (save-excursion (python-nav-forward-defun))
1792 (python-tests-look-at "(self): # d")))
1793 (should (= (save-excursion (python-nav-forward-defun))
1794 (python-tests-look-at "(self): # c")))
1795 (should (not (python-nav-forward-defun)))))
1797 (ert-deftest python-nav-forward-defun-2 ()
1798 (python-tests-with-temp-buffer
1800 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1801 '''print decorated function call data to stdout.
1803 Usage:
1805 @decoratorFunctionWithArguments('arg1', 'arg2')
1806 def func(a, b, c=True):
1807 pass
1810 def wwrap(f):
1811 print 'Inside wwrap()'
1812 def wrapped_f(*args):
1813 print 'Inside wrapped_f()'
1814 print 'Decorator arguments:', arg1, arg2, arg3
1815 f(*args)
1816 print 'After f(*args)'
1817 return wrapped_f
1818 return wwrap
1820 (goto-char (point-min))
1821 (should (= (save-excursion (python-nav-forward-defun))
1822 (python-tests-look-at "(arg1, arg2, arg3):")))
1823 (should (= (save-excursion (python-nav-forward-defun))
1824 (python-tests-look-at "(f):")))
1825 (should (= (save-excursion (python-nav-forward-defun))
1826 (python-tests-look-at "(*args):")))
1827 (should (not (python-nav-forward-defun)))))
1829 (ert-deftest python-nav-forward-defun-3 ()
1830 (python-tests-with-temp-buffer
1832 class A(object):
1833 pass
1836 def u(self):
1837 pass
1839 def v(self):
1840 pass
1842 def w(self):
1843 pass
1846 (goto-char (point-min))
1847 (let ((point (python-tests-look-at "(object):")))
1848 (should (not (python-nav-forward-defun)))
1849 (should (= point (point))))))
1851 (ert-deftest python-nav-beginning-of-statement-1 ()
1852 (python-tests-with-temp-buffer
1854 v1 = 123 + \
1855 456 + \
1857 v2 = (value1,
1858 value2,
1860 value3,
1861 value4)
1862 v3 = ('this is a string'
1864 'that is continued'
1865 'between lines'
1866 'within a paren',
1867 # this is a comment, yo
1868 'continue previous line')
1869 v4 = '''
1870 a very long
1871 string
1874 (python-tests-look-at "v2 =")
1875 (python-util-forward-comment -1)
1876 (should (= (save-excursion
1877 (python-nav-beginning-of-statement)
1878 (point))
1879 (python-tests-look-at "v1 =" -1 t)))
1880 (python-tests-look-at "v3 =")
1881 (python-util-forward-comment -1)
1882 (should (= (save-excursion
1883 (python-nav-beginning-of-statement)
1884 (point))
1885 (python-tests-look-at "v2 =" -1 t)))
1886 (python-tests-look-at "v4 =")
1887 (python-util-forward-comment -1)
1888 (should (= (save-excursion
1889 (python-nav-beginning-of-statement)
1890 (point))
1891 (python-tests-look-at "v3 =" -1 t)))
1892 (goto-char (point-max))
1893 (python-util-forward-comment -1)
1894 (should (= (save-excursion
1895 (python-nav-beginning-of-statement)
1896 (point))
1897 (python-tests-look-at "v4 =" -1 t)))))
1899 (ert-deftest python-nav-end-of-statement-1 ()
1900 (python-tests-with-temp-buffer
1902 v1 = 123 + \
1903 456 + \
1905 v2 = (value1,
1906 value2,
1908 value3,
1909 value4)
1910 v3 = ('this is a string'
1912 'that is continued'
1913 'between lines'
1914 'within a paren',
1915 # this is a comment, yo
1916 'continue previous line')
1917 v4 = '''
1918 a very long
1919 string
1922 (python-tests-look-at "v1 =")
1923 (should (= (save-excursion
1924 (python-nav-end-of-statement)
1925 (point))
1926 (save-excursion
1927 (python-tests-look-at "789")
1928 (line-end-position))))
1929 (python-tests-look-at "v2 =")
1930 (should (= (save-excursion
1931 (python-nav-end-of-statement)
1932 (point))
1933 (save-excursion
1934 (python-tests-look-at "value4)")
1935 (line-end-position))))
1936 (python-tests-look-at "v3 =")
1937 (should (= (save-excursion
1938 (python-nav-end-of-statement)
1939 (point))
1940 (save-excursion
1941 (python-tests-look-at
1942 "'continue previous line')")
1943 (line-end-position))))
1944 (python-tests-look-at "v4 =")
1945 (should (= (save-excursion
1946 (python-nav-end-of-statement)
1947 (point))
1948 (save-excursion
1949 (goto-char (point-max))
1950 (python-util-forward-comment -1)
1951 (point))))))
1953 (ert-deftest python-nav-forward-statement-1 ()
1954 (python-tests-with-temp-buffer
1956 v1 = 123 + \
1957 456 + \
1959 v2 = (value1,
1960 value2,
1962 value3,
1963 value4)
1964 v3 = ('this is a string'
1966 'that is continued'
1967 'between lines'
1968 'within a paren',
1969 # this is a comment, yo
1970 'continue previous line')
1971 v4 = '''
1972 a very long
1973 string
1976 (python-tests-look-at "v1 =")
1977 (should (= (save-excursion
1978 (python-nav-forward-statement)
1979 (point))
1980 (python-tests-look-at "v2 =")))
1981 (should (= (save-excursion
1982 (python-nav-forward-statement)
1983 (point))
1984 (python-tests-look-at "v3 =")))
1985 (should (= (save-excursion
1986 (python-nav-forward-statement)
1987 (point))
1988 (python-tests-look-at "v4 =")))
1989 (should (= (save-excursion
1990 (python-nav-forward-statement)
1991 (point))
1992 (point-max)))))
1994 (ert-deftest python-nav-backward-statement-1 ()
1995 (python-tests-with-temp-buffer
1997 v1 = 123 + \
1998 456 + \
2000 v2 = (value1,
2001 value2,
2003 value3,
2004 value4)
2005 v3 = ('this is a string'
2007 'that is continued'
2008 'between lines'
2009 'within a paren',
2010 # this is a comment, yo
2011 'continue previous line')
2012 v4 = '''
2013 a very long
2014 string
2017 (goto-char (point-max))
2018 (should (= (save-excursion
2019 (python-nav-backward-statement)
2020 (point))
2021 (python-tests-look-at "v4 =" -1)))
2022 (should (= (save-excursion
2023 (python-nav-backward-statement)
2024 (point))
2025 (python-tests-look-at "v3 =" -1)))
2026 (should (= (save-excursion
2027 (python-nav-backward-statement)
2028 (point))
2029 (python-tests-look-at "v2 =" -1)))
2030 (should (= (save-excursion
2031 (python-nav-backward-statement)
2032 (point))
2033 (python-tests-look-at "v1 =" -1)))))
2035 (ert-deftest python-nav-backward-statement-2 ()
2036 :expected-result :failed
2037 (python-tests-with-temp-buffer
2039 v1 = 123 + \
2040 456 + \
2042 v2 = (value1,
2043 value2,
2045 value3,
2046 value4)
2048 ;; FIXME: For some reason `python-nav-backward-statement' is moving
2049 ;; back two sentences when starting from 'value4)'.
2050 (goto-char (point-max))
2051 (python-util-forward-comment -1)
2052 (should (= (save-excursion
2053 (python-nav-backward-statement)
2054 (point))
2055 (python-tests-look-at "v2 =" -1 t)))))
2057 (ert-deftest python-nav-beginning-of-block-1 ()
2058 (python-tests-with-temp-buffer
2060 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2061 '''print decorated function call data to stdout.
2063 Usage:
2065 @decoratorFunctionWithArguments('arg1', 'arg2')
2066 def func(a, b, c=True):
2067 pass
2070 def wwrap(f):
2071 print 'Inside wwrap()'
2072 def wrapped_f(*args):
2073 print 'Inside wrapped_f()'
2074 print 'Decorator arguments:', arg1, arg2, arg3
2075 f(*args)
2076 print 'After f(*args)'
2077 return wrapped_f
2078 return wwrap
2080 (python-tests-look-at "return wwrap")
2081 (should (= (save-excursion
2082 (python-nav-beginning-of-block)
2083 (point))
2084 (python-tests-look-at "def decoratorFunctionWithArguments" -1)))
2085 (python-tests-look-at "print 'Inside wwrap()'")
2086 (should (= (save-excursion
2087 (python-nav-beginning-of-block)
2088 (point))
2089 (python-tests-look-at "def wwrap(f):" -1)))
2090 (python-tests-look-at "print 'After f(*args)'")
2091 (end-of-line)
2092 (should (= (save-excursion
2093 (python-nav-beginning-of-block)
2094 (point))
2095 (python-tests-look-at "def wrapped_f(*args):" -1)))
2096 (python-tests-look-at "return wrapped_f")
2097 (should (= (save-excursion
2098 (python-nav-beginning-of-block)
2099 (point))
2100 (python-tests-look-at "def wwrap(f):" -1)))))
2102 (ert-deftest python-nav-end-of-block-1 ()
2103 (python-tests-with-temp-buffer
2105 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2106 '''print decorated function call data to stdout.
2108 Usage:
2110 @decoratorFunctionWithArguments('arg1', 'arg2')
2111 def func(a, b, c=True):
2112 pass
2115 def wwrap(f):
2116 print 'Inside wwrap()'
2117 def wrapped_f(*args):
2118 print 'Inside wrapped_f()'
2119 print 'Decorator arguments:', arg1, arg2, arg3
2120 f(*args)
2121 print 'After f(*args)'
2122 return wrapped_f
2123 return wwrap
2125 (python-tests-look-at "def decoratorFunctionWithArguments")
2126 (should (= (save-excursion
2127 (python-nav-end-of-block)
2128 (point))
2129 (save-excursion
2130 (goto-char (point-max))
2131 (python-util-forward-comment -1)
2132 (point))))
2133 (python-tests-look-at "def wwrap(f):")
2134 (should (= (save-excursion
2135 (python-nav-end-of-block)
2136 (point))
2137 (save-excursion
2138 (python-tests-look-at "return wrapped_f")
2139 (line-end-position))))
2140 (end-of-line)
2141 (should (= (save-excursion
2142 (python-nav-end-of-block)
2143 (point))
2144 (save-excursion
2145 (python-tests-look-at "return wrapped_f")
2146 (line-end-position))))
2147 (python-tests-look-at "f(*args)")
2148 (should (= (save-excursion
2149 (python-nav-end-of-block)
2150 (point))
2151 (save-excursion
2152 (python-tests-look-at "print 'After f(*args)'")
2153 (line-end-position))))))
2155 (ert-deftest python-nav-forward-block-1 ()
2156 "This also accounts as a test for `python-nav-backward-block'."
2157 (python-tests-with-temp-buffer
2159 if request.user.is_authenticated():
2160 # def block():
2161 # pass
2162 try:
2163 profile = request.user.get_profile()
2164 except Profile.DoesNotExist:
2165 profile = Profile.objects.create(user=request.user)
2166 else:
2167 if profile.stats:
2168 profile.recalculate_stats()
2169 else:
2170 profile.clear_stats()
2171 finally:
2172 profile.views += 1
2173 profile.save()
2175 (should (= (save-excursion (python-nav-forward-block))
2176 (python-tests-look-at "if request.user.is_authenticated():")))
2177 (should (= (save-excursion (python-nav-forward-block))
2178 (python-tests-look-at "try:")))
2179 (should (= (save-excursion (python-nav-forward-block))
2180 (python-tests-look-at "except Profile.DoesNotExist:")))
2181 (should (= (save-excursion (python-nav-forward-block))
2182 (python-tests-look-at "else:")))
2183 (should (= (save-excursion (python-nav-forward-block))
2184 (python-tests-look-at "if profile.stats:")))
2185 (should (= (save-excursion (python-nav-forward-block))
2186 (python-tests-look-at "else:")))
2187 (should (= (save-excursion (python-nav-forward-block))
2188 (python-tests-look-at "finally:")))
2189 ;; When point is at the last block, leave it there and return nil
2190 (should (not (save-excursion (python-nav-forward-block))))
2191 ;; Move backwards, and even if the number of moves is less than the
2192 ;; provided argument return the point.
2193 (should (= (save-excursion (python-nav-forward-block -10))
2194 (python-tests-look-at
2195 "if request.user.is_authenticated():" -1)))))
2197 (ert-deftest python-nav-forward-sexp-1 ()
2198 (python-tests-with-temp-buffer
2204 (python-tests-look-at "a()")
2205 (python-nav-forward-sexp)
2206 (should (looking-at "$"))
2207 (should (save-excursion
2208 (beginning-of-line)
2209 (looking-at "a()")))
2210 (python-nav-forward-sexp)
2211 (should (looking-at "$"))
2212 (should (save-excursion
2213 (beginning-of-line)
2214 (looking-at "b()")))
2215 (python-nav-forward-sexp)
2216 (should (looking-at "$"))
2217 (should (save-excursion
2218 (beginning-of-line)
2219 (looking-at "c()")))
2220 ;; The default behavior when next to a paren should do what lisp
2221 ;; does and, otherwise `blink-matching-open' breaks.
2222 (python-nav-forward-sexp -1)
2223 (should (looking-at "()"))
2224 (should (save-excursion
2225 (beginning-of-line)
2226 (looking-at "c()")))
2227 (end-of-line)
2228 ;; Skipping parens should jump to `bolp'
2229 (python-nav-forward-sexp -1 nil t)
2230 (should (looking-at "c()"))
2231 (forward-line -1)
2232 (end-of-line)
2233 ;; b()
2234 (python-nav-forward-sexp -1)
2235 (should (looking-at "()"))
2236 (python-nav-forward-sexp -1)
2237 (should (looking-at "b()"))
2238 (end-of-line)
2239 (python-nav-forward-sexp -1 nil t)
2240 (should (looking-at "b()"))
2241 (forward-line -1)
2242 (end-of-line)
2243 ;; a()
2244 (python-nav-forward-sexp -1)
2245 (should (looking-at "()"))
2246 (python-nav-forward-sexp -1)
2247 (should (looking-at "a()"))
2248 (end-of-line)
2249 (python-nav-forward-sexp -1 nil t)
2250 (should (looking-at "a()"))))
2252 (ert-deftest python-nav-forward-sexp-2 ()
2253 (python-tests-with-temp-buffer
2255 def func():
2256 if True:
2257 aaa = bbb
2258 ccc = ddd
2259 eee = fff
2260 return ggg
2262 (python-tests-look-at "aa =")
2263 (python-nav-forward-sexp)
2264 (should (looking-at " = bbb"))
2265 (python-nav-forward-sexp)
2266 (should (looking-at "$"))
2267 (should (save-excursion
2268 (back-to-indentation)
2269 (looking-at "aaa = bbb")))
2270 (python-nav-forward-sexp)
2271 (should (looking-at "$"))
2272 (should (save-excursion
2273 (back-to-indentation)
2274 (looking-at "ccc = ddd")))
2275 (python-nav-forward-sexp)
2276 (should (looking-at "$"))
2277 (should (save-excursion
2278 (back-to-indentation)
2279 (looking-at "eee = fff")))
2280 (python-nav-forward-sexp)
2281 (should (looking-at "$"))
2282 (should (save-excursion
2283 (back-to-indentation)
2284 (looking-at "return ggg")))
2285 (python-nav-forward-sexp -1)
2286 (should (looking-at "def func():"))))
2288 (ert-deftest python-nav-forward-sexp-3 ()
2289 (python-tests-with-temp-buffer
2291 from some_module import some_sub_module
2292 from another_module import another_sub_module
2294 def another_statement():
2295 pass
2297 (python-tests-look-at "some_module")
2298 (python-nav-forward-sexp)
2299 (should (looking-at " import"))
2300 (python-nav-forward-sexp)
2301 (should (looking-at " some_sub_module"))
2302 (python-nav-forward-sexp)
2303 (should (looking-at "$"))
2304 (should
2305 (save-excursion
2306 (back-to-indentation)
2307 (looking-at
2308 "from some_module import some_sub_module")))
2309 (python-nav-forward-sexp)
2310 (should (looking-at "$"))
2311 (should
2312 (save-excursion
2313 (back-to-indentation)
2314 (looking-at
2315 "from another_module import another_sub_module")))
2316 (python-nav-forward-sexp)
2317 (should (looking-at "$"))
2318 (should
2319 (save-excursion
2320 (back-to-indentation)
2321 (looking-at
2322 "pass")))
2323 (python-nav-forward-sexp -1)
2324 (should (looking-at "def another_statement():"))
2325 (python-nav-forward-sexp -1)
2326 (should (looking-at "from another_module import another_sub_module"))
2327 (python-nav-forward-sexp -1)
2328 (should (looking-at "from some_module import some_sub_module"))))
2330 (ert-deftest python-nav-forward-sexp-safe-1 ()
2331 (python-tests-with-temp-buffer
2333 profile = Profile.objects.create(user=request.user)
2334 profile.notify()
2336 (python-tests-look-at "profile =")
2337 (python-nav-forward-sexp-safe 1)
2338 (should (looking-at "$"))
2339 (beginning-of-line 1)
2340 (python-tests-look-at "user=request.user")
2341 (python-nav-forward-sexp-safe -1)
2342 (should (looking-at "(user=request.user)"))
2343 (python-nav-forward-sexp-safe -4)
2344 (should (looking-at "profile ="))
2345 (python-tests-look-at "user=request.user")
2346 (python-nav-forward-sexp-safe 3)
2347 (should (looking-at ")"))
2348 (python-nav-forward-sexp-safe 1)
2349 (should (looking-at "$"))
2350 (python-nav-forward-sexp-safe 1)
2351 (should (looking-at "$"))))
2353 (ert-deftest python-nav-up-list-1 ()
2354 (python-tests-with-temp-buffer
2356 def f():
2357 if True:
2358 return [i for i in range(3)]
2360 (python-tests-look-at "3)]")
2361 (python-nav-up-list)
2362 (should (looking-at "]"))
2363 (python-nav-up-list)
2364 (should (looking-at "$"))))
2366 (ert-deftest python-nav-backward-up-list-1 ()
2367 :expected-result :failed
2368 (python-tests-with-temp-buffer
2370 def f():
2371 if True:
2372 return [i for i in range(3)]
2374 (python-tests-look-at "3)]")
2375 (python-nav-backward-up-list)
2376 (should (looking-at "(3)\\]"))
2377 (python-nav-backward-up-list)
2378 (should (looking-at
2379 "\\[i for i in range(3)\\]"))
2380 ;; FIXME: Need to move to beginning-of-statement.
2381 (python-nav-backward-up-list)
2382 (should (looking-at
2383 "return \\[i for i in range(3)\\]"))
2384 (python-nav-backward-up-list)
2385 (should (looking-at "if True:"))
2386 (python-nav-backward-up-list)
2387 (should (looking-at "def f():"))))
2389 (ert-deftest python-indent-dedent-line-backspace-1 ()
2390 "Check de-indentation on first call. Bug#18319."
2391 (python-tests-with-temp-buffer
2393 if True:
2394 x ()
2395 if False:
2397 (python-tests-look-at "if False:")
2398 (call-interactively #'python-indent-dedent-line-backspace)
2399 (should (zerop (current-indentation)))
2400 ;; XXX: This should be a call to `undo' but it's triggering errors.
2401 (insert " ")
2402 (should (= (current-indentation) 4))
2403 (call-interactively #'python-indent-dedent-line-backspace)
2404 (should (zerop (current-indentation)))))
2406 (ert-deftest python-indent-dedent-line-backspace-2 ()
2407 "Check de-indentation with tabs. Bug#19730."
2408 (let ((tab-width 8))
2409 (python-tests-with-temp-buffer
2411 if x:
2412 \tabcdefg
2414 (python-tests-look-at "abcdefg")
2415 (goto-char (line-end-position))
2416 (call-interactively #'python-indent-dedent-line-backspace)
2417 (should
2418 (string= (buffer-substring-no-properties
2419 (line-beginning-position) (line-end-position))
2420 "\tabcdef")))))
2422 (ert-deftest python-indent-dedent-line-backspace-3 ()
2423 "Paranoid check of de-indentation with tabs. Bug#19730."
2424 (let ((tab-width 8))
2425 (python-tests-with-temp-buffer
2427 if x:
2428 \tif y:
2429 \t abcdefg
2431 (python-tests-look-at "abcdefg")
2432 (goto-char (line-end-position))
2433 (call-interactively #'python-indent-dedent-line-backspace)
2434 (should
2435 (string= (buffer-substring-no-properties
2436 (line-beginning-position) (line-end-position))
2437 "\t abcdef"))
2438 (back-to-indentation)
2439 (call-interactively #'python-indent-dedent-line-backspace)
2440 (should
2441 (string= (buffer-substring-no-properties
2442 (line-beginning-position) (line-end-position))
2443 "\tabcdef"))
2444 (call-interactively #'python-indent-dedent-line-backspace)
2445 (should
2446 (string= (buffer-substring-no-properties
2447 (line-beginning-position) (line-end-position))
2448 " abcdef"))
2449 (call-interactively #'python-indent-dedent-line-backspace)
2450 (should
2451 (string= (buffer-substring-no-properties
2452 (line-beginning-position) (line-end-position))
2453 "abcdef")))))
2455 (ert-deftest python-bob-infloop-avoid ()
2456 "Test that strings at BOB don't confuse syntax analysis. Bug#24905"
2457 (python-tests-with-temp-buffer
2458 " \"\n"
2459 (goto-char (point-min))
2460 (font-lock-fontify-buffer)))
2463 ;;; Shell integration
2465 (defvar python-tests-shell-interpreter "python")
2467 (ert-deftest python-shell-get-process-name-1 ()
2468 "Check process name calculation sans `buffer-file-name'."
2469 (python-tests-with-temp-buffer
2471 (should (string= (python-shell-get-process-name nil)
2472 python-shell-buffer-name))
2473 (should (string= (python-shell-get-process-name t)
2474 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2476 (ert-deftest python-shell-get-process-name-2 ()
2477 "Check process name calculation with `buffer-file-name'."
2478 (python-tests-with-temp-file
2480 ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
2481 ;; should be respected.
2482 (should (string= (python-shell-get-process-name nil)
2483 python-shell-buffer-name))
2484 (should (string=
2485 (python-shell-get-process-name t)
2486 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2488 (ert-deftest python-shell-internal-get-process-name-1 ()
2489 "Check the internal process name is buffer-unique sans `buffer-file-name'."
2490 (python-tests-with-temp-buffer
2492 (should (string= (python-shell-internal-get-process-name)
2493 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2495 (ert-deftest python-shell-internal-get-process-name-2 ()
2496 "Check the internal process name is buffer-unique with `buffer-file-name'."
2497 (python-tests-with-temp-file
2499 (should (string= (python-shell-internal-get-process-name)
2500 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2502 (ert-deftest python-shell-calculate-command-1 ()
2503 "Check the command to execute is calculated correctly.
2504 Using `python-shell-interpreter' and
2505 `python-shell-interpreter-args'."
2506 (skip-unless (executable-find python-tests-shell-interpreter))
2507 (let ((python-shell-interpreter (executable-find
2508 python-tests-shell-interpreter))
2509 (python-shell-interpreter-args "-B"))
2510 (should (string=
2511 (format "%s %s"
2512 (shell-quote-argument python-shell-interpreter)
2513 python-shell-interpreter-args)
2514 (python-shell-calculate-command)))))
2516 (ert-deftest python-shell-calculate-pythonpath-1 ()
2517 "Test PYTHONPATH calculation."
2518 (let ((process-environment '("PYTHONPATH=/path0"))
2519 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2520 (should (string= (python-shell-calculate-pythonpath)
2521 (concat "/path1" path-separator
2522 "/path2" path-separator "/path0")))))
2524 (ert-deftest python-shell-calculate-pythonpath-2 ()
2525 "Test existing paths are moved to front."
2526 (let ((process-environment
2527 (list (concat "PYTHONPATH=/path0" path-separator "/path1")))
2528 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2529 (should (string= (python-shell-calculate-pythonpath)
2530 (concat "/path1" path-separator
2531 "/path2" path-separator "/path0")))))
2533 (ert-deftest python-shell-calculate-process-environment-1 ()
2534 "Test `python-shell-process-environment' modification."
2535 (let* ((python-shell-process-environment
2536 '("TESTVAR1=value1" "TESTVAR2=value2"))
2537 (process-environment (python-shell-calculate-process-environment)))
2538 (should (equal (getenv "TESTVAR1") "value1"))
2539 (should (equal (getenv "TESTVAR2") "value2"))))
2541 (ert-deftest python-shell-calculate-process-environment-2 ()
2542 "Test `python-shell-extra-pythonpaths' modification."
2543 (let* ((process-environment process-environment)
2544 (original-pythonpath (setenv "PYTHONPATH" "/path0"))
2545 (python-shell-extra-pythonpaths '("/path1" "/path2"))
2546 (process-environment (python-shell-calculate-process-environment)))
2547 (should (equal (getenv "PYTHONPATH")
2548 (concat "/path1" path-separator
2549 "/path2" path-separator "/path0")))))
2551 (ert-deftest python-shell-calculate-process-environment-3 ()
2552 "Test `python-shell-virtualenv-root' modification."
2553 (let* ((python-shell-virtualenv-root "/env")
2554 (process-environment
2555 (let (process-environment process-environment)
2556 (setenv "PYTHONHOME" "/home")
2557 (setenv "VIRTUAL_ENV")
2558 (python-shell-calculate-process-environment))))
2559 (should (not (getenv "PYTHONHOME")))
2560 (should (string= (getenv "VIRTUAL_ENV") "/env"))))
2562 (ert-deftest python-shell-calculate-process-environment-4 ()
2563 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is non-nil."
2564 (let* ((python-shell-unbuffered t)
2565 (process-environment
2566 (let ((process-environment process-environment))
2567 (setenv "PYTHONUNBUFFERED")
2568 (python-shell-calculate-process-environment))))
2569 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2571 (ert-deftest python-shell-calculate-process-environment-5 ()
2572 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is nil."
2573 (let* ((python-shell-unbuffered nil)
2574 (process-environment
2575 (let ((process-environment process-environment))
2576 (setenv "PYTHONUNBUFFERED")
2577 (python-shell-calculate-process-environment))))
2578 (should (not (getenv "PYTHONUNBUFFERED")))))
2580 (ert-deftest python-shell-calculate-process-environment-6 ()
2581 "Test PYTHONUNBUFFERED=1 when `python-shell-unbuffered' is nil."
2582 (let* ((python-shell-unbuffered nil)
2583 (process-environment
2584 (let ((process-environment process-environment))
2585 (setenv "PYTHONUNBUFFERED" "1")
2586 (python-shell-calculate-process-environment))))
2587 ;; User default settings must remain untouched:
2588 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2590 (ert-deftest python-shell-calculate-process-environment-7 ()
2591 "Test no side-effects on `process-environment'."
2592 (let* ((python-shell-process-environment
2593 '("TESTVAR1=value1" "TESTVAR2=value2"))
2594 (python-shell-virtualenv-root "/env")
2595 (python-shell-unbuffered t)
2596 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2597 (original-process-environment (copy-sequence process-environment)))
2598 (python-shell-calculate-process-environment)
2599 (should (equal process-environment original-process-environment))))
2601 (ert-deftest python-shell-calculate-process-environment-8 ()
2602 "Test no side-effects on `tramp-remote-process-environment'."
2603 (let* ((default-directory "/ssh::/example/dir/")
2604 (python-shell-process-environment
2605 '("TESTVAR1=value1" "TESTVAR2=value2"))
2606 (python-shell-virtualenv-root "/env")
2607 (python-shell-unbuffered t)
2608 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2609 (original-process-environment
2610 (copy-sequence tramp-remote-process-environment)))
2611 (python-shell-calculate-process-environment)
2612 (should (equal tramp-remote-process-environment original-process-environment))))
2614 (ert-deftest python-shell-calculate-exec-path-1 ()
2615 "Test `python-shell-exec-path' modification."
2616 (let* ((exec-path '("/path0"))
2617 (python-shell-exec-path '("/path1" "/path2"))
2618 (new-exec-path (python-shell-calculate-exec-path)))
2619 (should (equal new-exec-path '("/path1" "/path2" "/path0")))))
2621 (ert-deftest python-shell-calculate-exec-path-2 ()
2622 "Test `python-shell-virtualenv-root' modification."
2623 (let* ((exec-path '("/path0"))
2624 (python-shell-virtualenv-root "/env")
2625 (new-exec-path (python-shell-calculate-exec-path)))
2626 (should (equal new-exec-path
2627 (list (expand-file-name "/env/bin") "/path0")))))
2629 (ert-deftest python-shell-calculate-exec-path-3 ()
2630 "Test complete `python-shell-virtualenv-root' modification."
2631 (let* ((exec-path '("/path0"))
2632 (python-shell-exec-path '("/path1" "/path2"))
2633 (python-shell-virtualenv-root "/env")
2634 (new-exec-path (python-shell-calculate-exec-path)))
2635 (should (equal new-exec-path
2636 (list (expand-file-name "/env/bin")
2637 "/path1" "/path2" "/path0")))))
2639 (ert-deftest python-shell-calculate-exec-path-4 ()
2640 "Test complete `python-shell-virtualenv-root' with remote."
2641 (let* ((default-directory "/ssh::/example/dir/")
2642 (python-shell-remote-exec-path '("/path0"))
2643 (python-shell-exec-path '("/path1" "/path2"))
2644 (python-shell-virtualenv-root "/env")
2645 (new-exec-path (python-shell-calculate-exec-path)))
2646 (should (equal new-exec-path
2647 (list (expand-file-name "/env/bin")
2648 "/path1" "/path2" "/path0")))))
2650 (ert-deftest python-shell-calculate-exec-path-5 ()
2651 "Test no side-effects on `exec-path'."
2652 (let* ((exec-path '("/path0"))
2653 (python-shell-exec-path '("/path1" "/path2"))
2654 (python-shell-virtualenv-root "/env")
2655 (original-exec-path (copy-sequence exec-path)))
2656 (python-shell-calculate-exec-path)
2657 (should (equal exec-path original-exec-path))))
2659 (ert-deftest python-shell-calculate-exec-path-6 ()
2660 "Test no side-effects on `python-shell-remote-exec-path'."
2661 (let* ((default-directory "/ssh::/example/dir/")
2662 (python-shell-remote-exec-path '("/path0"))
2663 (python-shell-exec-path '("/path1" "/path2"))
2664 (python-shell-virtualenv-root "/env")
2665 (original-exec-path (copy-sequence python-shell-remote-exec-path)))
2666 (python-shell-calculate-exec-path)
2667 (should (equal python-shell-remote-exec-path original-exec-path))))
2669 (ert-deftest python-shell-with-environment-1 ()
2670 "Test environment with local `default-directory'."
2671 (let* ((exec-path '("/path0"))
2672 (python-shell-exec-path '("/path1" "/path2"))
2673 (original-exec-path exec-path)
2674 (python-shell-virtualenv-root "/env"))
2675 (python-shell-with-environment
2676 (should (equal exec-path
2677 (list (expand-file-name "/env/bin")
2678 "/path1" "/path2" "/path0")))
2679 (should (not (getenv "PYTHONHOME")))
2680 (should (string= (getenv "VIRTUAL_ENV") "/env")))
2681 (should (equal exec-path original-exec-path))))
2683 (ert-deftest python-shell-with-environment-2 ()
2684 "Test environment with remote `default-directory'."
2685 (let* ((default-directory "/ssh::/example/dir/")
2686 (python-shell-remote-exec-path '("/remote1" "/remote2"))
2687 (python-shell-exec-path '("/path1" "/path2"))
2688 (tramp-remote-process-environment '("EMACS=t"))
2689 (original-process-environment (copy-sequence tramp-remote-process-environment))
2690 (python-shell-virtualenv-root "/env"))
2691 (python-shell-with-environment
2692 (should (equal (python-shell-calculate-exec-path)
2693 (list (expand-file-name "/env/bin")
2694 "/path1" "/path2" "/remote1" "/remote2")))
2695 (let ((process-environment (python-shell-calculate-process-environment)))
2696 (should (not (getenv "PYTHONHOME")))
2697 (should (string= (getenv "VIRTUAL_ENV") "/env"))
2698 (should (equal tramp-remote-process-environment process-environment))))
2699 (should (equal tramp-remote-process-environment original-process-environment))))
2701 (ert-deftest python-shell-with-environment-3 ()
2702 "Test `python-shell-with-environment' is idempotent."
2703 (let* ((python-shell-extra-pythonpaths '("/example/dir/"))
2704 (python-shell-exec-path '("path1" "path2"))
2705 (python-shell-virtualenv-root "/home/user/env")
2706 (single-call
2707 (python-shell-with-environment
2708 (list exec-path process-environment)))
2709 (nested-call
2710 (python-shell-with-environment
2711 (python-shell-with-environment
2712 (list exec-path process-environment)))))
2713 (should (equal single-call nested-call))))
2715 (ert-deftest python-shell-make-comint-1 ()
2716 "Check comint creation for global shell buffer."
2717 (skip-unless (executable-find python-tests-shell-interpreter))
2718 ;; The interpreter can get killed too quickly to allow it to clean
2719 ;; up the tempfiles that the default python-shell-setup-codes create,
2720 ;; so it leaves tempfiles behind, which is a minor irritation.
2721 (let* ((python-shell-setup-codes nil)
2722 (python-shell-interpreter
2723 (executable-find python-tests-shell-interpreter))
2724 (proc-name (python-shell-get-process-name nil))
2725 (shell-buffer
2726 (python-tests-with-temp-buffer
2727 "" (python-shell-make-comint
2728 (python-shell-calculate-command) proc-name)))
2729 (process (get-buffer-process shell-buffer)))
2730 (unwind-protect
2731 (progn
2732 (set-process-query-on-exit-flag process nil)
2733 (should (process-live-p process))
2734 (with-current-buffer shell-buffer
2735 (should (eq major-mode 'inferior-python-mode))
2736 (should (string= (buffer-name) (format "*%s*" proc-name)))))
2737 (kill-buffer shell-buffer))))
2739 (ert-deftest python-shell-make-comint-2 ()
2740 "Check comint creation for internal shell buffer."
2741 (skip-unless (executable-find python-tests-shell-interpreter))
2742 (let* ((python-shell-setup-codes nil)
2743 (python-shell-interpreter
2744 (executable-find python-tests-shell-interpreter))
2745 (proc-name (python-shell-internal-get-process-name))
2746 (shell-buffer
2747 (python-tests-with-temp-buffer
2748 "" (python-shell-make-comint
2749 (python-shell-calculate-command) proc-name nil t)))
2750 (process (get-buffer-process shell-buffer)))
2751 (unwind-protect
2752 (progn
2753 (set-process-query-on-exit-flag process nil)
2754 (should (process-live-p process))
2755 (with-current-buffer shell-buffer
2756 (should (eq major-mode 'inferior-python-mode))
2757 (should (string= (buffer-name) (format " *%s*" proc-name)))))
2758 (kill-buffer shell-buffer))))
2760 (ert-deftest python-shell-make-comint-3 ()
2761 "Check comint creation with overridden python interpreter and args.
2762 The command passed to `python-shell-make-comint' as argument must
2763 locally override global values set in `python-shell-interpreter'
2764 and `python-shell-interpreter-args' in the new shell buffer."
2765 (skip-unless (executable-find python-tests-shell-interpreter))
2766 (let* ((python-shell-setup-codes nil)
2767 (python-shell-interpreter "interpreter")
2768 (python-shell-interpreter-args "--some-args")
2769 (proc-name (python-shell-get-process-name nil))
2770 (interpreter-override
2771 (concat (executable-find python-tests-shell-interpreter) " " "-i"))
2772 (shell-buffer
2773 (python-tests-with-temp-buffer
2774 "" (python-shell-make-comint interpreter-override proc-name nil)))
2775 (process (get-buffer-process shell-buffer)))
2776 (unwind-protect
2777 (progn
2778 (set-process-query-on-exit-flag process nil)
2779 (should (process-live-p process))
2780 (with-current-buffer shell-buffer
2781 (should (eq major-mode 'inferior-python-mode))
2782 (should (file-equal-p
2783 python-shell-interpreter
2784 (executable-find python-tests-shell-interpreter)))
2785 (should (string= python-shell-interpreter-args "-i"))))
2786 (kill-buffer shell-buffer))))
2788 (ert-deftest python-shell-make-comint-4 ()
2789 "Check shell calculated prompts regexps are set."
2790 (skip-unless (executable-find python-tests-shell-interpreter))
2791 (let* ((process-environment process-environment)
2792 (python-shell-setup-codes nil)
2793 (python-shell-interpreter
2794 (executable-find python-tests-shell-interpreter))
2795 (python-shell-interpreter-args "-i")
2796 (python-shell--prompt-calculated-input-regexp nil)
2797 (python-shell--prompt-calculated-output-regexp nil)
2798 (python-shell-prompt-detect-enabled t)
2799 (python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2800 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2801 (python-shell-prompt-regexp "in")
2802 (python-shell-prompt-block-regexp "block")
2803 (python-shell-prompt-pdb-regexp "pdf")
2804 (python-shell-prompt-output-regexp "output")
2805 (startup-code (concat "import sys\n"
2806 "sys.ps1 = 'py> '\n"
2807 "sys.ps2 = '..> '\n"
2808 "sys.ps3 = 'out '\n"))
2809 (startup-file (python-shell--save-temp-file startup-code))
2810 (proc-name (python-shell-get-process-name nil))
2811 (shell-buffer
2812 (progn
2813 (setenv "PYTHONSTARTUP" startup-file)
2814 (python-tests-with-temp-buffer
2815 "" (python-shell-make-comint
2816 (python-shell-calculate-command) proc-name nil))))
2817 (process (get-buffer-process shell-buffer)))
2818 (unwind-protect
2819 (progn
2820 (set-process-query-on-exit-flag process nil)
2821 (should (process-live-p process))
2822 (with-current-buffer shell-buffer
2823 (should (eq major-mode 'inferior-python-mode))
2824 (should (string=
2825 python-shell--prompt-calculated-input-regexp
2826 (concat "^\\(extralargeinputprompt\\|\\.\\.> \\|"
2827 "block\\|py> \\|pdf\\|sml\\|in\\)")))
2828 (should (string=
2829 python-shell--prompt-calculated-output-regexp
2830 "^\\(extralargeoutputprompt\\|output\\|out \\|sml\\)"))))
2831 (delete-file startup-file)
2832 (kill-buffer shell-buffer))))
2834 (ert-deftest python-shell-get-process-1 ()
2835 "Check dedicated shell process preference over global."
2836 (skip-unless (executable-find python-tests-shell-interpreter))
2837 (python-tests-with-temp-file
2839 (let* ((python-shell-setup-codes nil)
2840 (python-shell-interpreter
2841 (executable-find python-tests-shell-interpreter))
2842 (global-proc-name (python-shell-get-process-name nil))
2843 (dedicated-proc-name (python-shell-get-process-name t))
2844 (global-shell-buffer
2845 (python-shell-make-comint
2846 (python-shell-calculate-command) global-proc-name))
2847 (dedicated-shell-buffer
2848 (python-shell-make-comint
2849 (python-shell-calculate-command) dedicated-proc-name))
2850 (global-process (get-buffer-process global-shell-buffer))
2851 (dedicated-process (get-buffer-process dedicated-shell-buffer)))
2852 (unwind-protect
2853 (progn
2854 (set-process-query-on-exit-flag global-process nil)
2855 (set-process-query-on-exit-flag dedicated-process nil)
2856 ;; Prefer dedicated if global also exists.
2857 (should (equal (python-shell-get-process) dedicated-process))
2858 (kill-buffer dedicated-shell-buffer)
2859 ;; If there's only global, use it.
2860 (should (equal (python-shell-get-process) global-process))
2861 (kill-buffer global-shell-buffer)
2862 ;; No buffer available.
2863 (should (not (python-shell-get-process))))
2864 (ignore-errors (kill-buffer global-shell-buffer))
2865 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2867 (ert-deftest python-shell-internal-get-or-create-process-1 ()
2868 "Check internal shell process creation fallback."
2869 (skip-unless (executable-find python-tests-shell-interpreter))
2870 (python-tests-with-temp-file
2872 (should (not (process-live-p (python-shell-internal-get-process-name))))
2873 (let* ((python-shell-interpreter
2874 (executable-find python-tests-shell-interpreter))
2875 (internal-process-name (python-shell-internal-get-process-name))
2876 (internal-process (python-shell-internal-get-or-create-process))
2877 (internal-shell-buffer (process-buffer internal-process)))
2878 (unwind-protect
2879 (progn
2880 (set-process-query-on-exit-flag internal-process nil)
2881 (should (equal (process-name internal-process)
2882 internal-process-name))
2883 (should (equal internal-process
2884 (python-shell-internal-get-or-create-process)))
2885 ;; Assert the internal process is not a user process
2886 (should (not (python-shell-get-process)))
2887 (kill-buffer internal-shell-buffer))
2888 (ignore-errors (kill-buffer internal-shell-buffer))))))
2890 (ert-deftest python-shell-prompt-detect-1 ()
2891 "Check prompt autodetection."
2892 (skip-unless (executable-find python-tests-shell-interpreter))
2893 (let ((process-environment process-environment))
2894 ;; Ensure no startup file is enabled
2895 (setenv "PYTHONSTARTUP" "")
2896 (should python-shell-prompt-detect-enabled)
2897 (should (equal (python-shell-prompt-detect) '(">>> " "... " "")))))
2899 (ert-deftest python-shell-prompt-detect-2 ()
2900 "Check prompt autodetection with startup file. Bug#17370."
2901 (skip-unless (executable-find python-tests-shell-interpreter))
2902 (let* ((process-environment process-environment)
2903 (startup-code (concat "import sys\n"
2904 "sys.ps1 = 'py> '\n"
2905 "sys.ps2 = '..> '\n"
2906 "sys.ps3 = 'out '\n"))
2907 (startup-file (python-shell--save-temp-file startup-code)))
2908 (unwind-protect
2909 (progn
2910 ;; Ensure startup file is enabled
2911 (setenv "PYTHONSTARTUP" startup-file)
2912 (should python-shell-prompt-detect-enabled)
2913 (should (equal (python-shell-prompt-detect) '("py> " "..> " "out "))))
2914 (ignore-errors (delete-file startup-file)))))
2916 (ert-deftest python-shell-prompt-detect-3 ()
2917 "Check prompts are not autodetected when feature is disabled."
2918 (skip-unless (executable-find python-tests-shell-interpreter))
2919 (let ((process-environment process-environment)
2920 (python-shell-prompt-detect-enabled nil))
2921 ;; Ensure no startup file is enabled
2922 (should (not python-shell-prompt-detect-enabled))
2923 (should (not (python-shell-prompt-detect)))))
2925 (ert-deftest python-shell-prompt-detect-4 ()
2926 "Check warning is shown when detection fails."
2927 (skip-unless (executable-find python-tests-shell-interpreter))
2928 (let* ((process-environment process-environment)
2929 ;; Trigger failure by removing prompts in the startup file
2930 (startup-code (concat "import sys\n"
2931 "sys.ps1 = ''\n"
2932 "sys.ps2 = ''\n"
2933 "sys.ps3 = ''\n"))
2934 (startup-file (python-shell--save-temp-file startup-code)))
2935 (unwind-protect
2936 (progn
2937 (kill-buffer (get-buffer-create "*Warnings*"))
2938 (should (not (get-buffer "*Warnings*")))
2939 (setenv "PYTHONSTARTUP" startup-file)
2940 (should python-shell-prompt-detect-failure-warning)
2941 (should python-shell-prompt-detect-enabled)
2942 (should (not (python-shell-prompt-detect)))
2943 (should (get-buffer "*Warnings*")))
2944 (ignore-errors (delete-file startup-file)))))
2946 (ert-deftest python-shell-prompt-detect-5 ()
2947 "Check disabled warnings are not shown when detection fails."
2948 (skip-unless (executable-find python-tests-shell-interpreter))
2949 (let* ((process-environment process-environment)
2950 (startup-code (concat "import sys\n"
2951 "sys.ps1 = ''\n"
2952 "sys.ps2 = ''\n"
2953 "sys.ps3 = ''\n"))
2954 (startup-file (python-shell--save-temp-file startup-code))
2955 (python-shell-prompt-detect-failure-warning nil))
2956 (unwind-protect
2957 (progn
2958 (kill-buffer (get-buffer-create "*Warnings*"))
2959 (should (not (get-buffer "*Warnings*")))
2960 (setenv "PYTHONSTARTUP" startup-file)
2961 (should (not python-shell-prompt-detect-failure-warning))
2962 (should python-shell-prompt-detect-enabled)
2963 (should (not (python-shell-prompt-detect)))
2964 (should (not (get-buffer "*Warnings*"))))
2965 (ignore-errors (delete-file startup-file)))))
2967 (ert-deftest python-shell-prompt-detect-6 ()
2968 "Warnings are not shown when detection is disabled."
2969 (skip-unless (executable-find python-tests-shell-interpreter))
2970 (let* ((process-environment process-environment)
2971 (startup-code (concat "import sys\n"
2972 "sys.ps1 = ''\n"
2973 "sys.ps2 = ''\n"
2974 "sys.ps3 = ''\n"))
2975 (startup-file (python-shell--save-temp-file startup-code))
2976 (python-shell-prompt-detect-failure-warning t)
2977 (python-shell-prompt-detect-enabled nil))
2978 (unwind-protect
2979 (progn
2980 (kill-buffer (get-buffer-create "*Warnings*"))
2981 (should (not (get-buffer "*Warnings*")))
2982 (setenv "PYTHONSTARTUP" startup-file)
2983 (should python-shell-prompt-detect-failure-warning)
2984 (should (not python-shell-prompt-detect-enabled))
2985 (should (not (python-shell-prompt-detect)))
2986 (should (not (get-buffer "*Warnings*"))))
2987 (ignore-errors (delete-file startup-file)))))
2989 (ert-deftest python-shell-prompt-validate-regexps-1 ()
2990 "Check `python-shell-prompt-input-regexps' are validated."
2991 (let* ((python-shell-prompt-input-regexps '("\\("))
2992 (error-data (should-error (python-shell-prompt-validate-regexps)
2993 :type 'user-error)))
2994 (should
2995 (string= (cadr error-data)
2996 (format-message
2997 "Invalid regexp \\( in `python-shell-prompt-input-regexps'")))))
2999 (ert-deftest python-shell-prompt-validate-regexps-2 ()
3000 "Check `python-shell-prompt-output-regexps' are validated."
3001 (let* ((python-shell-prompt-output-regexps '("\\("))
3002 (error-data (should-error (python-shell-prompt-validate-regexps)
3003 :type 'user-error)))
3004 (should
3005 (string= (cadr error-data)
3006 (format-message
3007 "Invalid regexp \\( in `python-shell-prompt-output-regexps'")))))
3009 (ert-deftest python-shell-prompt-validate-regexps-3 ()
3010 "Check `python-shell-prompt-regexp' is validated."
3011 (let* ((python-shell-prompt-regexp "\\(")
3012 (error-data (should-error (python-shell-prompt-validate-regexps)
3013 :type 'user-error)))
3014 (should
3015 (string= (cadr error-data)
3016 (format-message
3017 "Invalid regexp \\( in `python-shell-prompt-regexp'")))))
3019 (ert-deftest python-shell-prompt-validate-regexps-4 ()
3020 "Check `python-shell-prompt-block-regexp' is validated."
3021 (let* ((python-shell-prompt-block-regexp "\\(")
3022 (error-data (should-error (python-shell-prompt-validate-regexps)
3023 :type 'user-error)))
3024 (should
3025 (string= (cadr error-data)
3026 (format-message
3027 "Invalid regexp \\( in `python-shell-prompt-block-regexp'")))))
3029 (ert-deftest python-shell-prompt-validate-regexps-5 ()
3030 "Check `python-shell-prompt-pdb-regexp' is validated."
3031 (let* ((python-shell-prompt-pdb-regexp "\\(")
3032 (error-data (should-error (python-shell-prompt-validate-regexps)
3033 :type 'user-error)))
3034 (should
3035 (string= (cadr error-data)
3036 (format-message
3037 "Invalid regexp \\( in `python-shell-prompt-pdb-regexp'")))))
3039 (ert-deftest python-shell-prompt-validate-regexps-6 ()
3040 "Check `python-shell-prompt-output-regexp' is validated."
3041 (let* ((python-shell-prompt-output-regexp "\\(")
3042 (error-data (should-error (python-shell-prompt-validate-regexps)
3043 :type 'user-error)))
3044 (should
3045 (string= (cadr error-data)
3046 (format-message
3047 "Invalid regexp \\( in `python-shell-prompt-output-regexp'")))))
3049 (ert-deftest python-shell-prompt-validate-regexps-7 ()
3050 "Check default regexps are valid."
3051 ;; should not signal error
3052 (python-shell-prompt-validate-regexps))
3054 (ert-deftest python-shell-prompt-set-calculated-regexps-1 ()
3055 "Check regexps are validated."
3056 (let* ((python-shell-prompt-output-regexp '("\\("))
3057 (python-shell--prompt-calculated-input-regexp nil)
3058 (python-shell--prompt-calculated-output-regexp nil)
3059 (python-shell-prompt-detect-enabled nil)
3060 (error-data (should-error (python-shell-prompt-set-calculated-regexps)
3061 :type 'user-error)))
3062 (should
3063 (string= (cadr error-data)
3064 (format-message
3065 "Invalid regexp \\( in `python-shell-prompt-output-regexp'")))))
3067 (ert-deftest python-shell-prompt-set-calculated-regexps-2 ()
3068 "Check `python-shell-prompt-input-regexps' are set."
3069 (let* ((python-shell-prompt-input-regexps '("my" "prompt"))
3070 (python-shell-prompt-output-regexps '(""))
3071 (python-shell-prompt-regexp "")
3072 (python-shell-prompt-block-regexp "")
3073 (python-shell-prompt-pdb-regexp "")
3074 (python-shell-prompt-output-regexp "")
3075 (python-shell--prompt-calculated-input-regexp nil)
3076 (python-shell--prompt-calculated-output-regexp nil)
3077 (python-shell-prompt-detect-enabled nil))
3078 (python-shell-prompt-set-calculated-regexps)
3079 (should (string= python-shell--prompt-calculated-input-regexp
3080 "^\\(prompt\\|my\\|\\)"))))
3082 (ert-deftest python-shell-prompt-set-calculated-regexps-3 ()
3083 "Check `python-shell-prompt-output-regexps' are set."
3084 (let* ((python-shell-prompt-input-regexps '(""))
3085 (python-shell-prompt-output-regexps '("my" "prompt"))
3086 (python-shell-prompt-regexp "")
3087 (python-shell-prompt-block-regexp "")
3088 (python-shell-prompt-pdb-regexp "")
3089 (python-shell-prompt-output-regexp "")
3090 (python-shell--prompt-calculated-input-regexp nil)
3091 (python-shell--prompt-calculated-output-regexp nil)
3092 (python-shell-prompt-detect-enabled nil))
3093 (python-shell-prompt-set-calculated-regexps)
3094 (should (string= python-shell--prompt-calculated-output-regexp
3095 "^\\(prompt\\|my\\|\\)"))))
3097 (ert-deftest python-shell-prompt-set-calculated-regexps-4 ()
3098 "Check user defined prompts are set."
3099 (let* ((python-shell-prompt-input-regexps '(""))
3100 (python-shell-prompt-output-regexps '(""))
3101 (python-shell-prompt-regexp "prompt")
3102 (python-shell-prompt-block-regexp "block")
3103 (python-shell-prompt-pdb-regexp "pdb")
3104 (python-shell-prompt-output-regexp "output")
3105 (python-shell--prompt-calculated-input-regexp nil)
3106 (python-shell--prompt-calculated-output-regexp nil)
3107 (python-shell-prompt-detect-enabled nil))
3108 (python-shell-prompt-set-calculated-regexps)
3109 (should (string= python-shell--prompt-calculated-input-regexp
3110 "^\\(prompt\\|block\\|pdb\\|\\)"))
3111 (should (string= python-shell--prompt-calculated-output-regexp
3112 "^\\(output\\|\\)"))))
3114 (ert-deftest python-shell-prompt-set-calculated-regexps-5 ()
3115 "Check order of regexps (larger first)."
3116 (let* ((python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
3117 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
3118 (python-shell-prompt-regexp "in")
3119 (python-shell-prompt-block-regexp "block")
3120 (python-shell-prompt-pdb-regexp "pdf")
3121 (python-shell-prompt-output-regexp "output")
3122 (python-shell--prompt-calculated-input-regexp nil)
3123 (python-shell--prompt-calculated-output-regexp nil)
3124 (python-shell-prompt-detect-enabled nil))
3125 (python-shell-prompt-set-calculated-regexps)
3126 (should (string= python-shell--prompt-calculated-input-regexp
3127 "^\\(extralargeinputprompt\\|block\\|pdf\\|sml\\|in\\)"))
3128 (should (string= python-shell--prompt-calculated-output-regexp
3129 "^\\(extralargeoutputprompt\\|output\\|sml\\)"))))
3131 (ert-deftest python-shell-prompt-set-calculated-regexps-6 ()
3132 "Check detected prompts are included `regexp-quote'd."
3133 (skip-unless (executable-find python-tests-shell-interpreter))
3134 (let* ((python-shell-prompt-input-regexps '(""))
3135 (python-shell-prompt-output-regexps '(""))
3136 (python-shell-prompt-regexp "")
3137 (python-shell-prompt-block-regexp "")
3138 (python-shell-prompt-pdb-regexp "")
3139 (python-shell-prompt-output-regexp "")
3140 (python-shell--prompt-calculated-input-regexp nil)
3141 (python-shell--prompt-calculated-output-regexp nil)
3142 (python-shell-prompt-detect-enabled t)
3143 (process-environment process-environment)
3144 (startup-code (concat "import sys\n"
3145 "sys.ps1 = 'p.> '\n"
3146 "sys.ps2 = '..> '\n"
3147 "sys.ps3 = 'o.t '\n"))
3148 (startup-file (python-shell--save-temp-file startup-code)))
3149 (unwind-protect
3150 (progn
3151 (setenv "PYTHONSTARTUP" startup-file)
3152 (python-shell-prompt-set-calculated-regexps)
3153 (should (string= python-shell--prompt-calculated-input-regexp
3154 "^\\(\\.\\.> \\|p\\.> \\|\\)"))
3155 (should (string= python-shell--prompt-calculated-output-regexp
3156 "^\\(o\\.t \\|\\)")))
3157 (ignore-errors (delete-file startup-file)))))
3159 (ert-deftest python-shell-buffer-substring-1 ()
3160 "Selecting a substring of the whole buffer must match its contents."
3161 (python-tests-with-temp-buffer
3163 class Foo(models.Model):
3164 pass
3167 class Bar(models.Model):
3168 pass
3170 (should (string= (buffer-string)
3171 (python-shell-buffer-substring (point-min) (point-max))))))
3173 (ert-deftest python-shell-buffer-substring-2 ()
3174 "Main block should be removed if NOMAIN is non-nil."
3175 (python-tests-with-temp-buffer
3177 class Foo(models.Model):
3178 pass
3180 class Bar(models.Model):
3181 pass
3183 if __name__ == \"__main__\":
3184 foo = Foo()
3185 print (foo)
3187 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3189 class Foo(models.Model):
3190 pass
3192 class Bar(models.Model):
3193 pass
3198 "))))
3200 (ert-deftest python-shell-buffer-substring-3 ()
3201 "Main block should be removed if NOMAIN is non-nil."
3202 (python-tests-with-temp-buffer
3204 class Foo(models.Model):
3205 pass
3207 if __name__ == \"__main__\":
3208 foo = Foo()
3209 print (foo)
3211 class Bar(models.Model):
3212 pass
3214 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3216 class Foo(models.Model):
3217 pass
3223 class Bar(models.Model):
3224 pass
3225 "))))
3227 (ert-deftest python-shell-buffer-substring-4 ()
3228 "Coding cookie should be added for substrings."
3229 (python-tests-with-temp-buffer
3230 "# coding: latin-1
3232 class Foo(models.Model):
3233 pass
3235 if __name__ == \"__main__\":
3236 foo = Foo()
3237 print (foo)
3239 class Bar(models.Model):
3240 pass
3242 (should (string= (python-shell-buffer-substring
3243 (python-tests-look-at "class Foo(models.Model):")
3244 (progn (python-nav-forward-sexp) (point)))
3245 "# -*- coding: latin-1 -*-
3247 class Foo(models.Model):
3248 pass"))))
3250 (ert-deftest python-shell-buffer-substring-5 ()
3251 "The proper amount of blank lines is added for a substring."
3252 (python-tests-with-temp-buffer
3253 "# coding: latin-1
3255 class Foo(models.Model):
3256 pass
3258 if __name__ == \"__main__\":
3259 foo = Foo()
3260 print (foo)
3262 class Bar(models.Model):
3263 pass
3265 (should (string= (python-shell-buffer-substring
3266 (python-tests-look-at "class Bar(models.Model):")
3267 (progn (python-nav-forward-sexp) (point)))
3268 "# -*- coding: latin-1 -*-
3277 class Bar(models.Model):
3278 pass"))))
3280 (ert-deftest python-shell-buffer-substring-6 ()
3281 "Handle substring with coding cookie in the second line."
3282 (python-tests-with-temp-buffer
3284 # coding: latin-1
3286 class Foo(models.Model):
3287 pass
3289 if __name__ == \"__main__\":
3290 foo = Foo()
3291 print (foo)
3293 class Bar(models.Model):
3294 pass
3296 (should (string= (python-shell-buffer-substring
3297 (python-tests-look-at "# coding: latin-1")
3298 (python-tests-look-at "if __name__ == \"__main__\":"))
3299 "# -*- coding: latin-1 -*-
3302 class Foo(models.Model):
3303 pass
3305 "))))
3307 (ert-deftest python-shell-buffer-substring-7 ()
3308 "Ensure first coding cookie gets precedence."
3309 (python-tests-with-temp-buffer
3310 "# coding: utf-8
3311 # coding: latin-1
3313 class Foo(models.Model):
3314 pass
3316 if __name__ == \"__main__\":
3317 foo = Foo()
3318 print (foo)
3320 class Bar(models.Model):
3321 pass
3323 (should (string= (python-shell-buffer-substring
3324 (python-tests-look-at "# coding: latin-1")
3325 (python-tests-look-at "if __name__ == \"__main__\":"))
3326 "# -*- coding: utf-8 -*-
3329 class Foo(models.Model):
3330 pass
3332 "))))
3334 (ert-deftest python-shell-buffer-substring-8 ()
3335 "Ensure first coding cookie gets precedence when sending whole buffer."
3336 (python-tests-with-temp-buffer
3337 "# coding: utf-8
3338 # coding: latin-1
3340 class Foo(models.Model):
3341 pass
3343 (should (string= (python-shell-buffer-substring (point-min) (point-max))
3344 "# coding: utf-8
3347 class Foo(models.Model):
3348 pass
3349 "))))
3351 (ert-deftest python-shell-buffer-substring-9 ()
3352 "Check substring starting from `point-min'."
3353 (python-tests-with-temp-buffer
3354 "# coding: utf-8
3356 class Foo(models.Model):
3357 pass
3359 class Bar(models.Model):
3360 pass
3362 (should (string= (python-shell-buffer-substring
3363 (point-min)
3364 (python-tests-look-at "class Bar(models.Model):"))
3365 "# coding: utf-8
3367 class Foo(models.Model):
3368 pass
3370 "))))
3372 (ert-deftest python-shell-buffer-substring-10 ()
3373 "Check substring from partial block."
3374 (python-tests-with-temp-buffer
3376 def foo():
3377 print ('a')
3379 (should (string= (python-shell-buffer-substring
3380 (python-tests-look-at "print ('a')")
3381 (point-max))
3382 "if True:
3384 print ('a')
3385 "))))
3387 (ert-deftest python-shell-buffer-substring-11 ()
3388 "Check substring from partial block and point within indentation."
3389 (python-tests-with-temp-buffer
3391 def foo():
3392 print ('a')
3394 (should (string= (python-shell-buffer-substring
3395 (progn
3396 (python-tests-look-at "print ('a')")
3397 (backward-char 1)
3398 (point))
3399 (point-max))
3400 "if True:
3402 print ('a')
3403 "))))
3405 (ert-deftest python-shell-buffer-substring-12 ()
3406 "Check substring from partial block and point in whitespace."
3407 (python-tests-with-temp-buffer
3409 def foo():
3411 # Whitespace
3413 print ('a')
3415 (should (string= (python-shell-buffer-substring
3416 (python-tests-look-at "# Whitespace")
3417 (point-max))
3418 "if True:
3421 # Whitespace
3423 print ('a')
3424 "))))
3428 ;;; Shell completion
3430 (ert-deftest python-shell-completion-native-interpreter-disabled-p-1 ()
3431 (let* ((python-shell-completion-native-disabled-interpreters (list "pypy"))
3432 (python-shell-interpreter "/some/path/to/bin/pypy"))
3433 (should (python-shell-completion-native-interpreter-disabled-p))))
3438 ;;; PDB Track integration
3441 ;;; Symbol completion
3444 ;;; Fill paragraph
3447 ;;; Skeletons
3450 ;;; FFAP
3453 ;;; Code check
3456 ;;; Eldoc
3458 (ert-deftest python-eldoc--get-symbol-at-point-1 ()
3459 "Test paren handling."
3460 (python-tests-with-temp-buffer
3462 map(xx
3463 map(codecs.open('somefile'
3465 (python-tests-look-at "ap(xx")
3466 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3467 (goto-char (line-end-position))
3468 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3469 (python-tests-look-at "('somefile'")
3470 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3471 (goto-char (line-end-position))
3472 (should (string= (python-eldoc--get-symbol-at-point) "codecs.open"))))
3474 (ert-deftest python-eldoc--get-symbol-at-point-2 ()
3475 "Ensure self is replaced with the class name."
3476 (python-tests-with-temp-buffer
3478 class TheClass:
3480 def some_method(self, n):
3481 return n
3483 def other(self):
3484 return self.some_method(1234)
3487 (python-tests-look-at "self.some_method")
3488 (should (string= (python-eldoc--get-symbol-at-point)
3489 "TheClass.some_method"))
3490 (python-tests-look-at "1234)")
3491 (should (string= (python-eldoc--get-symbol-at-point)
3492 "TheClass.some_method"))))
3494 (ert-deftest python-eldoc--get-symbol-at-point-3 ()
3495 "Ensure symbol is found when point is at end of buffer."
3496 (python-tests-with-temp-buffer
3498 some_symbol
3501 (goto-char (point-max))
3502 (should (string= (python-eldoc--get-symbol-at-point)
3503 "some_symbol"))))
3505 (ert-deftest python-eldoc--get-symbol-at-point-4 ()
3506 "Ensure symbol is found when point is at whitespace."
3507 (python-tests-with-temp-buffer
3509 some_symbol some_other_symbol
3511 (python-tests-look-at " some_other_symbol")
3512 (should (string= (python-eldoc--get-symbol-at-point)
3513 "some_symbol"))))
3516 ;;; Imenu
3518 (ert-deftest python-imenu-create-index-1 ()
3519 (python-tests-with-temp-buffer
3521 class Foo(models.Model):
3522 pass
3525 class Bar(models.Model):
3526 pass
3529 def decorator(arg1, arg2, arg3):
3530 '''print decorated function call data to stdout.
3532 Usage:
3534 @decorator('arg1', 'arg2')
3535 def func(a, b, c=True):
3536 pass
3539 def wrap(f):
3540 print ('wrap')
3541 def wrapped_f(*args):
3542 print ('wrapped_f')
3543 print ('Decorator arguments:', arg1, arg2, arg3)
3544 f(*args)
3545 print ('called f(*args)')
3546 return wrapped_f
3547 return wrap
3550 class Baz(object):
3552 def a(self):
3553 pass
3555 def b(self):
3556 pass
3558 class Frob(object):
3560 def c(self):
3561 pass
3563 (goto-char (point-max))
3564 (should (equal
3565 (list
3566 (cons "Foo (class)" (copy-marker 2))
3567 (cons "Bar (class)" (copy-marker 38))
3568 (list
3569 "decorator (def)"
3570 (cons "*function definition*" (copy-marker 74))
3571 (list
3572 "wrap (def)"
3573 (cons "*function definition*" (copy-marker 254))
3574 (cons "wrapped_f (def)" (copy-marker 294))))
3575 (list
3576 "Baz (class)"
3577 (cons "*class definition*" (copy-marker 519))
3578 (cons "a (def)" (copy-marker 539))
3579 (cons "b (def)" (copy-marker 570))
3580 (list
3581 "Frob (class)"
3582 (cons "*class definition*" (copy-marker 601))
3583 (cons "c (def)" (copy-marker 626)))))
3584 (python-imenu-create-index)))))
3586 (ert-deftest python-imenu-create-index-2 ()
3587 (python-tests-with-temp-buffer
3589 class Foo(object):
3590 def foo(self):
3591 def foo1():
3592 pass
3594 def foobar(self):
3595 pass
3597 (goto-char (point-max))
3598 (should (equal
3599 (list
3600 (list
3601 "Foo (class)"
3602 (cons "*class definition*" (copy-marker 2))
3603 (list
3604 "foo (def)"
3605 (cons "*function definition*" (copy-marker 21))
3606 (cons "foo1 (def)" (copy-marker 40)))
3607 (cons "foobar (def)" (copy-marker 78))))
3608 (python-imenu-create-index)))))
3610 (ert-deftest python-imenu-create-index-3 ()
3611 (python-tests-with-temp-buffer
3613 class Foo(object):
3614 def foo(self):
3615 def foo1():
3616 pass
3617 def foo2():
3618 pass
3620 (goto-char (point-max))
3621 (should (equal
3622 (list
3623 (list
3624 "Foo (class)"
3625 (cons "*class definition*" (copy-marker 2))
3626 (list
3627 "foo (def)"
3628 (cons "*function definition*" (copy-marker 21))
3629 (cons "foo1 (def)" (copy-marker 40))
3630 (cons "foo2 (def)" (copy-marker 77)))))
3631 (python-imenu-create-index)))))
3633 (ert-deftest python-imenu-create-index-4 ()
3634 (python-tests-with-temp-buffer
3636 class Foo(object):
3637 class Bar(object):
3638 def __init__(self):
3639 pass
3641 def __str__(self):
3642 pass
3644 def __init__(self):
3645 pass
3647 (goto-char (point-max))
3648 (should (equal
3649 (list
3650 (list
3651 "Foo (class)"
3652 (cons "*class definition*" (copy-marker 2))
3653 (list
3654 "Bar (class)"
3655 (cons "*class definition*" (copy-marker 21))
3656 (cons "__init__ (def)" (copy-marker 44))
3657 (cons "__str__ (def)" (copy-marker 90)))
3658 (cons "__init__ (def)" (copy-marker 135))))
3659 (python-imenu-create-index)))))
3661 (ert-deftest python-imenu-create-flat-index-1 ()
3662 (python-tests-with-temp-buffer
3664 class Foo(models.Model):
3665 pass
3668 class Bar(models.Model):
3669 pass
3672 def decorator(arg1, arg2, arg3):
3673 '''print decorated function call data to stdout.
3675 Usage:
3677 @decorator('arg1', 'arg2')
3678 def func(a, b, c=True):
3679 pass
3682 def wrap(f):
3683 print ('wrap')
3684 def wrapped_f(*args):
3685 print ('wrapped_f')
3686 print ('Decorator arguments:', arg1, arg2, arg3)
3687 f(*args)
3688 print ('called f(*args)')
3689 return wrapped_f
3690 return wrap
3693 class Baz(object):
3695 def a(self):
3696 pass
3698 def b(self):
3699 pass
3701 class Frob(object):
3703 def c(self):
3704 pass
3706 (goto-char (point-max))
3707 (should (equal
3708 (list (cons "Foo" (copy-marker 2))
3709 (cons "Bar" (copy-marker 38))
3710 (cons "decorator" (copy-marker 74))
3711 (cons "decorator.wrap" (copy-marker 254))
3712 (cons "decorator.wrap.wrapped_f" (copy-marker 294))
3713 (cons "Baz" (copy-marker 519))
3714 (cons "Baz.a" (copy-marker 539))
3715 (cons "Baz.b" (copy-marker 570))
3716 (cons "Baz.Frob" (copy-marker 601))
3717 (cons "Baz.Frob.c" (copy-marker 626)))
3718 (python-imenu-create-flat-index)))))
3720 (ert-deftest python-imenu-create-flat-index-2 ()
3721 (python-tests-with-temp-buffer
3723 class Foo(object):
3724 class Bar(object):
3725 def __init__(self):
3726 pass
3728 def __str__(self):
3729 pass
3731 def __init__(self):
3732 pass
3734 (goto-char (point-max))
3735 (should (equal
3736 (list
3737 (cons "Foo" (copy-marker 2))
3738 (cons "Foo.Bar" (copy-marker 21))
3739 (cons "Foo.Bar.__init__" (copy-marker 44))
3740 (cons "Foo.Bar.__str__" (copy-marker 90))
3741 (cons "Foo.__init__" (copy-marker 135)))
3742 (python-imenu-create-flat-index)))))
3745 ;;; Misc helpers
3747 (ert-deftest python-info-current-defun-1 ()
3748 (python-tests-with-temp-buffer
3750 def foo(a, b):
3752 (forward-line 1)
3753 (should (string= "foo" (python-info-current-defun)))
3754 (should (string= "def foo" (python-info-current-defun t)))
3755 (forward-line 1)
3756 (should (not (python-info-current-defun)))
3757 (indent-for-tab-command)
3758 (should (string= "foo" (python-info-current-defun)))
3759 (should (string= "def foo" (python-info-current-defun t)))))
3761 (ert-deftest python-info-current-defun-2 ()
3762 (python-tests-with-temp-buffer
3764 class C(object):
3766 def m(self):
3767 if True:
3768 return [i for i in range(3)]
3769 else:
3770 return []
3772 def b():
3773 do_b()
3775 def a():
3776 do_a()
3778 def c(self):
3779 do_c()
3781 (forward-line 1)
3782 (should (string= "C" (python-info-current-defun)))
3783 (should (string= "class C" (python-info-current-defun t)))
3784 (python-tests-look-at "return [i for ")
3785 (should (string= "C.m" (python-info-current-defun)))
3786 (should (string= "def C.m" (python-info-current-defun t)))
3787 (python-tests-look-at "def b():")
3788 (should (string= "C.m.b" (python-info-current-defun)))
3789 (should (string= "def C.m.b" (python-info-current-defun t)))
3790 (forward-line 2)
3791 (indent-for-tab-command)
3792 (python-indent-dedent-line-backspace 1)
3793 (should (string= "C.m" (python-info-current-defun)))
3794 (should (string= "def C.m" (python-info-current-defun t)))
3795 (python-tests-look-at "def c(self):")
3796 (forward-line -1)
3797 (indent-for-tab-command)
3798 (should (string= "C.m.a" (python-info-current-defun)))
3799 (should (string= "def C.m.a" (python-info-current-defun t)))
3800 (python-indent-dedent-line-backspace 1)
3801 (should (string= "C.m" (python-info-current-defun)))
3802 (should (string= "def C.m" (python-info-current-defun t)))
3803 (python-indent-dedent-line-backspace 1)
3804 (should (string= "C" (python-info-current-defun)))
3805 (should (string= "class C" (python-info-current-defun t)))
3806 (python-tests-look-at "def c(self):")
3807 (should (string= "C.c" (python-info-current-defun)))
3808 (should (string= "def C.c" (python-info-current-defun t)))
3809 (python-tests-look-at "do_c()")
3810 (should (string= "C.c" (python-info-current-defun)))
3811 (should (string= "def C.c" (python-info-current-defun t)))))
3813 (ert-deftest python-info-current-defun-3 ()
3814 (python-tests-with-temp-buffer
3816 def decoratorFunctionWithArguments(arg1, arg2, arg3):
3817 '''print decorated function call data to stdout.
3819 Usage:
3821 @decoratorFunctionWithArguments('arg1', 'arg2')
3822 def func(a, b, c=True):
3823 pass
3826 def wwrap(f):
3827 print 'Inside wwrap()'
3828 def wrapped_f(*args):
3829 print 'Inside wrapped_f()'
3830 print 'Decorator arguments:', arg1, arg2, arg3
3831 f(*args)
3832 print 'After f(*args)'
3833 return wrapped_f
3834 return wwrap
3836 (python-tests-look-at "def wwrap(f):")
3837 (forward-line -1)
3838 (should (not (python-info-current-defun)))
3839 (indent-for-tab-command 1)
3840 (should (string= (python-info-current-defun)
3841 "decoratorFunctionWithArguments"))
3842 (should (string= (python-info-current-defun t)
3843 "def decoratorFunctionWithArguments"))
3844 (python-tests-look-at "def wrapped_f(*args):")
3845 (should (string= (python-info-current-defun)
3846 "decoratorFunctionWithArguments.wwrap.wrapped_f"))
3847 (should (string= (python-info-current-defun t)
3848 "def decoratorFunctionWithArguments.wwrap.wrapped_f"))
3849 (python-tests-look-at "return wrapped_f")
3850 (should (string= (python-info-current-defun)
3851 "decoratorFunctionWithArguments.wwrap"))
3852 (should (string= (python-info-current-defun t)
3853 "def decoratorFunctionWithArguments.wwrap"))
3854 (end-of-line 1)
3855 (python-tests-look-at "return wwrap")
3856 (should (string= (python-info-current-defun)
3857 "decoratorFunctionWithArguments"))
3858 (should (string= (python-info-current-defun t)
3859 "def decoratorFunctionWithArguments"))))
3861 (ert-deftest python-info-current-symbol-1 ()
3862 (python-tests-with-temp-buffer
3864 class C(object):
3866 def m(self):
3867 self.c()
3869 def c(self):
3870 print ('a')
3872 (python-tests-look-at "self.c()")
3873 (should (string= "self.c" (python-info-current-symbol)))
3874 (should (string= "C.c" (python-info-current-symbol t)))))
3876 (ert-deftest python-info-current-symbol-2 ()
3877 (python-tests-with-temp-buffer
3879 class C(object):
3881 class M(object):
3883 def a(self):
3884 self.c()
3886 def c(self):
3887 pass
3889 (python-tests-look-at "self.c()")
3890 (should (string= "self.c" (python-info-current-symbol)))
3891 (should (string= "C.M.c" (python-info-current-symbol t)))))
3893 (ert-deftest python-info-current-symbol-3 ()
3894 "Keywords should not be considered symbols."
3895 :expected-result :failed
3896 (python-tests-with-temp-buffer
3898 class C(object):
3899 pass
3901 ;; FIXME: keywords are not symbols.
3902 (python-tests-look-at "class C")
3903 (should (not (python-info-current-symbol)))
3904 (should (not (python-info-current-symbol t)))
3905 (python-tests-look-at "C(object)")
3906 (should (string= "C" (python-info-current-symbol)))
3907 (should (string= "class C" (python-info-current-symbol t)))))
3909 (ert-deftest python-info-statement-starts-block-p-1 ()
3910 (python-tests-with-temp-buffer
3912 def long_function_name(
3913 var_one, var_two, var_three,
3914 var_four):
3915 print (var_one)
3917 (python-tests-look-at "def long_function_name")
3918 (should (python-info-statement-starts-block-p))
3919 (python-tests-look-at "print (var_one)")
3920 (python-util-forward-comment -1)
3921 (should (python-info-statement-starts-block-p))))
3923 (ert-deftest python-info-statement-starts-block-p-2 ()
3924 (python-tests-with-temp-buffer
3926 if width == 0 and height == 0 and \\\\
3927 color == 'red' and emphasis == 'strong' or \\\\
3928 highlight > 100:
3929 raise ValueError('sorry, you lose')
3931 (python-tests-look-at "if width == 0 and")
3932 (should (python-info-statement-starts-block-p))
3933 (python-tests-look-at "raise ValueError(")
3934 (python-util-forward-comment -1)
3935 (should (python-info-statement-starts-block-p))))
3937 (ert-deftest python-info-statement-ends-block-p-1 ()
3938 (python-tests-with-temp-buffer
3940 def long_function_name(
3941 var_one, var_two, var_three,
3942 var_four):
3943 print (var_one)
3945 (python-tests-look-at "print (var_one)")
3946 (should (python-info-statement-ends-block-p))))
3948 (ert-deftest python-info-statement-ends-block-p-2 ()
3949 (python-tests-with-temp-buffer
3951 if width == 0 and height == 0 and \\\\
3952 color == 'red' and emphasis == 'strong' or \\\\
3953 highlight > 100:
3954 raise ValueError(
3955 'sorry, you lose'
3959 (python-tests-look-at "raise ValueError(")
3960 (should (python-info-statement-ends-block-p))))
3962 (ert-deftest python-info-beginning-of-statement-p-1 ()
3963 (python-tests-with-temp-buffer
3965 def long_function_name(
3966 var_one, var_two, var_three,
3967 var_four):
3968 print (var_one)
3970 (python-tests-look-at "def long_function_name")
3971 (should (python-info-beginning-of-statement-p))
3972 (forward-char 10)
3973 (should (not (python-info-beginning-of-statement-p)))
3974 (python-tests-look-at "print (var_one)")
3975 (should (python-info-beginning-of-statement-p))
3976 (goto-char (line-beginning-position))
3977 (should (not (python-info-beginning-of-statement-p)))))
3979 (ert-deftest python-info-beginning-of-statement-p-2 ()
3980 (python-tests-with-temp-buffer
3982 if width == 0 and height == 0 and \\\\
3983 color == 'red' and emphasis == 'strong' or \\\\
3984 highlight > 100:
3985 raise ValueError(
3986 'sorry, you lose'
3990 (python-tests-look-at "if width == 0 and")
3991 (should (python-info-beginning-of-statement-p))
3992 (forward-char 10)
3993 (should (not (python-info-beginning-of-statement-p)))
3994 (python-tests-look-at "raise ValueError(")
3995 (should (python-info-beginning-of-statement-p))
3996 (goto-char (line-beginning-position))
3997 (should (not (python-info-beginning-of-statement-p)))))
3999 (ert-deftest python-info-end-of-statement-p-1 ()
4000 (python-tests-with-temp-buffer
4002 def long_function_name(
4003 var_one, var_two, var_three,
4004 var_four):
4005 print (var_one)
4007 (python-tests-look-at "def long_function_name")
4008 (should (not (python-info-end-of-statement-p)))
4009 (end-of-line)
4010 (should (not (python-info-end-of-statement-p)))
4011 (python-tests-look-at "print (var_one)")
4012 (python-util-forward-comment -1)
4013 (should (python-info-end-of-statement-p))
4014 (python-tests-look-at "print (var_one)")
4015 (should (not (python-info-end-of-statement-p)))
4016 (end-of-line)
4017 (should (python-info-end-of-statement-p))))
4019 (ert-deftest python-info-end-of-statement-p-2 ()
4020 (python-tests-with-temp-buffer
4022 if width == 0 and height == 0 and \\\\
4023 color == 'red' and emphasis == 'strong' or \\\\
4024 highlight > 100:
4025 raise ValueError(
4026 'sorry, you lose'
4030 (python-tests-look-at "if width == 0 and")
4031 (should (not (python-info-end-of-statement-p)))
4032 (end-of-line)
4033 (should (not (python-info-end-of-statement-p)))
4034 (python-tests-look-at "raise ValueError(")
4035 (python-util-forward-comment -1)
4036 (should (python-info-end-of-statement-p))
4037 (python-tests-look-at "raise ValueError(")
4038 (should (not (python-info-end-of-statement-p)))
4039 (end-of-line)
4040 (should (not (python-info-end-of-statement-p)))
4041 (goto-char (point-max))
4042 (python-util-forward-comment -1)
4043 (should (python-info-end-of-statement-p))))
4045 (ert-deftest python-info-beginning-of-block-p-1 ()
4046 (python-tests-with-temp-buffer
4048 def long_function_name(
4049 var_one, var_two, var_three,
4050 var_four):
4051 print (var_one)
4053 (python-tests-look-at "def long_function_name")
4054 (should (python-info-beginning-of-block-p))
4055 (python-tests-look-at "var_one, var_two, var_three,")
4056 (should (not (python-info-beginning-of-block-p)))
4057 (python-tests-look-at "print (var_one)")
4058 (should (not (python-info-beginning-of-block-p)))))
4060 (ert-deftest python-info-beginning-of-block-p-2 ()
4061 (python-tests-with-temp-buffer
4063 if width == 0 and height == 0 and \\\\
4064 color == 'red' and emphasis == 'strong' or \\\\
4065 highlight > 100:
4066 raise ValueError(
4067 'sorry, you lose'
4071 (python-tests-look-at "if width == 0 and")
4072 (should (python-info-beginning-of-block-p))
4073 (python-tests-look-at "color == 'red' and emphasis")
4074 (should (not (python-info-beginning-of-block-p)))
4075 (python-tests-look-at "raise ValueError(")
4076 (should (not (python-info-beginning-of-block-p)))))
4078 (ert-deftest python-info-end-of-block-p-1 ()
4079 (python-tests-with-temp-buffer
4081 def long_function_name(
4082 var_one, var_two, var_three,
4083 var_four):
4084 print (var_one)
4086 (python-tests-look-at "def long_function_name")
4087 (should (not (python-info-end-of-block-p)))
4088 (python-tests-look-at "var_one, var_two, var_three,")
4089 (should (not (python-info-end-of-block-p)))
4090 (python-tests-look-at "var_four):")
4091 (end-of-line)
4092 (should (not (python-info-end-of-block-p)))
4093 (python-tests-look-at "print (var_one)")
4094 (should (not (python-info-end-of-block-p)))
4095 (end-of-line 1)
4096 (should (python-info-end-of-block-p))))
4098 (ert-deftest python-info-end-of-block-p-2 ()
4099 (python-tests-with-temp-buffer
4101 if width == 0 and height == 0 and \\\\
4102 color == 'red' and emphasis == 'strong' or \\\\
4103 highlight > 100:
4104 raise ValueError(
4105 'sorry, you lose'
4109 (python-tests-look-at "if width == 0 and")
4110 (should (not (python-info-end-of-block-p)))
4111 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4112 (should (not (python-info-end-of-block-p)))
4113 (python-tests-look-at "highlight > 100:")
4114 (end-of-line)
4115 (should (not (python-info-end-of-block-p)))
4116 (python-tests-look-at "raise ValueError(")
4117 (should (not (python-info-end-of-block-p)))
4118 (end-of-line 1)
4119 (should (not (python-info-end-of-block-p)))
4120 (goto-char (point-max))
4121 (python-util-forward-comment -1)
4122 (should (python-info-end-of-block-p))))
4124 (ert-deftest python-info-dedenter-opening-block-position-1 ()
4125 (python-tests-with-temp-buffer
4127 if request.user.is_authenticated():
4128 try:
4129 profile = request.user.get_profile()
4130 except Profile.DoesNotExist:
4131 profile = Profile.objects.create(user=request.user)
4132 else:
4133 if profile.stats:
4134 profile.recalculate_stats()
4135 else:
4136 profile.clear_stats()
4137 finally:
4138 profile.views += 1
4139 profile.save()
4141 (python-tests-look-at "try:")
4142 (should (not (python-info-dedenter-opening-block-position)))
4143 (python-tests-look-at "except Profile.DoesNotExist:")
4144 (should (= (python-tests-look-at "try:" -1 t)
4145 (python-info-dedenter-opening-block-position)))
4146 (python-tests-look-at "else:")
4147 (should (= (python-tests-look-at "except Profile.DoesNotExist:" -1 t)
4148 (python-info-dedenter-opening-block-position)))
4149 (python-tests-look-at "if profile.stats:")
4150 (should (not (python-info-dedenter-opening-block-position)))
4151 (python-tests-look-at "else:")
4152 (should (= (python-tests-look-at "if profile.stats:" -1 t)
4153 (python-info-dedenter-opening-block-position)))
4154 (python-tests-look-at "finally:")
4155 (should (= (python-tests-look-at "else:" -2 t)
4156 (python-info-dedenter-opening-block-position)))))
4158 (ert-deftest python-info-dedenter-opening-block-position-2 ()
4159 (python-tests-with-temp-buffer
4161 if request.user.is_authenticated():
4162 profile = Profile.objects.get_or_create(user=request.user)
4163 if profile.stats:
4164 profile.recalculate_stats()
4166 data = {
4167 'else': 'do it'
4169 'else'
4171 (python-tests-look-at "'else': 'do it'")
4172 (should (not (python-info-dedenter-opening-block-position)))
4173 (python-tests-look-at "'else'")
4174 (should (not (python-info-dedenter-opening-block-position)))))
4176 (ert-deftest python-info-dedenter-opening-block-position-3 ()
4177 (python-tests-with-temp-buffer
4179 if save:
4180 try:
4181 write_to_disk(data)
4182 except IOError:
4183 msg = 'Error saving to disk'
4184 message(msg)
4185 logger.exception(msg)
4186 except Exception:
4187 if hide_details:
4188 logger.exception('Unhandled exception')
4189 else
4190 finally:
4191 data.free()
4193 (python-tests-look-at "try:")
4194 (should (not (python-info-dedenter-opening-block-position)))
4196 (python-tests-look-at "except IOError:")
4197 (should (= (python-tests-look-at "try:" -1 t)
4198 (python-info-dedenter-opening-block-position)))
4200 (python-tests-look-at "except Exception:")
4201 (should (= (python-tests-look-at "except IOError:" -1 t)
4202 (python-info-dedenter-opening-block-position)))
4204 (python-tests-look-at "if hide_details:")
4205 (should (not (python-info-dedenter-opening-block-position)))
4207 ;; check indentation modifies the detected opening block
4208 (python-tests-look-at "else")
4209 (should (= (python-tests-look-at "if hide_details:" -1 t)
4210 (python-info-dedenter-opening-block-position)))
4212 (indent-line-to 8)
4213 (should (= (python-tests-look-at "if hide_details:" -1 t)
4214 (python-info-dedenter-opening-block-position)))
4216 (indent-line-to 4)
4217 (should (= (python-tests-look-at "except Exception:" -1 t)
4218 (python-info-dedenter-opening-block-position)))
4220 (indent-line-to 0)
4221 (should (= (python-tests-look-at "if save:" -1 t)
4222 (python-info-dedenter-opening-block-position)))))
4224 (ert-deftest python-info-dedenter-opening-block-positions-1 ()
4225 (python-tests-with-temp-buffer
4227 if save:
4228 try:
4229 write_to_disk(data)
4230 except IOError:
4231 msg = 'Error saving to disk'
4232 message(msg)
4233 logger.exception(msg)
4234 except Exception:
4235 if hide_details:
4236 logger.exception('Unhandled exception')
4237 else
4238 finally:
4239 data.free()
4241 (python-tests-look-at "try:")
4242 (should (not (python-info-dedenter-opening-block-positions)))
4244 (python-tests-look-at "except IOError:")
4245 (should
4246 (equal (list
4247 (python-tests-look-at "try:" -1 t))
4248 (python-info-dedenter-opening-block-positions)))
4250 (python-tests-look-at "except Exception:")
4251 (should
4252 (equal (list
4253 (python-tests-look-at "except IOError:" -1 t))
4254 (python-info-dedenter-opening-block-positions)))
4256 (python-tests-look-at "if hide_details:")
4257 (should (not (python-info-dedenter-opening-block-positions)))
4259 ;; check indentation does not modify the detected opening blocks
4260 (python-tests-look-at "else")
4261 (should
4262 (equal (list
4263 (python-tests-look-at "if hide_details:" -1 t)
4264 (python-tests-look-at "except Exception:" -1 t)
4265 (python-tests-look-at "if save:" -1 t))
4266 (python-info-dedenter-opening-block-positions)))
4268 (indent-line-to 8)
4269 (should
4270 (equal (list
4271 (python-tests-look-at "if hide_details:" -1 t)
4272 (python-tests-look-at "except Exception:" -1 t)
4273 (python-tests-look-at "if save:" -1 t))
4274 (python-info-dedenter-opening-block-positions)))
4276 (indent-line-to 4)
4277 (should
4278 (equal (list
4279 (python-tests-look-at "if hide_details:" -1 t)
4280 (python-tests-look-at "except Exception:" -1 t)
4281 (python-tests-look-at "if save:" -1 t))
4282 (python-info-dedenter-opening-block-positions)))
4284 (indent-line-to 0)
4285 (should
4286 (equal (list
4287 (python-tests-look-at "if hide_details:" -1 t)
4288 (python-tests-look-at "except Exception:" -1 t)
4289 (python-tests-look-at "if save:" -1 t))
4290 (python-info-dedenter-opening-block-positions)))))
4292 (ert-deftest python-info-dedenter-opening-block-positions-2 ()
4293 "Test detection of opening blocks for elif."
4294 (python-tests-with-temp-buffer
4296 if var:
4297 if var2:
4298 something()
4299 elif var3:
4300 something_else()
4301 elif
4303 (python-tests-look-at "elif var3:")
4304 (should
4305 (equal (list
4306 (python-tests-look-at "if var2:" -1 t)
4307 (python-tests-look-at "if var:" -1 t))
4308 (python-info-dedenter-opening-block-positions)))
4310 (python-tests-look-at "elif\n")
4311 (should
4312 (equal (list
4313 (python-tests-look-at "elif var3:" -1 t)
4314 (python-tests-look-at "if var:" -1 t))
4315 (python-info-dedenter-opening-block-positions)))))
4317 (ert-deftest python-info-dedenter-opening-block-positions-3 ()
4318 "Test detection of opening blocks for else."
4319 (python-tests-with-temp-buffer
4321 try:
4322 something()
4323 except:
4324 if var:
4325 if var2:
4326 something()
4327 elif var3:
4328 something_else()
4329 else
4331 if var4:
4332 while var5:
4333 var4.pop()
4334 else
4336 for value in var6:
4337 if value > 0:
4338 print value
4339 else
4341 (python-tests-look-at "else\n")
4342 (should
4343 (equal (list
4344 (python-tests-look-at "elif var3:" -1 t)
4345 (python-tests-look-at "if var:" -1 t)
4346 (python-tests-look-at "except:" -1 t))
4347 (python-info-dedenter-opening-block-positions)))
4349 (python-tests-look-at "else\n")
4350 (should
4351 (equal (list
4352 (python-tests-look-at "while var5:" -1 t)
4353 (python-tests-look-at "if var4:" -1 t))
4354 (python-info-dedenter-opening-block-positions)))
4356 (python-tests-look-at "else\n")
4357 (should
4358 (equal (list
4359 (python-tests-look-at "if value > 0:" -1 t)
4360 (python-tests-look-at "for value in var6:" -1 t)
4361 (python-tests-look-at "if var4:" -1 t))
4362 (python-info-dedenter-opening-block-positions)))))
4364 (ert-deftest python-info-dedenter-opening-block-positions-4 ()
4365 "Test detection of opening blocks for except."
4366 (python-tests-with-temp-buffer
4368 try:
4369 something()
4370 except ValueError:
4371 something_else()
4372 except
4374 (python-tests-look-at "except ValueError:")
4375 (should
4376 (equal (list (python-tests-look-at "try:" -1 t))
4377 (python-info-dedenter-opening-block-positions)))
4379 (python-tests-look-at "except\n")
4380 (should
4381 (equal (list (python-tests-look-at "except ValueError:" -1 t))
4382 (python-info-dedenter-opening-block-positions)))))
4384 (ert-deftest python-info-dedenter-opening-block-positions-5 ()
4385 "Test detection of opening blocks for finally."
4386 (python-tests-with-temp-buffer
4388 try:
4389 something()
4390 finally
4392 try:
4393 something_else()
4394 except:
4395 logger.exception('something went wrong')
4396 finally
4398 try:
4399 something_else_else()
4400 except Exception:
4401 logger.exception('something else went wrong')
4402 else:
4403 print ('all good')
4404 finally
4406 (python-tests-look-at "finally\n")
4407 (should
4408 (equal (list (python-tests-look-at "try:" -1 t))
4409 (python-info-dedenter-opening-block-positions)))
4411 (python-tests-look-at "finally\n")
4412 (should
4413 (equal (list (python-tests-look-at "except:" -1 t))
4414 (python-info-dedenter-opening-block-positions)))
4416 (python-tests-look-at "finally\n")
4417 (should
4418 (equal (list (python-tests-look-at "else:" -1 t))
4419 (python-info-dedenter-opening-block-positions)))))
4421 (ert-deftest python-info-dedenter-opening-block-message-1 ()
4422 "Test dedenters inside strings are ignored."
4423 (python-tests-with-temp-buffer
4424 "'''
4425 try:
4426 something()
4427 except:
4428 logger.exception('something went wrong')
4431 (python-tests-look-at "except\n")
4432 (should (not (python-info-dedenter-opening-block-message)))))
4434 (ert-deftest python-info-dedenter-opening-block-message-2 ()
4435 "Test except keyword."
4436 (python-tests-with-temp-buffer
4438 try:
4439 something()
4440 except:
4441 logger.exception('something went wrong')
4443 (python-tests-look-at "except:")
4444 (should (string=
4445 "Closes try:"
4446 (substring-no-properties
4447 (python-info-dedenter-opening-block-message))))
4448 (end-of-line)
4449 (should (string=
4450 "Closes try:"
4451 (substring-no-properties
4452 (python-info-dedenter-opening-block-message))))))
4454 (ert-deftest python-info-dedenter-opening-block-message-3 ()
4455 "Test else keyword."
4456 (python-tests-with-temp-buffer
4458 try:
4459 something()
4460 except:
4461 logger.exception('something went wrong')
4462 else:
4463 logger.debug('all good')
4465 (python-tests-look-at "else:")
4466 (should (string=
4467 "Closes except:"
4468 (substring-no-properties
4469 (python-info-dedenter-opening-block-message))))
4470 (end-of-line)
4471 (should (string=
4472 "Closes except:"
4473 (substring-no-properties
4474 (python-info-dedenter-opening-block-message))))))
4476 (ert-deftest python-info-dedenter-opening-block-message-4 ()
4477 "Test finally keyword."
4478 (python-tests-with-temp-buffer
4480 try:
4481 something()
4482 except:
4483 logger.exception('something went wrong')
4484 else:
4485 logger.debug('all good')
4486 finally:
4487 clean()
4489 (python-tests-look-at "finally:")
4490 (should (string=
4491 "Closes else:"
4492 (substring-no-properties
4493 (python-info-dedenter-opening-block-message))))
4494 (end-of-line)
4495 (should (string=
4496 "Closes else:"
4497 (substring-no-properties
4498 (python-info-dedenter-opening-block-message))))))
4500 (ert-deftest python-info-dedenter-opening-block-message-5 ()
4501 "Test elif keyword."
4502 (python-tests-with-temp-buffer
4504 if a:
4505 something()
4506 elif b:
4508 (python-tests-look-at "elif b:")
4509 (should (string=
4510 "Closes if a:"
4511 (substring-no-properties
4512 (python-info-dedenter-opening-block-message))))
4513 (end-of-line)
4514 (should (string=
4515 "Closes if a:"
4516 (substring-no-properties
4517 (python-info-dedenter-opening-block-message))))))
4520 (ert-deftest python-info-dedenter-statement-p-1 ()
4521 "Test dedenters inside strings are ignored."
4522 (python-tests-with-temp-buffer
4523 "'''
4524 try:
4525 something()
4526 except:
4527 logger.exception('something went wrong')
4530 (python-tests-look-at "except\n")
4531 (should (not (python-info-dedenter-statement-p)))))
4533 (ert-deftest python-info-dedenter-statement-p-2 ()
4534 "Test except keyword."
4535 (python-tests-with-temp-buffer
4537 try:
4538 something()
4539 except:
4540 logger.exception('something went wrong')
4542 (python-tests-look-at "except:")
4543 (should (= (point) (python-info-dedenter-statement-p)))
4544 (end-of-line)
4545 (should (= (save-excursion
4546 (back-to-indentation)
4547 (point))
4548 (python-info-dedenter-statement-p)))))
4550 (ert-deftest python-info-dedenter-statement-p-3 ()
4551 "Test else keyword."
4552 (python-tests-with-temp-buffer
4554 try:
4555 something()
4556 except:
4557 logger.exception('something went wrong')
4558 else:
4559 logger.debug('all good')
4561 (python-tests-look-at "else:")
4562 (should (= (point) (python-info-dedenter-statement-p)))
4563 (end-of-line)
4564 (should (= (save-excursion
4565 (back-to-indentation)
4566 (point))
4567 (python-info-dedenter-statement-p)))))
4569 (ert-deftest python-info-dedenter-statement-p-4 ()
4570 "Test finally keyword."
4571 (python-tests-with-temp-buffer
4573 try:
4574 something()
4575 except:
4576 logger.exception('something went wrong')
4577 else:
4578 logger.debug('all good')
4579 finally:
4580 clean()
4582 (python-tests-look-at "finally:")
4583 (should (= (point) (python-info-dedenter-statement-p)))
4584 (end-of-line)
4585 (should (= (save-excursion
4586 (back-to-indentation)
4587 (point))
4588 (python-info-dedenter-statement-p)))))
4590 (ert-deftest python-info-dedenter-statement-p-5 ()
4591 "Test elif keyword."
4592 (python-tests-with-temp-buffer
4594 if a:
4595 something()
4596 elif b:
4598 (python-tests-look-at "elif b:")
4599 (should (= (point) (python-info-dedenter-statement-p)))
4600 (end-of-line)
4601 (should (= (save-excursion
4602 (back-to-indentation)
4603 (point))
4604 (python-info-dedenter-statement-p)))))
4606 (ert-deftest python-info-line-ends-backslash-p-1 ()
4607 (python-tests-with-temp-buffer
4609 objects = Thing.objects.all() \\\\
4610 .filter(
4611 type='toy',
4612 status='bought'
4613 ) \\\\
4614 .aggregate(
4615 Sum('amount')
4616 ) \\\\
4617 .values_list()
4619 (should (python-info-line-ends-backslash-p 2)) ; .filter(...
4620 (should (python-info-line-ends-backslash-p 3))
4621 (should (python-info-line-ends-backslash-p 4))
4622 (should (python-info-line-ends-backslash-p 5))
4623 (should (python-info-line-ends-backslash-p 6)) ; ) \...
4624 (should (python-info-line-ends-backslash-p 7))
4625 (should (python-info-line-ends-backslash-p 8))
4626 (should (python-info-line-ends-backslash-p 9))
4627 (should (not (python-info-line-ends-backslash-p 10))))) ; .values_list()...
4629 (ert-deftest python-info-beginning-of-backslash-1 ()
4630 (python-tests-with-temp-buffer
4632 objects = Thing.objects.all() \\\\
4633 .filter(
4634 type='toy',
4635 status='bought'
4636 ) \\\\
4637 .aggregate(
4638 Sum('amount')
4639 ) \\\\
4640 .values_list()
4642 (let ((first 2)
4643 (second (python-tests-look-at ".filter("))
4644 (third (python-tests-look-at ".aggregate(")))
4645 (should (= first (python-info-beginning-of-backslash 2)))
4646 (should (= second (python-info-beginning-of-backslash 3)))
4647 (should (= second (python-info-beginning-of-backslash 4)))
4648 (should (= second (python-info-beginning-of-backslash 5)))
4649 (should (= second (python-info-beginning-of-backslash 6)))
4650 (should (= third (python-info-beginning-of-backslash 7)))
4651 (should (= third (python-info-beginning-of-backslash 8)))
4652 (should (= third (python-info-beginning-of-backslash 9)))
4653 (should (not (python-info-beginning-of-backslash 10))))))
4655 (ert-deftest python-info-continuation-line-p-1 ()
4656 (python-tests-with-temp-buffer
4658 if width == 0 and height == 0 and \\\\
4659 color == 'red' and emphasis == 'strong' or \\\\
4660 highlight > 100:
4661 raise ValueError(
4662 'sorry, you lose'
4666 (python-tests-look-at "if width == 0 and height == 0 and")
4667 (should (not (python-info-continuation-line-p)))
4668 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4669 (should (python-info-continuation-line-p))
4670 (python-tests-look-at "highlight > 100:")
4671 (should (python-info-continuation-line-p))
4672 (python-tests-look-at "raise ValueError(")
4673 (should (not (python-info-continuation-line-p)))
4674 (python-tests-look-at "'sorry, you lose'")
4675 (should (python-info-continuation-line-p))
4676 (forward-line 1)
4677 (should (python-info-continuation-line-p))
4678 (python-tests-look-at ")")
4679 (should (python-info-continuation-line-p))
4680 (forward-line 1)
4681 (should (not (python-info-continuation-line-p)))))
4683 (ert-deftest python-info-block-continuation-line-p-1 ()
4684 (python-tests-with-temp-buffer
4686 if width == 0 and height == 0 and \\\\
4687 color == 'red' and emphasis == 'strong' or \\\\
4688 highlight > 100:
4689 raise ValueError(
4690 'sorry, you lose'
4694 (python-tests-look-at "if width == 0 and")
4695 (should (not (python-info-block-continuation-line-p)))
4696 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4697 (should (= (python-info-block-continuation-line-p)
4698 (python-tests-look-at "if width == 0 and" -1 t)))
4699 (python-tests-look-at "highlight > 100:")
4700 (should (not (python-info-block-continuation-line-p)))))
4702 (ert-deftest python-info-block-continuation-line-p-2 ()
4703 (python-tests-with-temp-buffer
4705 def foo(a,
4708 pass
4710 (python-tests-look-at "def foo(a,")
4711 (should (not (python-info-block-continuation-line-p)))
4712 (python-tests-look-at "b,")
4713 (should (= (python-info-block-continuation-line-p)
4714 (python-tests-look-at "def foo(a," -1 t)))
4715 (python-tests-look-at "c):")
4716 (should (not (python-info-block-continuation-line-p)))))
4718 (ert-deftest python-info-assignment-statement-p-1 ()
4719 (python-tests-with-temp-buffer
4721 data = foo(), bar() \\\\
4722 baz(), 4 \\\\
4723 5, 6
4725 (python-tests-look-at "data = foo(), bar()")
4726 (should (python-info-assignment-statement-p))
4727 (should (python-info-assignment-statement-p t))
4728 (python-tests-look-at "baz(), 4")
4729 (should (python-info-assignment-statement-p))
4730 (should (not (python-info-assignment-statement-p t)))
4731 (python-tests-look-at "5, 6")
4732 (should (python-info-assignment-statement-p))
4733 (should (not (python-info-assignment-statement-p t)))))
4735 (ert-deftest python-info-assignment-statement-p-2 ()
4736 (python-tests-with-temp-buffer
4738 data = (foo(), bar()
4739 baz(), 4
4740 5, 6)
4742 (python-tests-look-at "data = (foo(), bar()")
4743 (should (python-info-assignment-statement-p))
4744 (should (python-info-assignment-statement-p t))
4745 (python-tests-look-at "baz(), 4")
4746 (should (python-info-assignment-statement-p))
4747 (should (not (python-info-assignment-statement-p t)))
4748 (python-tests-look-at "5, 6)")
4749 (should (python-info-assignment-statement-p))
4750 (should (not (python-info-assignment-statement-p t)))))
4752 (ert-deftest python-info-assignment-statement-p-3 ()
4753 (python-tests-with-temp-buffer
4755 data '=' 42
4757 (python-tests-look-at "data '=' 42")
4758 (should (not (python-info-assignment-statement-p)))
4759 (should (not (python-info-assignment-statement-p t)))))
4761 (ert-deftest python-info-assignment-continuation-line-p-1 ()
4762 (python-tests-with-temp-buffer
4764 data = foo(), bar() \\\\
4765 baz(), 4 \\\\
4766 5, 6
4768 (python-tests-look-at "data = foo(), bar()")
4769 (should (not (python-info-assignment-continuation-line-p)))
4770 (python-tests-look-at "baz(), 4")
4771 (should (= (python-info-assignment-continuation-line-p)
4772 (python-tests-look-at "foo()," -1 t)))
4773 (python-tests-look-at "5, 6")
4774 (should (not (python-info-assignment-continuation-line-p)))))
4776 (ert-deftest python-info-assignment-continuation-line-p-2 ()
4777 (python-tests-with-temp-buffer
4779 data = (foo(), bar()
4780 baz(), 4
4781 5, 6)
4783 (python-tests-look-at "data = (foo(), bar()")
4784 (should (not (python-info-assignment-continuation-line-p)))
4785 (python-tests-look-at "baz(), 4")
4786 (should (= (python-info-assignment-continuation-line-p)
4787 (python-tests-look-at "(foo()," -1 t)))
4788 (python-tests-look-at "5, 6)")
4789 (should (not (python-info-assignment-continuation-line-p)))))
4791 (ert-deftest python-info-looking-at-beginning-of-defun-1 ()
4792 (python-tests-with-temp-buffer
4794 def decorat0r(deff):
4795 '''decorates stuff.
4797 @decorat0r
4798 def foo(arg):
4801 def wrap():
4802 deff()
4803 return wwrap
4805 (python-tests-look-at "def decorat0r(deff):")
4806 (should (python-info-looking-at-beginning-of-defun))
4807 (python-tests-look-at "def foo(arg):")
4808 (should (not (python-info-looking-at-beginning-of-defun)))
4809 (python-tests-look-at "def wrap():")
4810 (should (python-info-looking-at-beginning-of-defun))
4811 (python-tests-look-at "deff()")
4812 (should (not (python-info-looking-at-beginning-of-defun)))))
4814 (ert-deftest python-info-current-line-comment-p-1 ()
4815 (python-tests-with-temp-buffer
4817 # this is a comment
4818 foo = True # another comment
4819 '#this is a string'
4820 if foo:
4821 # more comments
4822 print ('bar') # print bar
4824 (python-tests-look-at "# this is a comment")
4825 (should (python-info-current-line-comment-p))
4826 (python-tests-look-at "foo = True # another comment")
4827 (should (not (python-info-current-line-comment-p)))
4828 (python-tests-look-at "'#this is a string'")
4829 (should (not (python-info-current-line-comment-p)))
4830 (python-tests-look-at "# more comments")
4831 (should (python-info-current-line-comment-p))
4832 (python-tests-look-at "print ('bar') # print bar")
4833 (should (not (python-info-current-line-comment-p)))))
4835 (ert-deftest python-info-current-line-empty-p ()
4836 (python-tests-with-temp-buffer
4838 # this is a comment
4840 foo = True # another comment
4842 (should (python-info-current-line-empty-p))
4843 (python-tests-look-at "# this is a comment")
4844 (should (not (python-info-current-line-empty-p)))
4845 (forward-line 1)
4846 (should (python-info-current-line-empty-p))))
4848 (ert-deftest python-info-docstring-p-1 ()
4849 "Test module docstring detection."
4850 (python-tests-with-temp-buffer
4851 "# -*- coding: utf-8 -*-
4852 #!/usr/bin/python
4855 Module Docstring Django style.
4857 u'''Additional module docstring.'''
4858 '''Not a module docstring.'''
4860 (python-tests-look-at "Module Docstring Django style.")
4861 (should (python-info-docstring-p))
4862 (python-tests-look-at "u'''Additional module docstring.'''")
4863 (should (python-info-docstring-p))
4864 (python-tests-look-at "'''Not a module docstring.'''")
4865 (should (not (python-info-docstring-p)))))
4867 (ert-deftest python-info-docstring-p-2 ()
4868 "Test variable docstring detection."
4869 (python-tests-with-temp-buffer
4871 variable = 42
4872 U'''Variable docstring.'''
4873 '''Additional variable docstring.'''
4874 '''Not a variable docstring.'''
4876 (python-tests-look-at "Variable docstring.")
4877 (should (python-info-docstring-p))
4878 (python-tests-look-at "u'''Additional variable docstring.'''")
4879 (should (python-info-docstring-p))
4880 (python-tests-look-at "'''Not a variable docstring.'''")
4881 (should (not (python-info-docstring-p)))))
4883 (ert-deftest python-info-docstring-p-3 ()
4884 "Test function docstring detection."
4885 (python-tests-with-temp-buffer
4887 def func(a, b):
4888 r'''
4889 Function docstring.
4891 onetwo style.
4893 R'''Additional function docstring.'''
4894 '''Not a function docstring.'''
4895 return a + b
4897 (python-tests-look-at "Function docstring.")
4898 (should (python-info-docstring-p))
4899 (python-tests-look-at "R'''Additional function docstring.'''")
4900 (should (python-info-docstring-p))
4901 (python-tests-look-at "'''Not a function docstring.'''")
4902 (should (not (python-info-docstring-p)))))
4904 (ert-deftest python-info-docstring-p-4 ()
4905 "Test class docstring detection."
4906 (python-tests-with-temp-buffer
4908 class Class:
4909 ur'''
4910 Class docstring.
4912 symmetric style.
4914 uR'''
4915 Additional class docstring.
4917 '''Not a class docstring.'''
4918 pass
4920 (python-tests-look-at "Class docstring.")
4921 (should (python-info-docstring-p))
4922 (python-tests-look-at "uR'''") ;; Additional class docstring
4923 (should (python-info-docstring-p))
4924 (python-tests-look-at "'''Not a class docstring.'''")
4925 (should (not (python-info-docstring-p)))))
4927 (ert-deftest python-info-docstring-p-5 ()
4928 "Test class attribute docstring detection."
4929 (python-tests-with-temp-buffer
4931 class Class:
4932 attribute = 42
4933 Ur'''
4934 Class attribute docstring.
4936 pep-257 style.
4939 UR'''
4940 Additional class attribute docstring.
4942 '''Not a class attribute docstring.'''
4943 pass
4945 (python-tests-look-at "Class attribute docstring.")
4946 (should (python-info-docstring-p))
4947 (python-tests-look-at "UR'''") ;; Additional class attr docstring
4948 (should (python-info-docstring-p))
4949 (python-tests-look-at "'''Not a class attribute docstring.'''")
4950 (should (not (python-info-docstring-p)))))
4952 (ert-deftest python-info-docstring-p-6 ()
4953 "Test class method docstring detection."
4954 (python-tests-with-temp-buffer
4956 class Class:
4958 def __init__(self, a, b):
4959 self.a = a
4960 self.b = b
4962 def __call__(self):
4963 '''Method docstring.
4965 pep-257-nn style.
4967 '''Additional method docstring.'''
4968 '''Not a method docstring.'''
4969 return self.a + self.b
4971 (python-tests-look-at "Method docstring.")
4972 (should (python-info-docstring-p))
4973 (python-tests-look-at "'''Additional method docstring.'''")
4974 (should (python-info-docstring-p))
4975 (python-tests-look-at "'''Not a method docstring.'''")
4976 (should (not (python-info-docstring-p)))))
4978 (ert-deftest python-info-encoding-from-cookie-1 ()
4979 "Should detect it on first line."
4980 (python-tests-with-temp-buffer
4981 "# coding=latin-1
4983 foo = True # another comment
4985 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4987 (ert-deftest python-info-encoding-from-cookie-2 ()
4988 "Should detect it on second line."
4989 (python-tests-with-temp-buffer
4991 # coding=latin-1
4993 foo = True # another comment
4995 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4997 (ert-deftest python-info-encoding-from-cookie-3 ()
4998 "Should not be detected on third line (and following ones)."
4999 (python-tests-with-temp-buffer
5002 # coding=latin-1
5003 foo = True # another comment
5005 (should (not (python-info-encoding-from-cookie)))))
5007 (ert-deftest python-info-encoding-from-cookie-4 ()
5008 "Should detect Emacs style."
5009 (python-tests-with-temp-buffer
5010 "# -*- coding: latin-1 -*-
5012 foo = True # another comment"
5013 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5015 (ert-deftest python-info-encoding-from-cookie-5 ()
5016 "Should detect Vim style."
5017 (python-tests-with-temp-buffer
5018 "# vim: set fileencoding=latin-1 :
5020 foo = True # another comment"
5021 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5023 (ert-deftest python-info-encoding-from-cookie-6 ()
5024 "First cookie wins."
5025 (python-tests-with-temp-buffer
5026 "# -*- coding: iso-8859-1 -*-
5027 # vim: set fileencoding=latin-1 :
5029 foo = True # another comment"
5030 (should (eq (python-info-encoding-from-cookie) 'iso-8859-1))))
5032 (ert-deftest python-info-encoding-from-cookie-7 ()
5033 "First cookie wins."
5034 (python-tests-with-temp-buffer
5035 "# vim: set fileencoding=latin-1 :
5036 # -*- coding: iso-8859-1 -*-
5038 foo = True # another comment"
5039 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5041 (ert-deftest python-info-encoding-1 ()
5042 "Should return the detected encoding from cookie."
5043 (python-tests-with-temp-buffer
5044 "# vim: set fileencoding=latin-1 :
5046 foo = True # another comment"
5047 (should (eq (python-info-encoding) 'latin-1))))
5049 (ert-deftest python-info-encoding-2 ()
5050 "Should default to utf-8."
5051 (python-tests-with-temp-buffer
5052 "# No encoding for you
5054 foo = True # another comment"
5055 (should (eq (python-info-encoding) 'utf-8))))
5058 ;;; Utility functions
5060 (ert-deftest python-util-goto-line-1 ()
5061 (python-tests-with-temp-buffer
5062 (concat
5063 "# a comment
5064 # another comment
5065 def foo(a, b, c):
5066 pass" (make-string 20 ?\n))
5067 (python-util-goto-line 10)
5068 (should (= (line-number-at-pos) 10))
5069 (python-util-goto-line 20)
5070 (should (= (line-number-at-pos) 20))))
5072 (ert-deftest python-util-clone-local-variables-1 ()
5073 (let ((buffer (generate-new-buffer
5074 "python-util-clone-local-variables-1"))
5075 (varcons
5076 '((python-fill-docstring-style . django)
5077 (python-shell-interpreter . "python")
5078 (python-shell-interpreter-args . "manage.py shell")
5079 (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
5080 (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
5081 (python-shell-extra-pythonpaths "/home/user/pylib/")
5082 (python-shell-completion-setup-code
5083 . "from IPython.core.completerlib import module_completion")
5084 (python-shell-completion-string-code
5085 . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
5086 (python-shell-virtualenv-root
5087 . "/home/user/.virtualenvs/project"))))
5088 (with-current-buffer buffer
5089 (kill-all-local-variables)
5090 (dolist (ccons varcons)
5091 (set (make-local-variable (car ccons)) (cdr ccons))))
5092 (python-tests-with-temp-buffer
5094 (python-util-clone-local-variables buffer)
5095 (dolist (ccons varcons)
5096 (should
5097 (equal (symbol-value (car ccons)) (cdr ccons)))))
5098 (kill-buffer buffer)))
5100 (ert-deftest python-util-strip-string-1 ()
5101 (should (string= (python-util-strip-string "\t\r\n str") "str"))
5102 (should (string= (python-util-strip-string "str \n\r") "str"))
5103 (should (string= (python-util-strip-string "\t\r\n str \n\r ") "str"))
5104 (should
5105 (string= (python-util-strip-string "\n str \nin \tg \n\r") "str \nin \tg"))
5106 (should (string= (python-util-strip-string "\n \t \n\r ") ""))
5107 (should (string= (python-util-strip-string "") "")))
5109 (ert-deftest python-util-forward-comment-1 ()
5110 (python-tests-with-temp-buffer
5111 (concat
5112 "# a comment
5113 # another comment
5114 # bad indented comment
5115 # more comments" (make-string 9999 ?\n))
5116 (python-util-forward-comment 1)
5117 (should (= (point) (point-max)))
5118 (python-util-forward-comment -1)
5119 (should (= (point) (point-min)))))
5121 (ert-deftest python-util-valid-regexp-p-1 ()
5122 (should (python-util-valid-regexp-p ""))
5123 (should (python-util-valid-regexp-p python-shell-prompt-regexp))
5124 (should (not (python-util-valid-regexp-p "\\("))))
5127 ;;; Electricity
5129 (ert-deftest python-parens-electric-indent-1 ()
5130 (let ((eim electric-indent-mode))
5131 (unwind-protect
5132 (progn
5133 (python-tests-with-temp-buffer
5135 from django.conf.urls import patterns, include, url
5137 from django.contrib import admin
5139 from myapp import views
5142 urlpatterns = patterns('',
5143 url(r'^$', views.index
5146 (electric-indent-mode 1)
5147 (python-tests-look-at "views.index")
5148 (end-of-line)
5150 ;; Inserting commas within the same line should leave
5151 ;; indentation unchanged.
5152 (python-tests-self-insert ",")
5153 (should (= (current-indentation) 4))
5155 ;; As well as any other input happening within the same
5156 ;; set of parens.
5157 (python-tests-self-insert " name='index')")
5158 (should (= (current-indentation) 4))
5160 ;; But a comma outside it, should trigger indentation.
5161 (python-tests-self-insert ",")
5162 (should (= (current-indentation) 23))
5164 ;; Newline indents to the first argument column
5165 (python-tests-self-insert "\n")
5166 (should (= (current-indentation) 23))
5168 ;; All this input must not change indentation
5169 (indent-line-to 4)
5170 (python-tests-self-insert "url(r'^/login$', views.login)")
5171 (should (= (current-indentation) 4))
5173 ;; But this comma does
5174 (python-tests-self-insert ",")
5175 (should (= (current-indentation) 23))))
5176 (or eim (electric-indent-mode -1)))))
5178 (ert-deftest python-triple-quote-pairing ()
5179 (let ((epm electric-pair-mode))
5180 (unwind-protect
5181 (progn
5182 (python-tests-with-temp-buffer
5183 "\"\"\n"
5184 (or epm (electric-pair-mode 1))
5185 (goto-char (1- (point-max)))
5186 (python-tests-self-insert ?\")
5187 (should (string= (buffer-string)
5188 "\"\"\"\"\"\"\n"))
5189 (should (= (point) 4)))
5190 (python-tests-with-temp-buffer
5191 "\n"
5192 (python-tests-self-insert (list ?\" ?\" ?\"))
5193 (should (string= (buffer-string)
5194 "\"\"\"\"\"\"\n"))
5195 (should (= (point) 4)))
5196 (python-tests-with-temp-buffer
5197 "\"\n\"\"\n"
5198 (goto-char (1- (point-max)))
5199 (python-tests-self-insert ?\")
5200 (should (= (point) (1- (point-max))))
5201 (should (string= (buffer-string)
5202 "\"\n\"\"\"\n"))))
5203 (or epm (electric-pair-mode -1)))))
5206 ;;; Hideshow support
5208 (ert-deftest python-hideshow-hide-levels-1 ()
5209 "Should hide all methods when called after class start."
5210 (let ((enabled hs-minor-mode))
5211 (unwind-protect
5212 (progn
5213 (python-tests-with-temp-buffer
5215 class SomeClass:
5217 def __init__(self, arg, kwarg=1):
5218 self.arg = arg
5219 self.kwarg = kwarg
5221 def filter(self, nums):
5222 def fn(item):
5223 return item in [self.arg, self.kwarg]
5224 return filter(fn, nums)
5226 def __str__(self):
5227 return '%s-%s' % (self.arg, self.kwarg)
5229 (hs-minor-mode 1)
5230 (python-tests-look-at "class SomeClass:")
5231 (forward-line)
5232 (hs-hide-level 1)
5233 (should
5234 (string=
5235 (python-tests-visible-string)
5237 class SomeClass:
5239 def __init__(self, arg, kwarg=1):
5240 def filter(self, nums):
5241 def __str__(self):"))))
5242 (or enabled (hs-minor-mode -1)))))
5244 (ert-deftest python-hideshow-hide-levels-2 ()
5245 "Should hide nested methods and parens at end of defun."
5246 (let ((enabled hs-minor-mode))
5247 (unwind-protect
5248 (progn
5249 (python-tests-with-temp-buffer
5251 class SomeClass:
5253 def __init__(self, arg, kwarg=1):
5254 self.arg = arg
5255 self.kwarg = kwarg
5257 def filter(self, nums):
5258 def fn(item):
5259 return item in [self.arg, self.kwarg]
5260 return filter(fn, nums)
5262 def __str__(self):
5263 return '%s-%s' % (self.arg, self.kwarg)
5265 (hs-minor-mode 1)
5266 (python-tests-look-at "def fn(item):")
5267 (hs-hide-block)
5268 (should
5269 (string=
5270 (python-tests-visible-string)
5272 class SomeClass:
5274 def __init__(self, arg, kwarg=1):
5275 self.arg = arg
5276 self.kwarg = kwarg
5278 def filter(self, nums):
5279 def fn(item):
5280 return filter(fn, nums)
5282 def __str__(self):
5283 return '%s-%s' % (self.arg, self.kwarg)
5284 "))))
5285 (or enabled (hs-minor-mode -1)))))
5289 (provide 'python-tests)
5291 ;; Local Variables:
5292 ;; indent-tabs-mode: nil
5293 ;; End:
5295 ;;; python-tests.el ends here