Give '$' punctuation syntax in make-mode (Bug#24477)
[emacs.git] / test / lisp / progmodes / python-tests.el
blob1c4d22d72faf029600ed08333a482c7cc4211a48
1 ;;; python-tests.el --- Test suite for python.el
3 ;; Copyright (C) 2013-2018 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 <https://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) python-indent-offset))
759 (python-tests-look-at "some_final_calculation()")
760 (should (eq (car (python-indent-context)) :after-backslash))
761 (should (= (python-indent-calculate-indentation) python-indent-offset))))
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-comma-inside-multiline-string ()
1113 "Test indentation ...."
1114 (python-tests-with-temp-buffer
1116 a = (
1117 '''\
1118 - foo,
1119 - bar
1122 (python-tests-look-at "- bar")
1123 (should (eq (car (python-indent-context)) :inside-string))
1124 (goto-char (line-end-position))
1125 (python-tests-self-insert ",")
1126 (should (= (current-indentation) 0))))
1128 (ert-deftest python-indent-electric-comma-after-multiline-string ()
1129 "Test indentation ...."
1130 (python-tests-with-temp-buffer
1132 a = (
1133 '''\
1134 - foo,
1135 - bar'''
1137 (python-tests-look-at "- bar'''")
1138 (should (eq (car (python-indent-context)) :inside-string))
1139 (goto-char (line-end-position))
1140 (python-tests-self-insert ",")
1141 (should (= (current-indentation) 0))))
1143 (ert-deftest python-indent-electric-colon-1 ()
1144 "Test indentation case from Bug#18228."
1145 (python-tests-with-temp-buffer
1147 def a():
1148 pass
1150 def b()
1152 (python-tests-look-at "def b()")
1153 (goto-char (line-end-position))
1154 (python-tests-self-insert ":")
1155 (should (= (current-indentation) 0))))
1157 (ert-deftest python-indent-electric-colon-2 ()
1158 "Test indentation case for dedenter."
1159 (python-tests-with-temp-buffer
1161 if do:
1162 something()
1163 else
1165 (python-tests-look-at "else")
1166 (goto-char (line-end-position))
1167 (python-tests-self-insert ":")
1168 (should (= (current-indentation) 0))))
1170 (ert-deftest python-indent-electric-colon-3 ()
1171 "Test indentation case for multi-line dedenter."
1172 (python-tests-with-temp-buffer
1174 if do:
1175 something()
1176 elif (this
1178 that)
1180 (python-tests-look-at "that)")
1181 (goto-char (line-end-position))
1182 (python-tests-self-insert ":")
1183 (python-tests-look-at "elif" -1)
1184 (should (= (current-indentation) 0))
1185 (python-tests-look-at "and")
1186 (should (= (current-indentation) 6))
1187 (python-tests-look-at "that)")
1188 (should (= (current-indentation) 6))))
1190 (ert-deftest python-indent-electric-colon-4 ()
1191 "Test indentation case where there is one more-indented previous open block."
1192 (python-tests-with-temp-buffer
1194 def f():
1195 if True:
1196 a = 5
1198 if True:
1199 a = 10
1201 b = 3
1203 else
1205 (python-tests-look-at "else")
1206 (goto-char (line-end-position))
1207 (python-tests-self-insert ":")
1208 (python-tests-look-at "else" -1)
1209 (should (= (current-indentation) 4))))
1211 (ert-deftest python-indent-region-1 ()
1212 "Test indentation case from Bug#18843."
1213 (let ((contents "
1214 def foo ():
1215 try:
1216 pass
1217 except:
1218 pass
1220 (python-tests-with-temp-buffer
1221 contents
1222 (python-indent-region (point-min) (point-max))
1223 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1224 contents)))))
1226 (ert-deftest python-indent-region-2 ()
1227 "Test region indentation on comments."
1228 (let ((contents "
1229 def f():
1230 if True:
1231 pass
1233 # This is
1234 # some multiline
1235 # comment
1237 (python-tests-with-temp-buffer
1238 contents
1239 (python-indent-region (point-min) (point-max))
1240 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1241 contents)))))
1243 (ert-deftest python-indent-region-3 ()
1244 "Test region indentation on comments."
1245 (let ((contents "
1246 def f():
1247 if True:
1248 pass
1249 # This is
1250 # some multiline
1251 # comment
1253 (expected "
1254 def f():
1255 if True:
1256 pass
1257 # This is
1258 # some multiline
1259 # comment
1261 (python-tests-with-temp-buffer
1262 contents
1263 (python-indent-region (point-min) (point-max))
1264 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1265 expected)))))
1267 (ert-deftest python-indent-region-4 ()
1268 "Test region indentation block starts, dedenters and enders."
1269 (let ((contents "
1270 def f():
1271 if True:
1272 a = 5
1273 else:
1274 a = 10
1275 return a
1277 (expected "
1278 def f():
1279 if True:
1280 a = 5
1281 else:
1282 a = 10
1283 return a
1285 (python-tests-with-temp-buffer
1286 contents
1287 (python-indent-region (point-min) (point-max))
1288 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1289 expected)))))
1291 (ert-deftest python-indent-region-5 ()
1292 "Test region indentation for docstrings."
1293 (let ((contents "
1294 def f():
1296 this is
1297 a multiline
1298 string
1300 x = \\
1302 this is an arbitrarily
1303 indented multiline
1304 string
1307 (expected "
1308 def f():
1310 this is
1311 a multiline
1312 string
1314 x = \\
1316 this is an arbitrarily
1317 indented multiline
1318 string
1321 (python-tests-with-temp-buffer
1322 contents
1323 (python-indent-region (point-min) (point-max))
1324 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1325 expected)))))
1328 ;;; Mark
1330 (ert-deftest python-mark-defun-1 ()
1331 """Test `python-mark-defun' with point at defun symbol start."""
1332 (python-tests-with-temp-buffer
1334 def foo(x):
1335 return x
1337 class A:
1338 pass
1340 class B:
1342 def __init__(self):
1343 self.b = 'b'
1345 def fun(self):
1346 return self.b
1348 class C:
1349 '''docstring'''
1351 (let ((transient-mark-mode t)
1352 (expected-mark-beginning-position
1353 (progn
1354 (python-tests-look-at "class A:")
1355 (1- (point))))
1356 (expected-mark-end-position-1
1357 (save-excursion
1358 (python-tests-look-at "pass")
1359 (forward-line)
1360 (point)))
1361 (expected-mark-end-position-2
1362 (save-excursion
1363 (python-tests-look-at "return self.b")
1364 (forward-line)
1365 (point)))
1366 (expected-mark-end-position-3
1367 (save-excursion
1368 (python-tests-look-at "'''docstring'''")
1369 (forward-line)
1370 (point))))
1371 ;; Select class A only, with point at bol.
1372 (python-mark-defun 1)
1373 (should (= (point) expected-mark-beginning-position))
1374 (should (= (marker-position (mark-marker))
1375 expected-mark-end-position-1))
1376 ;; expand to class B, start position should remain the same.
1377 (python-mark-defun 1)
1378 (should (= (point) expected-mark-beginning-position))
1379 (should (= (marker-position (mark-marker))
1380 expected-mark-end-position-2))
1381 ;; expand to class C, start position should remain the same.
1382 (python-mark-defun 1)
1383 (should (= (point) expected-mark-beginning-position))
1384 (should (= (marker-position (mark-marker))
1385 expected-mark-end-position-3)))))
1387 (ert-deftest python-mark-defun-2 ()
1388 """Test `python-mark-defun' with point at nested defun symbol start."""
1389 (python-tests-with-temp-buffer
1391 def foo(x):
1392 return x
1394 class A:
1395 pass
1397 class B:
1399 def __init__(self):
1400 self.b = 'b'
1402 def fun(self):
1403 return self.b
1405 class C:
1406 '''docstring'''
1408 (let ((transient-mark-mode t)
1409 (expected-mark-beginning-position
1410 (progn
1411 (python-tests-look-at "def __init__(self):")
1412 (1- (line-beginning-position))))
1413 (expected-mark-end-position-1
1414 (save-excursion
1415 (python-tests-look-at "self.b = 'b'")
1416 (forward-line)
1417 (point)))
1418 (expected-mark-end-position-2
1419 (save-excursion
1420 (python-tests-look-at "return self.b")
1421 (forward-line)
1422 (point)))
1423 (expected-mark-end-position-3
1424 (save-excursion
1425 (python-tests-look-at "'''docstring'''")
1426 (forward-line)
1427 (point))))
1428 ;; Select B.__init only, with point at its start.
1429 (python-mark-defun 1)
1430 (should (= (point) expected-mark-beginning-position))
1431 (should (= (marker-position (mark-marker))
1432 expected-mark-end-position-1))
1433 ;; expand to B.fun, start position should remain the same.
1434 (python-mark-defun 1)
1435 (should (= (point) expected-mark-beginning-position))
1436 (should (= (marker-position (mark-marker))
1437 expected-mark-end-position-2))
1438 ;; expand to class C, start position should remain the same.
1439 (python-mark-defun 1)
1440 (should (= (point) expected-mark-beginning-position))
1441 (should (= (marker-position (mark-marker))
1442 expected-mark-end-position-3)))))
1444 (ert-deftest python-mark-defun-3 ()
1445 """Test `python-mark-defun' with point inside defun symbol."""
1446 (python-tests-with-temp-buffer
1448 def foo(x):
1449 return x
1451 class A:
1452 pass
1454 class B:
1456 def __init__(self):
1457 self.b = 'b'
1459 def fun(self):
1460 return self.b
1462 class C:
1463 '''docstring'''
1465 (let ((expected-mark-beginning-position
1466 (progn
1467 (python-tests-look-at "def fun(self):")
1468 (python-tests-look-at "(self):")
1469 (1- (line-beginning-position))))
1470 (expected-mark-end-position
1471 (save-excursion
1472 (python-tests-look-at "return self.b")
1473 (forward-line)
1474 (point))))
1475 ;; Should select B.fun, despite point is inside the defun symbol.
1476 (python-mark-defun 1)
1477 (should (= (point) expected-mark-beginning-position))
1478 (should (= (marker-position (mark-marker))
1479 expected-mark-end-position)))))
1482 ;;; Navigation
1484 (ert-deftest python-nav-beginning-of-defun-1 ()
1485 (python-tests-with-temp-buffer
1487 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1488 '''print decorated function call data to stdout.
1490 Usage:
1492 @decoratorFunctionWithArguments('arg1', 'arg2')
1493 def func(a, b, c=True):
1494 pass
1497 def wwrap(f):
1498 print 'Inside wwrap()'
1499 def wrapped_f(*args):
1500 print 'Inside wrapped_f()'
1501 print 'Decorator arguments:', arg1, arg2, arg3
1502 f(*args)
1503 print 'After f(*args)'
1504 return wrapped_f
1505 return wwrap
1507 (python-tests-look-at "return wrap")
1508 (should (= (save-excursion
1509 (python-nav-beginning-of-defun)
1510 (point))
1511 (save-excursion
1512 (python-tests-look-at "def wrapped_f(*args):" -1)
1513 (beginning-of-line)
1514 (point))))
1515 (python-tests-look-at "def wrapped_f(*args):" -1)
1516 (should (= (save-excursion
1517 (python-nav-beginning-of-defun)
1518 (point))
1519 (save-excursion
1520 (python-tests-look-at "def wwrap(f):" -1)
1521 (beginning-of-line)
1522 (point))))
1523 (python-tests-look-at "def wwrap(f):" -1)
1524 (should (= (save-excursion
1525 (python-nav-beginning-of-defun)
1526 (point))
1527 (save-excursion
1528 (python-tests-look-at "def decoratorFunctionWithArguments" -1)
1529 (beginning-of-line)
1530 (point))))))
1532 (ert-deftest python-nav-beginning-of-defun-2 ()
1533 (python-tests-with-temp-buffer
1535 class C(object):
1537 def m(self):
1538 self.c()
1540 def b():
1541 pass
1543 def a():
1544 pass
1546 def c(self):
1547 pass
1549 ;; Nested defuns, are handled with care.
1550 (python-tests-look-at "def c(self):")
1551 (should (= (save-excursion
1552 (python-nav-beginning-of-defun)
1553 (point))
1554 (save-excursion
1555 (python-tests-look-at "def m(self):" -1)
1556 (beginning-of-line)
1557 (point))))
1558 ;; Defuns on same levels should be respected.
1559 (python-tests-look-at "def a():" -1)
1560 (should (= (save-excursion
1561 (python-nav-beginning-of-defun)
1562 (point))
1563 (save-excursion
1564 (python-tests-look-at "def b():" -1)
1565 (beginning-of-line)
1566 (point))))
1567 ;; Jump to a top level defun.
1568 (python-tests-look-at "def b():" -1)
1569 (should (= (save-excursion
1570 (python-nav-beginning-of-defun)
1571 (point))
1572 (save-excursion
1573 (python-tests-look-at "def m(self):" -1)
1574 (beginning-of-line)
1575 (point))))
1576 ;; Jump to a top level defun again.
1577 (python-tests-look-at "def m(self):" -1)
1578 (should (= (save-excursion
1579 (python-nav-beginning-of-defun)
1580 (point))
1581 (save-excursion
1582 (python-tests-look-at "class C(object):" -1)
1583 (beginning-of-line)
1584 (point))))))
1586 (ert-deftest python-nav-beginning-of-defun-3 ()
1587 (python-tests-with-temp-buffer
1589 class C(object):
1591 async def m(self):
1592 return await self.c()
1594 async def c(self):
1595 pass
1597 (python-tests-look-at "self.c()")
1598 (should (= (save-excursion
1599 (python-nav-beginning-of-defun)
1600 (point))
1601 (save-excursion
1602 (python-tests-look-at "async def m" -1)
1603 (beginning-of-line)
1604 (point))))))
1606 (ert-deftest python-nav-end-of-defun-1 ()
1607 (python-tests-with-temp-buffer
1609 class C(object):
1611 def m(self):
1612 self.c()
1614 def b():
1615 pass
1617 def a():
1618 pass
1620 def c(self):
1621 pass
1623 (should (= (save-excursion
1624 (python-tests-look-at "class C(object):")
1625 (python-nav-end-of-defun)
1626 (point))
1627 (save-excursion
1628 (point-max))))
1629 (should (= (save-excursion
1630 (python-tests-look-at "def m(self):")
1631 (python-nav-end-of-defun)
1632 (point))
1633 (save-excursion
1634 (python-tests-look-at "def c(self):")
1635 (forward-line -1)
1636 (point))))
1637 (should (= (save-excursion
1638 (python-tests-look-at "def b():")
1639 (python-nav-end-of-defun)
1640 (point))
1641 (save-excursion
1642 (python-tests-look-at "def b():")
1643 (forward-line 2)
1644 (point))))
1645 (should (= (save-excursion
1646 (python-tests-look-at "def c(self):")
1647 (python-nav-end-of-defun)
1648 (point))
1649 (save-excursion
1650 (point-max))))))
1652 (ert-deftest python-nav-end-of-defun-2 ()
1653 (python-tests-with-temp-buffer
1655 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1656 '''print decorated function call data to stdout.
1658 Usage:
1660 @decoratorFunctionWithArguments('arg1', 'arg2')
1661 def func(a, b, c=True):
1662 pass
1665 def wwrap(f):
1666 print 'Inside wwrap()'
1667 def wrapped_f(*args):
1668 print 'Inside wrapped_f()'
1669 print 'Decorator arguments:', arg1, arg2, arg3
1670 f(*args)
1671 print 'After f(*args)'
1672 return wrapped_f
1673 return wwrap
1675 (should (= (save-excursion
1676 (python-tests-look-at "def decoratorFunctionWithArguments")
1677 (python-nav-end-of-defun)
1678 (point))
1679 (save-excursion
1680 (point-max))))
1681 (should (= (save-excursion
1682 (python-tests-look-at "@decoratorFunctionWithArguments")
1683 (python-nav-end-of-defun)
1684 (point))
1685 (save-excursion
1686 (point-max))))
1687 (should (= (save-excursion
1688 (python-tests-look-at "def wwrap(f):")
1689 (python-nav-end-of-defun)
1690 (point))
1691 (save-excursion
1692 (python-tests-look-at "return wwrap")
1693 (line-beginning-position))))
1694 (should (= (save-excursion
1695 (python-tests-look-at "def wrapped_f(*args):")
1696 (python-nav-end-of-defun)
1697 (point))
1698 (save-excursion
1699 (python-tests-look-at "return wrapped_f")
1700 (line-beginning-position))))
1701 (should (= (save-excursion
1702 (python-tests-look-at "f(*args)")
1703 (python-nav-end-of-defun)
1704 (point))
1705 (save-excursion
1706 (python-tests-look-at "return wrapped_f")
1707 (line-beginning-position))))))
1709 (ert-deftest python-nav-backward-defun-1 ()
1710 (python-tests-with-temp-buffer
1712 class A(object): # A
1714 def a(self): # a
1715 pass
1717 def b(self): # b
1718 pass
1720 class B(object): # B
1722 class C(object): # C
1724 def d(self): # d
1725 pass
1727 # def e(self): # e
1728 # pass
1730 def c(self): # c
1731 pass
1733 # def d(self): # d
1734 # pass
1736 (goto-char (point-max))
1737 (should (= (save-excursion (python-nav-backward-defun))
1738 (python-tests-look-at " def c(self): # c" -1)))
1739 (should (= (save-excursion (python-nav-backward-defun))
1740 (python-tests-look-at " def d(self): # d" -1)))
1741 (should (= (save-excursion (python-nav-backward-defun))
1742 (python-tests-look-at " class C(object): # C" -1)))
1743 (should (= (save-excursion (python-nav-backward-defun))
1744 (python-tests-look-at " class B(object): # B" -1)))
1745 (should (= (save-excursion (python-nav-backward-defun))
1746 (python-tests-look-at " def b(self): # b" -1)))
1747 (should (= (save-excursion (python-nav-backward-defun))
1748 (python-tests-look-at " def a(self): # a" -1)))
1749 (should (= (save-excursion (python-nav-backward-defun))
1750 (python-tests-look-at "class A(object): # A" -1)))
1751 (should (not (python-nav-backward-defun)))))
1753 (ert-deftest python-nav-backward-defun-2 ()
1754 (python-tests-with-temp-buffer
1756 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1757 '''print decorated function call data to stdout.
1759 Usage:
1761 @decoratorFunctionWithArguments('arg1', 'arg2')
1762 def func(a, b, c=True):
1763 pass
1766 def wwrap(f):
1767 print 'Inside wwrap()'
1768 def wrapped_f(*args):
1769 print 'Inside wrapped_f()'
1770 print 'Decorator arguments:', arg1, arg2, arg3
1771 f(*args)
1772 print 'After f(*args)'
1773 return wrapped_f
1774 return wwrap
1776 (goto-char (point-max))
1777 (should (= (save-excursion (python-nav-backward-defun))
1778 (python-tests-look-at " def wrapped_f(*args):" -1)))
1779 (should (= (save-excursion (python-nav-backward-defun))
1780 (python-tests-look-at " def wwrap(f):" -1)))
1781 (should (= (save-excursion (python-nav-backward-defun))
1782 (python-tests-look-at "def decoratorFunctionWithArguments(arg1, arg2, arg3):" -1)))
1783 (should (not (python-nav-backward-defun)))))
1785 (ert-deftest python-nav-backward-defun-3 ()
1786 (python-tests-with-temp-buffer
1789 def u(self):
1790 pass
1792 def v(self):
1793 pass
1795 def w(self):
1796 pass
1799 class A(object):
1800 pass
1802 (goto-char (point-min))
1803 (let ((point (python-tests-look-at "class A(object):")))
1804 (should (not (python-nav-backward-defun)))
1805 (should (= point (point))))))
1807 (ert-deftest python-nav-forward-defun-1 ()
1808 (python-tests-with-temp-buffer
1810 class A(object): # A
1812 def a(self): # a
1813 pass
1815 def b(self): # b
1816 pass
1818 class B(object): # B
1820 class C(object): # C
1822 def d(self): # d
1823 pass
1825 # def e(self): # e
1826 # pass
1828 def c(self): # c
1829 pass
1831 # def d(self): # d
1832 # pass
1834 (goto-char (point-min))
1835 (should (= (save-excursion (python-nav-forward-defun))
1836 (python-tests-look-at "(object): # A")))
1837 (should (= (save-excursion (python-nav-forward-defun))
1838 (python-tests-look-at "(self): # a")))
1839 (should (= (save-excursion (python-nav-forward-defun))
1840 (python-tests-look-at "(self): # b")))
1841 (should (= (save-excursion (python-nav-forward-defun))
1842 (python-tests-look-at "(object): # B")))
1843 (should (= (save-excursion (python-nav-forward-defun))
1844 (python-tests-look-at "(object): # C")))
1845 (should (= (save-excursion (python-nav-forward-defun))
1846 (python-tests-look-at "(self): # d")))
1847 (should (= (save-excursion (python-nav-forward-defun))
1848 (python-tests-look-at "(self): # c")))
1849 (should (not (python-nav-forward-defun)))))
1851 (ert-deftest python-nav-forward-defun-2 ()
1852 (python-tests-with-temp-buffer
1854 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1855 '''print decorated function call data to stdout.
1857 Usage:
1859 @decoratorFunctionWithArguments('arg1', 'arg2')
1860 def func(a, b, c=True):
1861 pass
1864 def wwrap(f):
1865 print 'Inside wwrap()'
1866 def wrapped_f(*args):
1867 print 'Inside wrapped_f()'
1868 print 'Decorator arguments:', arg1, arg2, arg3
1869 f(*args)
1870 print 'After f(*args)'
1871 return wrapped_f
1872 return wwrap
1874 (goto-char (point-min))
1875 (should (= (save-excursion (python-nav-forward-defun))
1876 (python-tests-look-at "(arg1, arg2, arg3):")))
1877 (should (= (save-excursion (python-nav-forward-defun))
1878 (python-tests-look-at "(f):")))
1879 (should (= (save-excursion (python-nav-forward-defun))
1880 (python-tests-look-at "(*args):")))
1881 (should (not (python-nav-forward-defun)))))
1883 (ert-deftest python-nav-forward-defun-3 ()
1884 (python-tests-with-temp-buffer
1886 class A(object):
1887 pass
1890 def u(self):
1891 pass
1893 def v(self):
1894 pass
1896 def w(self):
1897 pass
1900 (goto-char (point-min))
1901 (let ((point (python-tests-look-at "(object):")))
1902 (should (not (python-nav-forward-defun)))
1903 (should (= point (point))))))
1905 (ert-deftest python-nav-beginning-of-statement-1 ()
1906 (python-tests-with-temp-buffer
1908 v1 = 123 + \\
1909 456 + \\
1911 v2 = (value1,
1912 value2,
1914 value3,
1915 value4)
1916 v3 = ('this is a string'
1918 'that is continued'
1919 'between lines'
1920 'within a paren',
1921 # this is a comment, yo
1922 'continue previous line')
1923 v4 = '''
1924 a very long
1925 string
1928 (python-tests-look-at "v2 =")
1929 (python-util-forward-comment -1)
1930 (should (= (save-excursion
1931 (python-nav-beginning-of-statement)
1932 (point))
1933 (python-tests-look-at "v1 =" -1 t)))
1934 (python-tests-look-at "v3 =")
1935 (python-util-forward-comment -1)
1936 (should (= (save-excursion
1937 (python-nav-beginning-of-statement)
1938 (point))
1939 (python-tests-look-at "v2 =" -1 t)))
1940 (python-tests-look-at "v4 =")
1941 (python-util-forward-comment -1)
1942 (should (= (save-excursion
1943 (python-nav-beginning-of-statement)
1944 (point))
1945 (python-tests-look-at "v3 =" -1 t)))
1946 (goto-char (point-max))
1947 (python-util-forward-comment -1)
1948 (should (= (save-excursion
1949 (python-nav-beginning-of-statement)
1950 (point))
1951 (python-tests-look-at "v4 =" -1 t)))))
1953 (ert-deftest python-nav-end-of-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-end-of-statement)
1979 (point))
1980 (save-excursion
1981 (python-tests-look-at "789")
1982 (line-end-position))))
1983 (python-tests-look-at "v2 =")
1984 (should (= (save-excursion
1985 (python-nav-end-of-statement)
1986 (point))
1987 (save-excursion
1988 (python-tests-look-at "value4)")
1989 (line-end-position))))
1990 (python-tests-look-at "v3 =")
1991 (should (= (save-excursion
1992 (python-nav-end-of-statement)
1993 (point))
1994 (save-excursion
1995 (python-tests-look-at
1996 "'continue previous line')")
1997 (line-end-position))))
1998 (python-tests-look-at "v4 =")
1999 (should (= (save-excursion
2000 (python-nav-end-of-statement)
2001 (point))
2002 (save-excursion
2003 (goto-char (point-max))
2004 (python-util-forward-comment -1)
2005 (point))))))
2007 (ert-deftest python-nav-forward-statement-1 ()
2008 (python-tests-with-temp-buffer
2010 v1 = 123 + \\
2011 456 + \\
2013 v2 = (value1,
2014 value2,
2016 value3,
2017 value4)
2018 v3 = ('this is a string'
2020 'that is continued'
2021 'between lines'
2022 'within a paren',
2023 # this is a comment, yo
2024 'continue previous line')
2025 v4 = '''
2026 a very long
2027 string
2030 (python-tests-look-at "v1 =")
2031 (should (= (save-excursion
2032 (python-nav-forward-statement)
2033 (point))
2034 (python-tests-look-at "v2 =")))
2035 (should (= (save-excursion
2036 (python-nav-forward-statement)
2037 (point))
2038 (python-tests-look-at "v3 =")))
2039 (should (= (save-excursion
2040 (python-nav-forward-statement)
2041 (point))
2042 (python-tests-look-at "v4 =")))
2043 (should (= (save-excursion
2044 (python-nav-forward-statement)
2045 (point))
2046 (point-max)))))
2048 (ert-deftest python-nav-backward-statement-1 ()
2049 (python-tests-with-temp-buffer
2051 v1 = 123 + \\
2052 456 + \\
2054 v2 = (value1,
2055 value2,
2057 value3,
2058 value4)
2059 v3 = ('this is a string'
2061 'that is continued'
2062 'between lines'
2063 'within a paren',
2064 # this is a comment, yo
2065 'continue previous line')
2066 v4 = '''
2067 a very long
2068 string
2071 (goto-char (point-max))
2072 (should (= (save-excursion
2073 (python-nav-backward-statement)
2074 (point))
2075 (python-tests-look-at "v4 =" -1)))
2076 (should (= (save-excursion
2077 (python-nav-backward-statement)
2078 (point))
2079 (python-tests-look-at "v3 =" -1)))
2080 (should (= (save-excursion
2081 (python-nav-backward-statement)
2082 (point))
2083 (python-tests-look-at "v2 =" -1)))
2084 (should (= (save-excursion
2085 (python-nav-backward-statement)
2086 (point))
2087 (python-tests-look-at "v1 =" -1)))))
2089 (ert-deftest python-nav-backward-statement-2 ()
2090 :expected-result :failed
2091 (python-tests-with-temp-buffer
2093 v1 = 123 + \\
2094 456 + \\
2096 v2 = (value1,
2097 value2,
2099 value3,
2100 value4)
2102 ;; FIXME: For some reason `python-nav-backward-statement' is moving
2103 ;; back two sentences when starting from 'value4)'.
2104 (goto-char (point-max))
2105 (python-util-forward-comment -1)
2106 (should (= (save-excursion
2107 (python-nav-backward-statement)
2108 (point))
2109 (python-tests-look-at "v2 =" -1 t)))))
2111 (ert-deftest python-nav-beginning-of-block-1 ()
2112 (python-tests-with-temp-buffer
2114 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2115 '''print decorated function call data to stdout.
2117 Usage:
2119 @decoratorFunctionWithArguments('arg1', 'arg2')
2120 def func(a, b, c=True):
2121 pass
2124 def wwrap(f):
2125 print 'Inside wwrap()'
2126 def wrapped_f(*args):
2127 print 'Inside wrapped_f()'
2128 print 'Decorator arguments:', arg1, arg2, arg3
2129 f(*args)
2130 print 'After f(*args)'
2131 return wrapped_f
2132 return wwrap
2134 (python-tests-look-at "return wwrap")
2135 (should (= (save-excursion
2136 (python-nav-beginning-of-block)
2137 (point))
2138 (python-tests-look-at "def decoratorFunctionWithArguments" -1)))
2139 (python-tests-look-at "print 'Inside wwrap()'")
2140 (should (= (save-excursion
2141 (python-nav-beginning-of-block)
2142 (point))
2143 (python-tests-look-at "def wwrap(f):" -1)))
2144 (python-tests-look-at "print 'After f(*args)'")
2145 (end-of-line)
2146 (should (= (save-excursion
2147 (python-nav-beginning-of-block)
2148 (point))
2149 (python-tests-look-at "def wrapped_f(*args):" -1)))
2150 (python-tests-look-at "return wrapped_f")
2151 (should (= (save-excursion
2152 (python-nav-beginning-of-block)
2153 (point))
2154 (python-tests-look-at "def wwrap(f):" -1)))))
2156 (ert-deftest python-nav-end-of-block-1 ()
2157 (python-tests-with-temp-buffer
2159 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2160 '''print decorated function call data to stdout.
2162 Usage:
2164 @decoratorFunctionWithArguments('arg1', 'arg2')
2165 def func(a, b, c=True):
2166 pass
2169 def wwrap(f):
2170 print 'Inside wwrap()'
2171 def wrapped_f(*args):
2172 print 'Inside wrapped_f()'
2173 print 'Decorator arguments:', arg1, arg2, arg3
2174 f(*args)
2175 print 'After f(*args)'
2176 return wrapped_f
2177 return wwrap
2179 (python-tests-look-at "def decoratorFunctionWithArguments")
2180 (should (= (save-excursion
2181 (python-nav-end-of-block)
2182 (point))
2183 (save-excursion
2184 (goto-char (point-max))
2185 (python-util-forward-comment -1)
2186 (point))))
2187 (python-tests-look-at "def wwrap(f):")
2188 (should (= (save-excursion
2189 (python-nav-end-of-block)
2190 (point))
2191 (save-excursion
2192 (python-tests-look-at "return wrapped_f")
2193 (line-end-position))))
2194 (end-of-line)
2195 (should (= (save-excursion
2196 (python-nav-end-of-block)
2197 (point))
2198 (save-excursion
2199 (python-tests-look-at "return wrapped_f")
2200 (line-end-position))))
2201 (python-tests-look-at "f(*args)")
2202 (should (= (save-excursion
2203 (python-nav-end-of-block)
2204 (point))
2205 (save-excursion
2206 (python-tests-look-at "print 'After f(*args)'")
2207 (line-end-position))))))
2209 (ert-deftest python-nav-forward-block-1 ()
2210 "This also accounts as a test for `python-nav-backward-block'."
2211 (python-tests-with-temp-buffer
2213 if request.user.is_authenticated():
2214 # def block():
2215 # pass
2216 try:
2217 profile = request.user.get_profile()
2218 except Profile.DoesNotExist:
2219 profile = Profile.objects.create(user=request.user)
2220 else:
2221 if profile.stats:
2222 profile.recalculate_stats()
2223 else:
2224 profile.clear_stats()
2225 finally:
2226 profile.views += 1
2227 profile.save()
2229 (should (= (save-excursion (python-nav-forward-block))
2230 (python-tests-look-at "if request.user.is_authenticated():")))
2231 (should (= (save-excursion (python-nav-forward-block))
2232 (python-tests-look-at "try:")))
2233 (should (= (save-excursion (python-nav-forward-block))
2234 (python-tests-look-at "except Profile.DoesNotExist:")))
2235 (should (= (save-excursion (python-nav-forward-block))
2236 (python-tests-look-at "else:")))
2237 (should (= (save-excursion (python-nav-forward-block))
2238 (python-tests-look-at "if profile.stats:")))
2239 (should (= (save-excursion (python-nav-forward-block))
2240 (python-tests-look-at "else:")))
2241 (should (= (save-excursion (python-nav-forward-block))
2242 (python-tests-look-at "finally:")))
2243 ;; When point is at the last block, leave it there and return nil
2244 (should (not (save-excursion (python-nav-forward-block))))
2245 ;; Move backwards, and even if the number of moves is less than the
2246 ;; provided argument return the point.
2247 (should (= (save-excursion (python-nav-forward-block -10))
2248 (python-tests-look-at
2249 "if request.user.is_authenticated():" -1)))))
2251 (ert-deftest python-nav-forward-sexp-1 ()
2252 (python-tests-with-temp-buffer
2258 (python-tests-look-at "a()")
2259 (python-nav-forward-sexp)
2260 (should (looking-at "$"))
2261 (should (save-excursion
2262 (beginning-of-line)
2263 (looking-at "a()")))
2264 (python-nav-forward-sexp)
2265 (should (looking-at "$"))
2266 (should (save-excursion
2267 (beginning-of-line)
2268 (looking-at "b()")))
2269 (python-nav-forward-sexp)
2270 (should (looking-at "$"))
2271 (should (save-excursion
2272 (beginning-of-line)
2273 (looking-at "c()")))
2274 ;; The default behavior when next to a paren should do what lisp
2275 ;; does and, otherwise `blink-matching-open' breaks.
2276 (python-nav-forward-sexp -1)
2277 (should (looking-at "()"))
2278 (should (save-excursion
2279 (beginning-of-line)
2280 (looking-at "c()")))
2281 (end-of-line)
2282 ;; Skipping parens should jump to `bolp'
2283 (python-nav-forward-sexp -1 nil t)
2284 (should (looking-at "c()"))
2285 (forward-line -1)
2286 (end-of-line)
2287 ;; b()
2288 (python-nav-forward-sexp -1)
2289 (should (looking-at "()"))
2290 (python-nav-forward-sexp -1)
2291 (should (looking-at "b()"))
2292 (end-of-line)
2293 (python-nav-forward-sexp -1 nil t)
2294 (should (looking-at "b()"))
2295 (forward-line -1)
2296 (end-of-line)
2297 ;; a()
2298 (python-nav-forward-sexp -1)
2299 (should (looking-at "()"))
2300 (python-nav-forward-sexp -1)
2301 (should (looking-at "a()"))
2302 (end-of-line)
2303 (python-nav-forward-sexp -1 nil t)
2304 (should (looking-at "a()"))))
2306 (ert-deftest python-nav-forward-sexp-2 ()
2307 (python-tests-with-temp-buffer
2309 def func():
2310 if True:
2311 aaa = bbb
2312 ccc = ddd
2313 eee = fff
2314 return ggg
2316 (python-tests-look-at "aa =")
2317 (python-nav-forward-sexp)
2318 (should (looking-at " = bbb"))
2319 (python-nav-forward-sexp)
2320 (should (looking-at "$"))
2321 (should (save-excursion
2322 (back-to-indentation)
2323 (looking-at "aaa = bbb")))
2324 (python-nav-forward-sexp)
2325 (should (looking-at "$"))
2326 (should (save-excursion
2327 (back-to-indentation)
2328 (looking-at "ccc = ddd")))
2329 (python-nav-forward-sexp)
2330 (should (looking-at "$"))
2331 (should (save-excursion
2332 (back-to-indentation)
2333 (looking-at "eee = fff")))
2334 (python-nav-forward-sexp)
2335 (should (looking-at "$"))
2336 (should (save-excursion
2337 (back-to-indentation)
2338 (looking-at "return ggg")))
2339 (python-nav-forward-sexp -1)
2340 (should (looking-at "def func():"))))
2342 (ert-deftest python-nav-forward-sexp-3 ()
2343 (python-tests-with-temp-buffer
2345 from some_module import some_sub_module
2346 from another_module import another_sub_module
2348 def another_statement():
2349 pass
2351 (python-tests-look-at "some_module")
2352 (python-nav-forward-sexp)
2353 (should (looking-at " import"))
2354 (python-nav-forward-sexp)
2355 (should (looking-at " some_sub_module"))
2356 (python-nav-forward-sexp)
2357 (should (looking-at "$"))
2358 (should
2359 (save-excursion
2360 (back-to-indentation)
2361 (looking-at
2362 "from some_module import some_sub_module")))
2363 (python-nav-forward-sexp)
2364 (should (looking-at "$"))
2365 (should
2366 (save-excursion
2367 (back-to-indentation)
2368 (looking-at
2369 "from another_module import another_sub_module")))
2370 (python-nav-forward-sexp)
2371 (should (looking-at "$"))
2372 (should
2373 (save-excursion
2374 (back-to-indentation)
2375 (looking-at
2376 "pass")))
2377 (python-nav-forward-sexp -1)
2378 (should (looking-at "def another_statement():"))
2379 (python-nav-forward-sexp -1)
2380 (should (looking-at "from another_module import another_sub_module"))
2381 (python-nav-forward-sexp -1)
2382 (should (looking-at "from some_module import some_sub_module"))))
2384 (ert-deftest python-nav-forward-sexp-safe-1 ()
2385 (python-tests-with-temp-buffer
2387 profile = Profile.objects.create(user=request.user)
2388 profile.notify()
2390 (python-tests-look-at "profile =")
2391 (python-nav-forward-sexp-safe 1)
2392 (should (looking-at "$"))
2393 (beginning-of-line 1)
2394 (python-tests-look-at "user=request.user")
2395 (python-nav-forward-sexp-safe -1)
2396 (should (looking-at "(user=request.user)"))
2397 (python-nav-forward-sexp-safe -4)
2398 (should (looking-at "profile ="))
2399 (python-tests-look-at "user=request.user")
2400 (python-nav-forward-sexp-safe 3)
2401 (should (looking-at ")"))
2402 (python-nav-forward-sexp-safe 1)
2403 (should (looking-at "$"))
2404 (python-nav-forward-sexp-safe 1)
2405 (should (looking-at "$"))))
2407 (ert-deftest python-nav-up-list-1 ()
2408 (python-tests-with-temp-buffer
2410 def f():
2411 if True:
2412 return [i for i in range(3)]
2414 (python-tests-look-at "3)]")
2415 (python-nav-up-list)
2416 (should (looking-at "]"))
2417 (python-nav-up-list)
2418 (should (looking-at "$"))))
2420 (ert-deftest python-nav-backward-up-list-1 ()
2421 :expected-result :failed
2422 (python-tests-with-temp-buffer
2424 def f():
2425 if True:
2426 return [i for i in range(3)]
2428 (python-tests-look-at "3)]")
2429 (python-nav-backward-up-list)
2430 (should (looking-at "(3)\\]"))
2431 (python-nav-backward-up-list)
2432 (should (looking-at
2433 "\\[i for i in range(3)\\]"))
2434 ;; FIXME: Need to move to beginning-of-statement.
2435 (python-nav-backward-up-list)
2436 (should (looking-at
2437 "return \\[i for i in range(3)\\]"))
2438 (python-nav-backward-up-list)
2439 (should (looking-at "if True:"))
2440 (python-nav-backward-up-list)
2441 (should (looking-at "def f():"))))
2443 (ert-deftest python-indent-dedent-line-backspace-1 ()
2444 "Check de-indentation on first call. Bug#18319."
2445 (python-tests-with-temp-buffer
2447 if True:
2448 x ()
2449 if False:
2451 (python-tests-look-at "if False:")
2452 (call-interactively #'python-indent-dedent-line-backspace)
2453 (should (zerop (current-indentation)))
2454 ;; XXX: This should be a call to `undo' but it's triggering errors.
2455 (insert " ")
2456 (should (= (current-indentation) 4))
2457 (call-interactively #'python-indent-dedent-line-backspace)
2458 (should (zerop (current-indentation)))))
2460 (ert-deftest python-indent-dedent-line-backspace-2 ()
2461 "Check de-indentation with tabs. Bug#19730."
2462 (let ((tab-width 8))
2463 (python-tests-with-temp-buffer
2465 if x:
2466 \tabcdefg
2468 (python-tests-look-at "abcdefg")
2469 (goto-char (line-end-position))
2470 (call-interactively #'python-indent-dedent-line-backspace)
2471 (should
2472 (string= (buffer-substring-no-properties
2473 (line-beginning-position) (line-end-position))
2474 "\tabcdef")))))
2476 (ert-deftest python-indent-dedent-line-backspace-3 ()
2477 "Paranoid check of de-indentation with tabs. Bug#19730."
2478 (let ((tab-width 8))
2479 (python-tests-with-temp-buffer
2481 if x:
2482 \tif y:
2483 \t abcdefg
2485 (python-tests-look-at "abcdefg")
2486 (goto-char (line-end-position))
2487 (call-interactively #'python-indent-dedent-line-backspace)
2488 (should
2489 (string= (buffer-substring-no-properties
2490 (line-beginning-position) (line-end-position))
2491 "\t abcdef"))
2492 (back-to-indentation)
2493 (call-interactively #'python-indent-dedent-line-backspace)
2494 (should
2495 (string= (buffer-substring-no-properties
2496 (line-beginning-position) (line-end-position))
2497 "\tabcdef"))
2498 (call-interactively #'python-indent-dedent-line-backspace)
2499 (should
2500 (string= (buffer-substring-no-properties
2501 (line-beginning-position) (line-end-position))
2502 " abcdef"))
2503 (call-interactively #'python-indent-dedent-line-backspace)
2504 (should
2505 (string= (buffer-substring-no-properties
2506 (line-beginning-position) (line-end-position))
2507 "abcdef")))))
2509 (ert-deftest python-bob-infloop-avoid ()
2510 "Test that strings at BOB don't confuse syntax analysis. Bug#24905"
2511 (python-tests-with-temp-buffer
2512 " \"\n"
2513 (goto-char (point-min))
2514 (call-interactively 'font-lock-fontify-buffer)))
2517 ;;; Shell integration
2519 (defvar python-tests-shell-interpreter "python")
2521 (ert-deftest python-shell-get-process-name-1 ()
2522 "Check process name calculation sans `buffer-file-name'."
2523 (python-tests-with-temp-buffer
2525 (should (string= (python-shell-get-process-name nil)
2526 python-shell-buffer-name))
2527 (should (string= (python-shell-get-process-name t)
2528 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2530 (ert-deftest python-shell-get-process-name-2 ()
2531 "Check process name calculation with `buffer-file-name'."
2532 (python-tests-with-temp-file
2534 ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
2535 ;; should be respected.
2536 (should (string= (python-shell-get-process-name nil)
2537 python-shell-buffer-name))
2538 (should (string=
2539 (python-shell-get-process-name t)
2540 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2542 (ert-deftest python-shell-internal-get-process-name-1 ()
2543 "Check the internal process name is buffer-unique sans `buffer-file-name'."
2544 (python-tests-with-temp-buffer
2546 (should (string= (python-shell-internal-get-process-name)
2547 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2549 (ert-deftest python-shell-internal-get-process-name-2 ()
2550 "Check the internal process name is buffer-unique with `buffer-file-name'."
2551 (python-tests-with-temp-file
2553 (should (string= (python-shell-internal-get-process-name)
2554 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2556 (ert-deftest python-shell-calculate-pythonpath-1 ()
2557 "Test PYTHONPATH calculation."
2558 (let ((process-environment '("PYTHONPATH=/path0"))
2559 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2560 (should (string= (python-shell-calculate-pythonpath)
2561 (concat "/path1" path-separator
2562 "/path2" path-separator "/path0")))))
2564 (ert-deftest python-shell-calculate-pythonpath-2 ()
2565 "Test existing paths are moved to front."
2566 (let ((process-environment
2567 (list (concat "PYTHONPATH=/path0" path-separator "/path1")))
2568 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2569 (should (string= (python-shell-calculate-pythonpath)
2570 (concat "/path1" path-separator
2571 "/path2" path-separator "/path0")))))
2573 (ert-deftest python-shell-calculate-process-environment-1 ()
2574 "Test `python-shell-process-environment' modification."
2575 (let* ((python-shell-process-environment
2576 '("TESTVAR1=value1" "TESTVAR2=value2"))
2577 (process-environment (python-shell-calculate-process-environment)))
2578 (should (equal (getenv "TESTVAR1") "value1"))
2579 (should (equal (getenv "TESTVAR2") "value2"))))
2581 (ert-deftest python-shell-calculate-process-environment-2 ()
2582 "Test `python-shell-extra-pythonpaths' modification."
2583 (let* ((process-environment process-environment)
2584 (original-pythonpath (setenv "PYTHONPATH" "/path0"))
2585 (python-shell-extra-pythonpaths '("/path1" "/path2"))
2586 (process-environment (python-shell-calculate-process-environment)))
2587 (should (equal (getenv "PYTHONPATH")
2588 (concat "/path1" path-separator
2589 "/path2" path-separator "/path0")))))
2591 (ert-deftest python-shell-calculate-process-environment-3 ()
2592 "Test `python-shell-virtualenv-root' modification."
2593 (let* ((python-shell-virtualenv-root "/env")
2594 (process-environment
2595 (let ((process-environment process-environment))
2596 (setenv "PYTHONHOME" "/home")
2597 (setenv "VIRTUAL_ENV")
2598 (python-shell-calculate-process-environment))))
2599 (should (not (getenv "PYTHONHOME")))
2600 (should (string= (getenv "VIRTUAL_ENV") "/env"))))
2602 (ert-deftest python-shell-calculate-process-environment-4 ()
2603 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is non-nil."
2604 (let* ((python-shell-unbuffered t)
2605 (process-environment
2606 (let ((process-environment process-environment))
2607 (setenv "PYTHONUNBUFFERED")
2608 (python-shell-calculate-process-environment))))
2609 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2611 (ert-deftest python-shell-calculate-process-environment-5 ()
2612 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is nil."
2613 (let* ((python-shell-unbuffered nil)
2614 (process-environment
2615 (let ((process-environment process-environment))
2616 (setenv "PYTHONUNBUFFERED")
2617 (python-shell-calculate-process-environment))))
2618 (should (not (getenv "PYTHONUNBUFFERED")))))
2620 (ert-deftest python-shell-calculate-process-environment-6 ()
2621 "Test PYTHONUNBUFFERED=1 when `python-shell-unbuffered' is nil."
2622 (let* ((python-shell-unbuffered nil)
2623 (process-environment
2624 (let ((process-environment process-environment))
2625 (setenv "PYTHONUNBUFFERED" "1")
2626 (python-shell-calculate-process-environment))))
2627 ;; User default settings must remain untouched:
2628 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2630 (ert-deftest python-shell-calculate-process-environment-7 ()
2631 "Test no side-effects on `process-environment'."
2632 (let* ((python-shell-process-environment
2633 '("TESTVAR1=value1" "TESTVAR2=value2"))
2634 (python-shell-virtualenv-root (or (getenv "VIRTUAL_ENV") "/env"))
2635 (python-shell-unbuffered t)
2636 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2637 (original-process-environment (copy-sequence process-environment)))
2638 (python-shell-calculate-process-environment)
2639 (should (equal process-environment original-process-environment))))
2641 (ert-deftest python-shell-calculate-process-environment-8 ()
2642 "Test no side-effects on `tramp-remote-process-environment'."
2643 (let* ((default-directory "/ssh::/example/dir/")
2644 (python-shell-process-environment
2645 '("TESTVAR1=value1" "TESTVAR2=value2"))
2646 (python-shell-virtualenv-root "/env")
2647 (python-shell-unbuffered t)
2648 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2649 (original-process-environment
2650 (copy-sequence tramp-remote-process-environment)))
2651 (python-shell-calculate-process-environment)
2652 (should (equal tramp-remote-process-environment original-process-environment))))
2654 (ert-deftest python-shell-calculate-exec-path-1 ()
2655 "Test `python-shell-exec-path' modification."
2656 (let* ((exec-path '("/path0"))
2657 (python-shell-exec-path '("/path1" "/path2"))
2658 (new-exec-path (python-shell-calculate-exec-path)))
2659 (should (equal new-exec-path '("/path1" "/path2" "/path0")))))
2661 (ert-deftest python-shell-calculate-exec-path-2 ()
2662 "Test `python-shell-virtualenv-root' modification."
2663 (let* ((exec-path '("/path0"))
2664 (python-shell-virtualenv-root "/env")
2665 (new-exec-path (python-shell-calculate-exec-path)))
2666 (should (equal new-exec-path
2667 (list (expand-file-name "/env/bin") "/path0")))))
2669 (ert-deftest python-shell-calculate-exec-path-3 ()
2670 "Test complete `python-shell-virtualenv-root' modification."
2671 (let* ((exec-path '("/path0"))
2672 (python-shell-exec-path '("/path1" "/path2"))
2673 (python-shell-virtualenv-root "/env")
2674 (new-exec-path (python-shell-calculate-exec-path)))
2675 (should (equal new-exec-path
2676 (list (expand-file-name "/env/bin")
2677 "/path1" "/path2" "/path0")))))
2679 (ert-deftest python-shell-calculate-exec-path-4 ()
2680 "Test complete `python-shell-virtualenv-root' with remote."
2681 (let* ((default-directory "/ssh::/example/dir/")
2682 (python-shell-remote-exec-path '("/path0"))
2683 (python-shell-exec-path '("/path1" "/path2"))
2684 (python-shell-virtualenv-root "/env")
2685 (new-exec-path (python-shell-calculate-exec-path)))
2686 (should (equal new-exec-path
2687 (list (expand-file-name "/env/bin")
2688 "/path1" "/path2" "/path0")))))
2690 (ert-deftest python-shell-calculate-exec-path-5 ()
2691 "Test no side-effects on `exec-path'."
2692 (let* ((exec-path '("/path0"))
2693 (python-shell-exec-path '("/path1" "/path2"))
2694 (python-shell-virtualenv-root "/env")
2695 (original-exec-path (copy-sequence exec-path)))
2696 (python-shell-calculate-exec-path)
2697 (should (equal exec-path original-exec-path))))
2699 (ert-deftest python-shell-calculate-exec-path-6 ()
2700 "Test no side-effects on `python-shell-remote-exec-path'."
2701 (let* ((default-directory "/ssh::/example/dir/")
2702 (python-shell-remote-exec-path '("/path0"))
2703 (python-shell-exec-path '("/path1" "/path2"))
2704 (python-shell-virtualenv-root "/env")
2705 (original-exec-path (copy-sequence python-shell-remote-exec-path)))
2706 (python-shell-calculate-exec-path)
2707 (should (equal python-shell-remote-exec-path original-exec-path))))
2709 (ert-deftest python-shell-with-environment-1 ()
2710 "Test environment with local `default-directory'."
2711 (let* ((exec-path '("/path0"))
2712 (python-shell-exec-path '("/path1" "/path2"))
2713 (original-exec-path exec-path)
2714 (python-shell-virtualenv-root "/env"))
2715 (python-shell-with-environment
2716 (should (equal exec-path
2717 (list (expand-file-name "/env/bin")
2718 "/path1" "/path2" "/path0")))
2719 (should (not (getenv "PYTHONHOME")))
2720 (should (string= (getenv "VIRTUAL_ENV") "/env")))
2721 (should (equal exec-path original-exec-path))))
2723 (ert-deftest python-shell-with-environment-2 ()
2724 "Test environment with remote `default-directory'."
2725 (let* ((default-directory "/ssh::/example/dir/")
2726 (python-shell-remote-exec-path '("/remote1" "/remote2"))
2727 (python-shell-exec-path '("/path1" "/path2"))
2728 (tramp-remote-process-environment '("EMACS=t"))
2729 (original-process-environment (copy-sequence tramp-remote-process-environment))
2730 (python-shell-virtualenv-root "/env"))
2731 (python-shell-with-environment
2732 (should (equal (python-shell-calculate-exec-path)
2733 (list (expand-file-name "/env/bin")
2734 "/path1" "/path2" "/remote1" "/remote2")))
2735 (let ((process-environment (python-shell-calculate-process-environment)))
2736 (should (not (getenv "PYTHONHOME")))
2737 (should (string= (getenv "VIRTUAL_ENV") "/env"))
2738 (should (equal tramp-remote-process-environment process-environment))))
2739 (should (equal tramp-remote-process-environment original-process-environment))))
2741 (ert-deftest python-shell-with-environment-3 ()
2742 "Test `python-shell-with-environment' is idempotent."
2743 (let* ((python-shell-extra-pythonpaths '("/example/dir/"))
2744 (python-shell-exec-path '("path1" "path2"))
2745 (python-shell-virtualenv-root "/home/user/env")
2746 (single-call
2747 (python-shell-with-environment
2748 (list exec-path process-environment)))
2749 (nested-call
2750 (python-shell-with-environment
2751 (python-shell-with-environment
2752 (list exec-path process-environment)))))
2753 (should (equal single-call nested-call))))
2755 (ert-deftest python-shell-make-comint-1 ()
2756 "Check comint creation for global shell buffer."
2757 (skip-unless (executable-find python-tests-shell-interpreter))
2758 ;; The interpreter can get killed too quickly to allow it to clean
2759 ;; up the tempfiles that the default python-shell-setup-codes create,
2760 ;; so it leaves tempfiles behind, which is a minor irritation.
2761 (let* ((python-shell-setup-codes nil)
2762 (python-shell-interpreter
2763 (executable-find python-tests-shell-interpreter))
2764 (proc-name (python-shell-get-process-name nil))
2765 (shell-buffer
2766 (python-tests-with-temp-buffer
2767 "" (python-shell-make-comint
2768 (python-shell-calculate-command) proc-name)))
2769 (process (get-buffer-process shell-buffer)))
2770 (unwind-protect
2771 (progn
2772 (set-process-query-on-exit-flag process nil)
2773 (should (process-live-p process))
2774 (with-current-buffer shell-buffer
2775 (should (eq major-mode 'inferior-python-mode))
2776 (should (string= (buffer-name) (format "*%s*" proc-name)))))
2777 (kill-buffer shell-buffer))))
2779 (ert-deftest python-shell-make-comint-2 ()
2780 "Check comint creation for internal shell buffer."
2781 (skip-unless (executable-find python-tests-shell-interpreter))
2782 (let* ((python-shell-setup-codes nil)
2783 (python-shell-interpreter
2784 (executable-find python-tests-shell-interpreter))
2785 (proc-name (python-shell-internal-get-process-name))
2786 (shell-buffer
2787 (python-tests-with-temp-buffer
2788 "" (python-shell-make-comint
2789 (python-shell-calculate-command) proc-name nil t)))
2790 (process (get-buffer-process shell-buffer)))
2791 (unwind-protect
2792 (progn
2793 (set-process-query-on-exit-flag process nil)
2794 (should (process-live-p process))
2795 (with-current-buffer shell-buffer
2796 (should (eq major-mode 'inferior-python-mode))
2797 (should (string= (buffer-name) (format " *%s*" proc-name)))))
2798 (kill-buffer shell-buffer))))
2800 (ert-deftest python-shell-make-comint-3 ()
2801 "Check comint creation with overridden python interpreter and args.
2802 The command passed to `python-shell-make-comint' as argument must
2803 locally override global values set in `python-shell-interpreter'
2804 and `python-shell-interpreter-args' in the new shell buffer."
2805 (skip-unless (executable-find python-tests-shell-interpreter))
2806 (let* ((python-shell-setup-codes nil)
2807 (python-shell-interpreter "interpreter")
2808 (python-shell-interpreter-args "--some-args")
2809 (proc-name (python-shell-get-process-name nil))
2810 (interpreter-override
2811 (concat (executable-find python-tests-shell-interpreter) " " "-i"))
2812 (shell-buffer
2813 (python-tests-with-temp-buffer
2814 "" (python-shell-make-comint interpreter-override proc-name nil)))
2815 (process (get-buffer-process shell-buffer)))
2816 (unwind-protect
2817 (progn
2818 (set-process-query-on-exit-flag process nil)
2819 (should (process-live-p process))
2820 (with-current-buffer shell-buffer
2821 (should (eq major-mode 'inferior-python-mode))
2822 (should (file-equal-p
2823 python-shell-interpreter
2824 (executable-find python-tests-shell-interpreter)))
2825 (should (string= python-shell-interpreter-args "-i"))))
2826 (kill-buffer shell-buffer))))
2828 (ert-deftest python-shell-make-comint-4 ()
2829 "Check shell calculated prompts regexps are set."
2830 (skip-unless (executable-find python-tests-shell-interpreter))
2831 (let* ((process-environment process-environment)
2832 (python-shell-setup-codes nil)
2833 (python-shell-interpreter
2834 (executable-find python-tests-shell-interpreter))
2835 (python-shell-interpreter-args "-i")
2836 (python-shell--prompt-calculated-input-regexp nil)
2837 (python-shell--prompt-calculated-output-regexp nil)
2838 (python-shell-prompt-detect-enabled t)
2839 (python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2840 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2841 (python-shell-prompt-regexp "in")
2842 (python-shell-prompt-block-regexp "block")
2843 (python-shell-prompt-pdb-regexp "pdf")
2844 (python-shell-prompt-output-regexp "output")
2845 (startup-code (concat "import sys\n"
2846 "sys.ps1 = 'py> '\n"
2847 "sys.ps2 = '..> '\n"
2848 "sys.ps3 = 'out '\n"))
2849 (startup-file (python-shell--save-temp-file startup-code))
2850 (proc-name (python-shell-get-process-name nil))
2851 (shell-buffer
2852 (progn
2853 (setenv "PYTHONSTARTUP" startup-file)
2854 (python-tests-with-temp-buffer
2855 "" (python-shell-make-comint
2856 (python-shell-calculate-command) proc-name nil))))
2857 (process (get-buffer-process shell-buffer)))
2858 (unwind-protect
2859 (progn
2860 (set-process-query-on-exit-flag process nil)
2861 (should (process-live-p process))
2862 (with-current-buffer shell-buffer
2863 (should (eq major-mode 'inferior-python-mode))
2864 (should (string=
2865 python-shell--prompt-calculated-input-regexp
2866 (concat "^\\(extralargeinputprompt\\|\\.\\.> \\|"
2867 "block\\|py> \\|pdf\\|sml\\|in\\)")))
2868 (should (string=
2869 python-shell--prompt-calculated-output-regexp
2870 "^\\(extralargeoutputprompt\\|output\\|out \\|sml\\)"))))
2871 (delete-file startup-file)
2872 (kill-buffer shell-buffer))))
2874 (ert-deftest python-shell-get-process-1 ()
2875 "Check dedicated shell process preference over global."
2876 (skip-unless (executable-find python-tests-shell-interpreter))
2877 (python-tests-with-temp-file
2879 (let* ((python-shell-setup-codes nil)
2880 (python-shell-interpreter
2881 (executable-find python-tests-shell-interpreter))
2882 (global-proc-name (python-shell-get-process-name nil))
2883 (dedicated-proc-name (python-shell-get-process-name t))
2884 (global-shell-buffer
2885 (python-shell-make-comint
2886 (python-shell-calculate-command) global-proc-name))
2887 (dedicated-shell-buffer
2888 (python-shell-make-comint
2889 (python-shell-calculate-command) dedicated-proc-name))
2890 (global-process (get-buffer-process global-shell-buffer))
2891 (dedicated-process (get-buffer-process dedicated-shell-buffer)))
2892 (unwind-protect
2893 (progn
2894 (set-process-query-on-exit-flag global-process nil)
2895 (set-process-query-on-exit-flag dedicated-process nil)
2896 ;; Prefer dedicated if global also exists.
2897 (should (equal (python-shell-get-process) dedicated-process))
2898 (kill-buffer dedicated-shell-buffer)
2899 ;; If there's only global, use it.
2900 (should (equal (python-shell-get-process) global-process))
2901 (kill-buffer global-shell-buffer)
2902 ;; No buffer available.
2903 (should (not (python-shell-get-process))))
2904 (ignore-errors (kill-buffer global-shell-buffer))
2905 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2907 (ert-deftest python-shell-internal-get-or-create-process-1 ()
2908 "Check internal shell process creation fallback."
2909 (skip-unless (executable-find python-tests-shell-interpreter))
2910 (python-tests-with-temp-file
2912 (should (not (process-live-p (python-shell-internal-get-process-name))))
2913 (let* ((python-shell-interpreter
2914 (executable-find python-tests-shell-interpreter))
2915 (internal-process-name (python-shell-internal-get-process-name))
2916 (internal-process (python-shell-internal-get-or-create-process))
2917 (internal-shell-buffer (process-buffer internal-process)))
2918 (unwind-protect
2919 (progn
2920 (set-process-query-on-exit-flag internal-process nil)
2921 (should (equal (process-name internal-process)
2922 internal-process-name))
2923 (should (equal internal-process
2924 (python-shell-internal-get-or-create-process)))
2925 ;; Assert the internal process is not a user process
2926 (should (not (python-shell-get-process)))
2927 (kill-buffer internal-shell-buffer))
2928 (ignore-errors (kill-buffer internal-shell-buffer))))))
2930 (ert-deftest python-shell-prompt-detect-1 ()
2931 "Check prompt autodetection."
2932 (skip-unless (executable-find python-tests-shell-interpreter))
2933 (let ((process-environment process-environment))
2934 ;; Ensure no startup file is enabled
2935 (setenv "PYTHONSTARTUP" "")
2936 (should python-shell-prompt-detect-enabled)
2937 (should (equal (python-shell-prompt-detect) '(">>> " "... " "")))))
2939 (ert-deftest python-shell-prompt-detect-2 ()
2940 "Check prompt autodetection with startup file. Bug#17370."
2941 (skip-unless (executable-find python-tests-shell-interpreter))
2942 (let* ((process-environment process-environment)
2943 (startup-code (concat "import sys\n"
2944 "sys.ps1 = 'py> '\n"
2945 "sys.ps2 = '..> '\n"
2946 "sys.ps3 = 'out '\n"))
2947 (startup-file (python-shell--save-temp-file startup-code)))
2948 (unwind-protect
2949 (progn
2950 ;; Ensure startup file is enabled
2951 (setenv "PYTHONSTARTUP" startup-file)
2952 (should python-shell-prompt-detect-enabled)
2953 (should (equal (python-shell-prompt-detect) '("py> " "..> " "out "))))
2954 (ignore-errors (delete-file startup-file)))))
2956 (ert-deftest python-shell-prompt-detect-3 ()
2957 "Check prompts are not autodetected when feature is disabled."
2958 (skip-unless (executable-find python-tests-shell-interpreter))
2959 (let ((process-environment process-environment)
2960 (python-shell-prompt-detect-enabled nil))
2961 ;; Ensure no startup file is enabled
2962 (should (not python-shell-prompt-detect-enabled))
2963 (should (not (python-shell-prompt-detect)))))
2965 (ert-deftest python-shell-prompt-detect-4 ()
2966 "Check warning is shown when detection fails."
2967 (skip-unless (executable-find python-tests-shell-interpreter))
2968 (let* ((process-environment process-environment)
2969 ;; Trigger failure by removing prompts in the startup file
2970 (startup-code (concat "import sys\n"
2971 "sys.ps1 = ''\n"
2972 "sys.ps2 = ''\n"
2973 "sys.ps3 = ''\n"))
2974 (startup-file (python-shell--save-temp-file startup-code)))
2975 (unwind-protect
2976 (progn
2977 (kill-buffer (get-buffer-create "*Warnings*"))
2978 (should (not (get-buffer "*Warnings*")))
2979 (setenv "PYTHONSTARTUP" startup-file)
2980 (should python-shell-prompt-detect-failure-warning)
2981 (should python-shell-prompt-detect-enabled)
2982 (should (not (python-shell-prompt-detect)))
2983 (should (get-buffer "*Warnings*")))
2984 (ignore-errors (delete-file startup-file)))))
2986 (ert-deftest python-shell-prompt-detect-5 ()
2987 "Check disabled warnings are not shown when detection fails."
2988 (skip-unless (executable-find python-tests-shell-interpreter))
2989 (let* ((process-environment process-environment)
2990 (startup-code (concat "import sys\n"
2991 "sys.ps1 = ''\n"
2992 "sys.ps2 = ''\n"
2993 "sys.ps3 = ''\n"))
2994 (startup-file (python-shell--save-temp-file startup-code))
2995 (python-shell-prompt-detect-failure-warning nil))
2996 (unwind-protect
2997 (progn
2998 (kill-buffer (get-buffer-create "*Warnings*"))
2999 (should (not (get-buffer "*Warnings*")))
3000 (setenv "PYTHONSTARTUP" startup-file)
3001 (should (not python-shell-prompt-detect-failure-warning))
3002 (should python-shell-prompt-detect-enabled)
3003 (should (not (python-shell-prompt-detect)))
3004 (should (not (get-buffer "*Warnings*"))))
3005 (ignore-errors (delete-file startup-file)))))
3007 (ert-deftest python-shell-prompt-detect-6 ()
3008 "Warnings are not shown when detection is disabled."
3009 (skip-unless (executable-find python-tests-shell-interpreter))
3010 (let* ((process-environment process-environment)
3011 (startup-code (concat "import sys\n"
3012 "sys.ps1 = ''\n"
3013 "sys.ps2 = ''\n"
3014 "sys.ps3 = ''\n"))
3015 (startup-file (python-shell--save-temp-file startup-code))
3016 (python-shell-prompt-detect-failure-warning t)
3017 (python-shell-prompt-detect-enabled nil))
3018 (unwind-protect
3019 (progn
3020 (kill-buffer (get-buffer-create "*Warnings*"))
3021 (should (not (get-buffer "*Warnings*")))
3022 (setenv "PYTHONSTARTUP" startup-file)
3023 (should python-shell-prompt-detect-failure-warning)
3024 (should (not python-shell-prompt-detect-enabled))
3025 (should (not (python-shell-prompt-detect)))
3026 (should (not (get-buffer "*Warnings*"))))
3027 (ignore-errors (delete-file startup-file)))))
3029 (ert-deftest python-shell-prompt-validate-regexps-1 ()
3030 "Check `python-shell-prompt-input-regexps' are validated."
3031 (let* ((python-shell-prompt-input-regexps '("\\("))
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-input-regexps'")))))
3039 (ert-deftest python-shell-prompt-validate-regexps-2 ()
3040 "Check `python-shell-prompt-output-regexps' are validated."
3041 (let* ((python-shell-prompt-output-regexps '("\\("))
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-regexps'")))))
3049 (ert-deftest python-shell-prompt-validate-regexps-3 ()
3050 "Check `python-shell-prompt-regexp' is validated."
3051 (let* ((python-shell-prompt-regexp "\\(")
3052 (error-data (should-error (python-shell-prompt-validate-regexps)
3053 :type 'user-error)))
3054 (should
3055 (string= (cadr error-data)
3056 (format-message
3057 "Invalid regexp \\( in `python-shell-prompt-regexp'")))))
3059 (ert-deftest python-shell-prompt-validate-regexps-4 ()
3060 "Check `python-shell-prompt-block-regexp' is validated."
3061 (let* ((python-shell-prompt-block-regexp "\\(")
3062 (error-data (should-error (python-shell-prompt-validate-regexps)
3063 :type 'user-error)))
3064 (should
3065 (string= (cadr error-data)
3066 (format-message
3067 "Invalid regexp \\( in `python-shell-prompt-block-regexp'")))))
3069 (ert-deftest python-shell-prompt-validate-regexps-5 ()
3070 "Check `python-shell-prompt-pdb-regexp' is validated."
3071 (let* ((python-shell-prompt-pdb-regexp "\\(")
3072 (error-data (should-error (python-shell-prompt-validate-regexps)
3073 :type 'user-error)))
3074 (should
3075 (string= (cadr error-data)
3076 (format-message
3077 "Invalid regexp \\( in `python-shell-prompt-pdb-regexp'")))))
3079 (ert-deftest python-shell-prompt-validate-regexps-6 ()
3080 "Check `python-shell-prompt-output-regexp' is validated."
3081 (let* ((python-shell-prompt-output-regexp "\\(")
3082 (error-data (should-error (python-shell-prompt-validate-regexps)
3083 :type 'user-error)))
3084 (should
3085 (string= (cadr error-data)
3086 (format-message
3087 "Invalid regexp \\( in `python-shell-prompt-output-regexp'")))))
3089 (ert-deftest python-shell-prompt-validate-regexps-7 ()
3090 "Check default regexps are valid."
3091 ;; should not signal error
3092 (python-shell-prompt-validate-regexps))
3094 (ert-deftest python-shell-prompt-set-calculated-regexps-1 ()
3095 "Check regexps are validated."
3096 (let* ((python-shell-prompt-output-regexp '("\\("))
3097 (python-shell--prompt-calculated-input-regexp nil)
3098 (python-shell--prompt-calculated-output-regexp nil)
3099 (python-shell-prompt-detect-enabled nil)
3100 (error-data (should-error (python-shell-prompt-set-calculated-regexps)
3101 :type 'user-error)))
3102 (should
3103 (string= (cadr error-data)
3104 (format-message
3105 "Invalid regexp \\( in `python-shell-prompt-output-regexp'")))))
3107 (ert-deftest python-shell-prompt-set-calculated-regexps-2 ()
3108 "Check `python-shell-prompt-input-regexps' are set."
3109 (let* ((python-shell-prompt-input-regexps '("my" "prompt"))
3110 (python-shell-prompt-output-regexps '(""))
3111 (python-shell-prompt-regexp "")
3112 (python-shell-prompt-block-regexp "")
3113 (python-shell-prompt-pdb-regexp "")
3114 (python-shell-prompt-output-regexp "")
3115 (python-shell--prompt-calculated-input-regexp nil)
3116 (python-shell--prompt-calculated-output-regexp nil)
3117 (python-shell-prompt-detect-enabled nil))
3118 (python-shell-prompt-set-calculated-regexps)
3119 (should (string= python-shell--prompt-calculated-input-regexp
3120 "^\\(prompt\\|my\\|\\)"))))
3122 (ert-deftest python-shell-prompt-set-calculated-regexps-3 ()
3123 "Check `python-shell-prompt-output-regexps' are set."
3124 (let* ((python-shell-prompt-input-regexps '(""))
3125 (python-shell-prompt-output-regexps '("my" "prompt"))
3126 (python-shell-prompt-regexp "")
3127 (python-shell-prompt-block-regexp "")
3128 (python-shell-prompt-pdb-regexp "")
3129 (python-shell-prompt-output-regexp "")
3130 (python-shell--prompt-calculated-input-regexp nil)
3131 (python-shell--prompt-calculated-output-regexp nil)
3132 (python-shell-prompt-detect-enabled nil))
3133 (python-shell-prompt-set-calculated-regexps)
3134 (should (string= python-shell--prompt-calculated-output-regexp
3135 "^\\(prompt\\|my\\|\\)"))))
3137 (ert-deftest python-shell-prompt-set-calculated-regexps-4 ()
3138 "Check user defined prompts are set."
3139 (let* ((python-shell-prompt-input-regexps '(""))
3140 (python-shell-prompt-output-regexps '(""))
3141 (python-shell-prompt-regexp "prompt")
3142 (python-shell-prompt-block-regexp "block")
3143 (python-shell-prompt-pdb-regexp "pdb")
3144 (python-shell-prompt-output-regexp "output")
3145 (python-shell--prompt-calculated-input-regexp nil)
3146 (python-shell--prompt-calculated-output-regexp nil)
3147 (python-shell-prompt-detect-enabled nil))
3148 (python-shell-prompt-set-calculated-regexps)
3149 (should (string= python-shell--prompt-calculated-input-regexp
3150 "^\\(prompt\\|block\\|pdb\\|\\)"))
3151 (should (string= python-shell--prompt-calculated-output-regexp
3152 "^\\(output\\|\\)"))))
3154 (ert-deftest python-shell-prompt-set-calculated-regexps-5 ()
3155 "Check order of regexps (larger first)."
3156 (let* ((python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
3157 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
3158 (python-shell-prompt-regexp "in")
3159 (python-shell-prompt-block-regexp "block")
3160 (python-shell-prompt-pdb-regexp "pdf")
3161 (python-shell-prompt-output-regexp "output")
3162 (python-shell--prompt-calculated-input-regexp nil)
3163 (python-shell--prompt-calculated-output-regexp nil)
3164 (python-shell-prompt-detect-enabled nil))
3165 (python-shell-prompt-set-calculated-regexps)
3166 (should (string= python-shell--prompt-calculated-input-regexp
3167 "^\\(extralargeinputprompt\\|block\\|pdf\\|sml\\|in\\)"))
3168 (should (string= python-shell--prompt-calculated-output-regexp
3169 "^\\(extralargeoutputprompt\\|output\\|sml\\)"))))
3171 (ert-deftest python-shell-prompt-set-calculated-regexps-6 ()
3172 "Check detected prompts are included `regexp-quote'd."
3173 (skip-unless (executable-find python-tests-shell-interpreter))
3174 (let* ((python-shell-prompt-input-regexps '(""))
3175 (python-shell-prompt-output-regexps '(""))
3176 (python-shell-prompt-regexp "")
3177 (python-shell-prompt-block-regexp "")
3178 (python-shell-prompt-pdb-regexp "")
3179 (python-shell-prompt-output-regexp "")
3180 (python-shell--prompt-calculated-input-regexp nil)
3181 (python-shell--prompt-calculated-output-regexp nil)
3182 (python-shell-prompt-detect-enabled t)
3183 (process-environment process-environment)
3184 (startup-code (concat "import sys\n"
3185 "sys.ps1 = 'p.> '\n"
3186 "sys.ps2 = '..> '\n"
3187 "sys.ps3 = 'o.t '\n"))
3188 (startup-file (python-shell--save-temp-file startup-code)))
3189 (unwind-protect
3190 (progn
3191 (setenv "PYTHONSTARTUP" startup-file)
3192 (python-shell-prompt-set-calculated-regexps)
3193 (should (string= python-shell--prompt-calculated-input-regexp
3194 "^\\(\\.\\.> \\|p\\.> \\|\\)"))
3195 (should (string= python-shell--prompt-calculated-output-regexp
3196 "^\\(o\\.t \\|\\)")))
3197 (ignore-errors (delete-file startup-file)))))
3199 (ert-deftest python-shell-buffer-substring-1 ()
3200 "Selecting a substring of the whole buffer must match its contents."
3201 (python-tests-with-temp-buffer
3203 class Foo(models.Model):
3204 pass
3207 class Bar(models.Model):
3208 pass
3210 (should (string= (buffer-string)
3211 (python-shell-buffer-substring (point-min) (point-max))))))
3213 (ert-deftest python-shell-buffer-substring-2 ()
3214 "Main block should be removed if NOMAIN is non-nil."
3215 (python-tests-with-temp-buffer
3217 class Foo(models.Model):
3218 pass
3220 class Bar(models.Model):
3221 pass
3223 if __name__ == \"__main__\":
3224 foo = Foo()
3225 print (foo)
3227 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3229 class Foo(models.Model):
3230 pass
3232 class Bar(models.Model):
3233 pass
3238 "))))
3240 (ert-deftest python-shell-buffer-substring-3 ()
3241 "Main block should be removed if NOMAIN is non-nil."
3242 (python-tests-with-temp-buffer
3244 class Foo(models.Model):
3245 pass
3247 if __name__ == \"__main__\":
3248 foo = Foo()
3249 print (foo)
3251 class Bar(models.Model):
3252 pass
3254 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3256 class Foo(models.Model):
3257 pass
3263 class Bar(models.Model):
3264 pass
3265 "))))
3267 (ert-deftest python-shell-buffer-substring-4 ()
3268 "Coding cookie should be added for substrings."
3269 (python-tests-with-temp-buffer
3270 "# coding: latin-1
3272 class Foo(models.Model):
3273 pass
3275 if __name__ == \"__main__\":
3276 foo = Foo()
3277 print (foo)
3279 class Bar(models.Model):
3280 pass
3282 (should (string= (python-shell-buffer-substring
3283 (python-tests-look-at "class Foo(models.Model):")
3284 (progn (python-nav-forward-sexp) (point)))
3285 "# -*- coding: latin-1 -*-
3287 class Foo(models.Model):
3288 pass"))))
3290 (ert-deftest python-shell-buffer-substring-5 ()
3291 "The proper amount of blank lines is added for a substring."
3292 (python-tests-with-temp-buffer
3293 "# coding: latin-1
3295 class Foo(models.Model):
3296 pass
3298 if __name__ == \"__main__\":
3299 foo = Foo()
3300 print (foo)
3302 class Bar(models.Model):
3303 pass
3305 (should (string= (python-shell-buffer-substring
3306 (python-tests-look-at "class Bar(models.Model):")
3307 (progn (python-nav-forward-sexp) (point)))
3308 "# -*- coding: latin-1 -*-
3317 class Bar(models.Model):
3318 pass"))))
3320 (ert-deftest python-shell-buffer-substring-6 ()
3321 "Handle substring with coding cookie in the second line."
3322 (python-tests-with-temp-buffer
3324 # coding: latin-1
3326 class Foo(models.Model):
3327 pass
3329 if __name__ == \"__main__\":
3330 foo = Foo()
3331 print (foo)
3333 class Bar(models.Model):
3334 pass
3336 (should (string= (python-shell-buffer-substring
3337 (python-tests-look-at "# coding: latin-1")
3338 (python-tests-look-at "if __name__ == \"__main__\":"))
3339 "# -*- coding: latin-1 -*-
3342 class Foo(models.Model):
3343 pass
3345 "))))
3347 (ert-deftest python-shell-buffer-substring-7 ()
3348 "Ensure first coding cookie gets precedence."
3349 (python-tests-with-temp-buffer
3350 "# coding: utf-8
3351 # coding: latin-1
3353 class Foo(models.Model):
3354 pass
3356 if __name__ == \"__main__\":
3357 foo = Foo()
3358 print (foo)
3360 class Bar(models.Model):
3361 pass
3363 (should (string= (python-shell-buffer-substring
3364 (python-tests-look-at "# coding: latin-1")
3365 (python-tests-look-at "if __name__ == \"__main__\":"))
3366 "# -*- coding: utf-8 -*-
3369 class Foo(models.Model):
3370 pass
3372 "))))
3374 (ert-deftest python-shell-buffer-substring-8 ()
3375 "Ensure first coding cookie gets precedence when sending whole buffer."
3376 (python-tests-with-temp-buffer
3377 "# coding: utf-8
3378 # coding: latin-1
3380 class Foo(models.Model):
3381 pass
3383 (should (string= (python-shell-buffer-substring (point-min) (point-max))
3384 "# coding: utf-8
3387 class Foo(models.Model):
3388 pass
3389 "))))
3391 (ert-deftest python-shell-buffer-substring-9 ()
3392 "Check substring starting from `point-min'."
3393 (python-tests-with-temp-buffer
3394 "# coding: utf-8
3396 class Foo(models.Model):
3397 pass
3399 class Bar(models.Model):
3400 pass
3402 (should (string= (python-shell-buffer-substring
3403 (point-min)
3404 (python-tests-look-at "class Bar(models.Model):"))
3405 "# coding: utf-8
3407 class Foo(models.Model):
3408 pass
3410 "))))
3412 (ert-deftest python-shell-buffer-substring-10 ()
3413 "Check substring from partial block."
3414 (python-tests-with-temp-buffer
3416 def foo():
3417 print ('a')
3419 (should (string= (python-shell-buffer-substring
3420 (python-tests-look-at "print ('a')")
3421 (point-max))
3422 "if True:
3424 print ('a')
3425 "))))
3427 (ert-deftest python-shell-buffer-substring-11 ()
3428 "Check substring from partial block and point within indentation."
3429 (python-tests-with-temp-buffer
3431 def foo():
3432 print ('a')
3434 (should (string= (python-shell-buffer-substring
3435 (progn
3436 (python-tests-look-at "print ('a')")
3437 (backward-char 1)
3438 (point))
3439 (point-max))
3440 "if True:
3442 print ('a')
3443 "))))
3445 (ert-deftest python-shell-buffer-substring-12 ()
3446 "Check substring from partial block and point in whitespace."
3447 (python-tests-with-temp-buffer
3449 def foo():
3451 # Whitespace
3453 print ('a')
3455 (should (string= (python-shell-buffer-substring
3456 (python-tests-look-at "# Whitespace")
3457 (point-max))
3458 "if True:
3461 # Whitespace
3463 print ('a')
3464 "))))
3468 ;;; Shell completion
3470 (ert-deftest python-shell-completion-native-interpreter-disabled-p-1 ()
3471 (let* ((python-shell-completion-native-disabled-interpreters (list "pypy"))
3472 (python-shell-interpreter "/some/path/to/bin/pypy"))
3473 (should (python-shell-completion-native-interpreter-disabled-p))))
3478 ;;; PDB Track integration
3481 ;;; Symbol completion
3484 ;;; Fill paragraph
3487 ;;; Skeletons
3490 ;;; FFAP
3493 ;;; Code check
3496 ;;; Eldoc
3498 (ert-deftest python-eldoc--get-symbol-at-point-1 ()
3499 "Test paren handling."
3500 (python-tests-with-temp-buffer
3502 map(xx
3503 map(codecs.open('somefile'
3505 (python-tests-look-at "ap(xx")
3506 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3507 (goto-char (line-end-position))
3508 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3509 (python-tests-look-at "('somefile'")
3510 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3511 (goto-char (line-end-position))
3512 (should (string= (python-eldoc--get-symbol-at-point) "codecs.open"))))
3514 (ert-deftest python-eldoc--get-symbol-at-point-2 ()
3515 "Ensure self is replaced with the class name."
3516 (python-tests-with-temp-buffer
3518 class TheClass:
3520 def some_method(self, n):
3521 return n
3523 def other(self):
3524 return self.some_method(1234)
3527 (python-tests-look-at "self.some_method")
3528 (should (string= (python-eldoc--get-symbol-at-point)
3529 "TheClass.some_method"))
3530 (python-tests-look-at "1234)")
3531 (should (string= (python-eldoc--get-symbol-at-point)
3532 "TheClass.some_method"))))
3534 (ert-deftest python-eldoc--get-symbol-at-point-3 ()
3535 "Ensure symbol is found when point is at end of buffer."
3536 (python-tests-with-temp-buffer
3538 some_symbol
3541 (goto-char (point-max))
3542 (should (string= (python-eldoc--get-symbol-at-point)
3543 "some_symbol"))))
3545 (ert-deftest python-eldoc--get-symbol-at-point-4 ()
3546 "Ensure symbol is found when point is at whitespace."
3547 (python-tests-with-temp-buffer
3549 some_symbol some_other_symbol
3551 (python-tests-look-at " some_other_symbol")
3552 (should (string= (python-eldoc--get-symbol-at-point)
3553 "some_symbol"))))
3556 ;;; Imenu
3558 (ert-deftest python-imenu-create-index-1 ()
3559 (python-tests-with-temp-buffer
3561 class Foo(models.Model):
3562 pass
3565 class Bar(models.Model):
3566 pass
3569 def decorator(arg1, arg2, arg3):
3570 '''print decorated function call data to stdout.
3572 Usage:
3574 @decorator('arg1', 'arg2')
3575 def func(a, b, c=True):
3576 pass
3579 def wrap(f):
3580 print ('wrap')
3581 def wrapped_f(*args):
3582 print ('wrapped_f')
3583 print ('Decorator arguments:', arg1, arg2, arg3)
3584 f(*args)
3585 print ('called f(*args)')
3586 return wrapped_f
3587 return wrap
3590 class Baz(object):
3592 def a(self):
3593 pass
3595 def b(self):
3596 pass
3598 class Frob(object):
3600 def c(self):
3601 pass
3603 async def d(self):
3604 pass
3606 (goto-char (point-max))
3607 (should (equal
3608 (list
3609 (cons "Foo (class)" (copy-marker 2))
3610 (cons "Bar (class)" (copy-marker 38))
3611 (list
3612 "decorator (def)"
3613 (cons "*function definition*" (copy-marker 74))
3614 (list
3615 "wrap (def)"
3616 (cons "*function definition*" (copy-marker 254))
3617 (cons "wrapped_f (def)" (copy-marker 294))))
3618 (list
3619 "Baz (class)"
3620 (cons "*class definition*" (copy-marker 519))
3621 (cons "a (def)" (copy-marker 539))
3622 (cons "b (def)" (copy-marker 570))
3623 (list
3624 "Frob (class)"
3625 (cons "*class definition*" (copy-marker 601))
3626 (cons "c (def)" (copy-marker 626))
3627 (cons "d (async def)" (copy-marker 665)))))
3628 (python-imenu-create-index)))))
3630 (ert-deftest python-imenu-create-index-2 ()
3631 (python-tests-with-temp-buffer
3633 class Foo(object):
3634 def foo(self):
3635 def foo1():
3636 pass
3638 def foobar(self):
3639 pass
3641 (goto-char (point-max))
3642 (should (equal
3643 (list
3644 (list
3645 "Foo (class)"
3646 (cons "*class definition*" (copy-marker 2))
3647 (list
3648 "foo (def)"
3649 (cons "*function definition*" (copy-marker 21))
3650 (cons "foo1 (def)" (copy-marker 40)))
3651 (cons "foobar (def)" (copy-marker 78))))
3652 (python-imenu-create-index)))))
3654 (ert-deftest python-imenu-create-index-3 ()
3655 (python-tests-with-temp-buffer
3657 class Foo(object):
3658 def foo(self):
3659 def foo1():
3660 pass
3661 def foo2():
3662 pass
3664 (goto-char (point-max))
3665 (should (equal
3666 (list
3667 (list
3668 "Foo (class)"
3669 (cons "*class definition*" (copy-marker 2))
3670 (list
3671 "foo (def)"
3672 (cons "*function definition*" (copy-marker 21))
3673 (cons "foo1 (def)" (copy-marker 40))
3674 (cons "foo2 (def)" (copy-marker 77)))))
3675 (python-imenu-create-index)))))
3677 (ert-deftest python-imenu-create-index-4 ()
3678 (python-tests-with-temp-buffer
3680 class Foo(object):
3681 class Bar(object):
3682 def __init__(self):
3683 pass
3685 def __str__(self):
3686 pass
3688 def __init__(self):
3689 pass
3691 (goto-char (point-max))
3692 (should (equal
3693 (list
3694 (list
3695 "Foo (class)"
3696 (cons "*class definition*" (copy-marker 2))
3697 (list
3698 "Bar (class)"
3699 (cons "*class definition*" (copy-marker 21))
3700 (cons "__init__ (def)" (copy-marker 44))
3701 (cons "__str__ (def)" (copy-marker 90)))
3702 (cons "__init__ (def)" (copy-marker 135))))
3703 (python-imenu-create-index)))))
3705 (ert-deftest python-imenu-create-flat-index-1 ()
3706 (python-tests-with-temp-buffer
3708 class Foo(models.Model):
3709 pass
3712 class Bar(models.Model):
3713 pass
3716 def decorator(arg1, arg2, arg3):
3717 '''print decorated function call data to stdout.
3719 Usage:
3721 @decorator('arg1', 'arg2')
3722 def func(a, b, c=True):
3723 pass
3726 def wrap(f):
3727 print ('wrap')
3728 def wrapped_f(*args):
3729 print ('wrapped_f')
3730 print ('Decorator arguments:', arg1, arg2, arg3)
3731 f(*args)
3732 print ('called f(*args)')
3733 return wrapped_f
3734 return wrap
3737 class Baz(object):
3739 def a(self):
3740 pass
3742 def b(self):
3743 pass
3745 class Frob(object):
3747 def c(self):
3748 pass
3750 async def d(self):
3751 pass
3753 (goto-char (point-max))
3754 (should (equal
3755 (list (cons "Foo" (copy-marker 2))
3756 (cons "Bar" (copy-marker 38))
3757 (cons "decorator" (copy-marker 74))
3758 (cons "decorator.wrap" (copy-marker 254))
3759 (cons "decorator.wrap.wrapped_f" (copy-marker 294))
3760 (cons "Baz" (copy-marker 519))
3761 (cons "Baz.a" (copy-marker 539))
3762 (cons "Baz.b" (copy-marker 570))
3763 (cons "Baz.Frob" (copy-marker 601))
3764 (cons "Baz.Frob.c" (copy-marker 626))
3765 (cons "Baz.Frob.d" (copy-marker 665)))
3766 (python-imenu-create-flat-index)))))
3768 (ert-deftest python-imenu-create-flat-index-2 ()
3769 (python-tests-with-temp-buffer
3771 class Foo(object):
3772 class Bar(object):
3773 def __init__(self):
3774 pass
3776 def __str__(self):
3777 pass
3779 def __init__(self):
3780 pass
3782 (goto-char (point-max))
3783 (should (equal
3784 (list
3785 (cons "Foo" (copy-marker 2))
3786 (cons "Foo.Bar" (copy-marker 21))
3787 (cons "Foo.Bar.__init__" (copy-marker 44))
3788 (cons "Foo.Bar.__str__" (copy-marker 90))
3789 (cons "Foo.__init__" (copy-marker 135)))
3790 (python-imenu-create-flat-index)))))
3793 ;;; Misc helpers
3795 (ert-deftest python-info-current-defun-1 ()
3796 (python-tests-with-temp-buffer
3798 def foo(a, b):
3800 (forward-line 1)
3801 (should (string= "foo" (python-info-current-defun)))
3802 (should (string= "def foo" (python-info-current-defun t)))
3803 (forward-line 1)
3804 (should (not (python-info-current-defun)))
3805 (indent-for-tab-command)
3806 (should (string= "foo" (python-info-current-defun)))
3807 (should (string= "def foo" (python-info-current-defun t)))))
3809 (ert-deftest python-info-current-defun-2 ()
3810 (python-tests-with-temp-buffer
3812 class C(object):
3814 def m(self):
3815 if True:
3816 return [i for i in range(3)]
3817 else:
3818 return []
3820 def b():
3821 do_b()
3823 def a():
3824 do_a()
3826 def c(self):
3827 do_c()
3829 (forward-line 1)
3830 (should (string= "C" (python-info-current-defun)))
3831 (should (string= "class C" (python-info-current-defun t)))
3832 (python-tests-look-at "return [i for ")
3833 (should (string= "C.m" (python-info-current-defun)))
3834 (should (string= "def C.m" (python-info-current-defun t)))
3835 (python-tests-look-at "def b():")
3836 (should (string= "C.m.b" (python-info-current-defun)))
3837 (should (string= "def C.m.b" (python-info-current-defun t)))
3838 (forward-line 2)
3839 (indent-for-tab-command)
3840 (python-indent-dedent-line-backspace 1)
3841 (should (string= "C.m" (python-info-current-defun)))
3842 (should (string= "def C.m" (python-info-current-defun t)))
3843 (python-tests-look-at "def c(self):")
3844 (forward-line -1)
3845 (indent-for-tab-command)
3846 (should (string= "C.m.a" (python-info-current-defun)))
3847 (should (string= "def C.m.a" (python-info-current-defun t)))
3848 (python-indent-dedent-line-backspace 1)
3849 (should (string= "C.m" (python-info-current-defun)))
3850 (should (string= "def C.m" (python-info-current-defun t)))
3851 (python-indent-dedent-line-backspace 1)
3852 (should (string= "C" (python-info-current-defun)))
3853 (should (string= "class C" (python-info-current-defun t)))
3854 (python-tests-look-at "def c(self):")
3855 (should (string= "C.c" (python-info-current-defun)))
3856 (should (string= "def C.c" (python-info-current-defun t)))
3857 (python-tests-look-at "do_c()")
3858 (should (string= "C.c" (python-info-current-defun)))
3859 (should (string= "def C.c" (python-info-current-defun t)))))
3861 (ert-deftest python-info-current-defun-3 ()
3862 (python-tests-with-temp-buffer
3864 def decoratorFunctionWithArguments(arg1, arg2, arg3):
3865 '''print decorated function call data to stdout.
3867 Usage:
3869 @decoratorFunctionWithArguments('arg1', 'arg2')
3870 def func(a, b, c=True):
3871 pass
3874 def wwrap(f):
3875 print 'Inside wwrap()'
3876 def wrapped_f(*args):
3877 print 'Inside wrapped_f()'
3878 print 'Decorator arguments:', arg1, arg2, arg3
3879 f(*args)
3880 print 'After f(*args)'
3881 return wrapped_f
3882 return wwrap
3884 (python-tests-look-at "def wwrap(f):")
3885 (forward-line -1)
3886 (should (not (python-info-current-defun)))
3887 (indent-for-tab-command 1)
3888 (should (string= (python-info-current-defun)
3889 "decoratorFunctionWithArguments"))
3890 (should (string= (python-info-current-defun t)
3891 "def decoratorFunctionWithArguments"))
3892 (python-tests-look-at "def wrapped_f(*args):")
3893 (should (string= (python-info-current-defun)
3894 "decoratorFunctionWithArguments.wwrap.wrapped_f"))
3895 (should (string= (python-info-current-defun t)
3896 "def decoratorFunctionWithArguments.wwrap.wrapped_f"))
3897 (python-tests-look-at "return wrapped_f")
3898 (should (string= (python-info-current-defun)
3899 "decoratorFunctionWithArguments.wwrap"))
3900 (should (string= (python-info-current-defun t)
3901 "def decoratorFunctionWithArguments.wwrap"))
3902 (end-of-line 1)
3903 (python-tests-look-at "return wwrap")
3904 (should (string= (python-info-current-defun)
3905 "decoratorFunctionWithArguments"))
3906 (should (string= (python-info-current-defun t)
3907 "def decoratorFunctionWithArguments"))))
3909 (ert-deftest python-info-current-symbol-1 ()
3910 (python-tests-with-temp-buffer
3912 class C(object):
3914 def m(self):
3915 self.c()
3917 def c(self):
3918 print ('a')
3920 (python-tests-look-at "self.c()")
3921 (should (string= "self.c" (python-info-current-symbol)))
3922 (should (string= "C.c" (python-info-current-symbol t)))))
3924 (ert-deftest python-info-current-symbol-2 ()
3925 (python-tests-with-temp-buffer
3927 class C(object):
3929 class M(object):
3931 def a(self):
3932 self.c()
3934 def c(self):
3935 pass
3937 (python-tests-look-at "self.c()")
3938 (should (string= "self.c" (python-info-current-symbol)))
3939 (should (string= "C.M.c" (python-info-current-symbol t)))))
3941 (ert-deftest python-info-current-symbol-3 ()
3942 "Keywords should not be considered symbols."
3943 :expected-result :failed
3944 (python-tests-with-temp-buffer
3946 class C(object):
3947 pass
3949 ;; FIXME: keywords are not symbols.
3950 (python-tests-look-at "class C")
3951 (should (not (python-info-current-symbol)))
3952 (should (not (python-info-current-symbol t)))
3953 (python-tests-look-at "C(object)")
3954 (should (string= "C" (python-info-current-symbol)))
3955 (should (string= "class C" (python-info-current-symbol t)))))
3957 (ert-deftest python-info-statement-starts-block-p-1 ()
3958 (python-tests-with-temp-buffer
3960 def long_function_name(
3961 var_one, var_two, var_three,
3962 var_four):
3963 print (var_one)
3965 (python-tests-look-at "def long_function_name")
3966 (should (python-info-statement-starts-block-p))
3967 (python-tests-look-at "print (var_one)")
3968 (python-util-forward-comment -1)
3969 (should (python-info-statement-starts-block-p))))
3971 (ert-deftest python-info-statement-starts-block-p-2 ()
3972 (python-tests-with-temp-buffer
3974 if width == 0 and height == 0 and \\
3975 color == 'red' and emphasis == 'strong' or \\
3976 highlight > 100:
3977 raise ValueError('sorry, you lose')
3979 (python-tests-look-at "if width == 0 and")
3980 (should (python-info-statement-starts-block-p))
3981 (python-tests-look-at "raise ValueError(")
3982 (python-util-forward-comment -1)
3983 (should (python-info-statement-starts-block-p))))
3985 (ert-deftest python-info-statement-ends-block-p-1 ()
3986 (python-tests-with-temp-buffer
3988 def long_function_name(
3989 var_one, var_two, var_three,
3990 var_four):
3991 print (var_one)
3993 (python-tests-look-at "print (var_one)")
3994 (should (python-info-statement-ends-block-p))))
3996 (ert-deftest python-info-statement-ends-block-p-2 ()
3997 (python-tests-with-temp-buffer
3999 if width == 0 and height == 0 and \\
4000 color == 'red' and emphasis == 'strong' or \\
4001 highlight > 100:
4002 raise ValueError(
4003 'sorry, you lose'
4007 (python-tests-look-at "raise ValueError(")
4008 (should (python-info-statement-ends-block-p))))
4010 (ert-deftest python-info-beginning-of-statement-p-1 ()
4011 (python-tests-with-temp-buffer
4013 def long_function_name(
4014 var_one, var_two, var_three,
4015 var_four):
4016 print (var_one)
4018 (python-tests-look-at "def long_function_name")
4019 (should (python-info-beginning-of-statement-p))
4020 (forward-char 10)
4021 (should (not (python-info-beginning-of-statement-p)))
4022 (python-tests-look-at "print (var_one)")
4023 (should (python-info-beginning-of-statement-p))
4024 (goto-char (line-beginning-position))
4025 (should (not (python-info-beginning-of-statement-p)))))
4027 (ert-deftest python-info-beginning-of-statement-p-2 ()
4028 (python-tests-with-temp-buffer
4030 if width == 0 and height == 0 and \\
4031 color == 'red' and emphasis == 'strong' or \\
4032 highlight > 100:
4033 raise ValueError(
4034 'sorry, you lose'
4038 (python-tests-look-at "if width == 0 and")
4039 (should (python-info-beginning-of-statement-p))
4040 (forward-char 10)
4041 (should (not (python-info-beginning-of-statement-p)))
4042 (python-tests-look-at "raise ValueError(")
4043 (should (python-info-beginning-of-statement-p))
4044 (goto-char (line-beginning-position))
4045 (should (not (python-info-beginning-of-statement-p)))))
4047 (ert-deftest python-info-end-of-statement-p-1 ()
4048 (python-tests-with-temp-buffer
4050 def long_function_name(
4051 var_one, var_two, var_three,
4052 var_four):
4053 print (var_one)
4055 (python-tests-look-at "def long_function_name")
4056 (should (not (python-info-end-of-statement-p)))
4057 (end-of-line)
4058 (should (not (python-info-end-of-statement-p)))
4059 (python-tests-look-at "print (var_one)")
4060 (python-util-forward-comment -1)
4061 (should (python-info-end-of-statement-p))
4062 (python-tests-look-at "print (var_one)")
4063 (should (not (python-info-end-of-statement-p)))
4064 (end-of-line)
4065 (should (python-info-end-of-statement-p))))
4067 (ert-deftest python-info-end-of-statement-p-2 ()
4068 (python-tests-with-temp-buffer
4070 if width == 0 and height == 0 and \\
4071 color == 'red' and emphasis == 'strong' or \\
4072 highlight > 100:
4073 raise ValueError(
4074 'sorry, you lose'
4078 (python-tests-look-at "if width == 0 and")
4079 (should (not (python-info-end-of-statement-p)))
4080 (end-of-line)
4081 (should (not (python-info-end-of-statement-p)))
4082 (python-tests-look-at "raise ValueError(")
4083 (python-util-forward-comment -1)
4084 (should (python-info-end-of-statement-p))
4085 (python-tests-look-at "raise ValueError(")
4086 (should (not (python-info-end-of-statement-p)))
4087 (end-of-line)
4088 (should (not (python-info-end-of-statement-p)))
4089 (goto-char (point-max))
4090 (python-util-forward-comment -1)
4091 (should (python-info-end-of-statement-p))))
4093 (ert-deftest python-info-beginning-of-block-p-1 ()
4094 (python-tests-with-temp-buffer
4096 def long_function_name(
4097 var_one, var_two, var_three,
4098 var_four):
4099 print (var_one)
4101 (python-tests-look-at "def long_function_name")
4102 (should (python-info-beginning-of-block-p))
4103 (python-tests-look-at "var_one, var_two, var_three,")
4104 (should (not (python-info-beginning-of-block-p)))
4105 (python-tests-look-at "print (var_one)")
4106 (should (not (python-info-beginning-of-block-p)))))
4108 (ert-deftest python-info-beginning-of-block-p-2 ()
4109 (python-tests-with-temp-buffer
4111 if width == 0 and height == 0 and \\
4112 color == 'red' and emphasis == 'strong' or \\
4113 highlight > 100:
4114 raise ValueError(
4115 'sorry, you lose'
4119 (python-tests-look-at "if width == 0 and")
4120 (should (python-info-beginning-of-block-p))
4121 (python-tests-look-at "color == 'red' and emphasis")
4122 (should (not (python-info-beginning-of-block-p)))
4123 (python-tests-look-at "raise ValueError(")
4124 (should (not (python-info-beginning-of-block-p)))))
4126 (ert-deftest python-info-end-of-block-p-1 ()
4127 (python-tests-with-temp-buffer
4129 def long_function_name(
4130 var_one, var_two, var_three,
4131 var_four):
4132 print (var_one)
4134 (python-tests-look-at "def long_function_name")
4135 (should (not (python-info-end-of-block-p)))
4136 (python-tests-look-at "var_one, var_two, var_three,")
4137 (should (not (python-info-end-of-block-p)))
4138 (python-tests-look-at "var_four):")
4139 (end-of-line)
4140 (should (not (python-info-end-of-block-p)))
4141 (python-tests-look-at "print (var_one)")
4142 (should (not (python-info-end-of-block-p)))
4143 (end-of-line 1)
4144 (should (python-info-end-of-block-p))))
4146 (ert-deftest python-info-end-of-block-p-2 ()
4147 (python-tests-with-temp-buffer
4149 if width == 0 and height == 0 and \\
4150 color == 'red' and emphasis == 'strong' or \\
4151 highlight > 100:
4152 raise ValueError(
4153 'sorry, you lose'
4157 (python-tests-look-at "if width == 0 and")
4158 (should (not (python-info-end-of-block-p)))
4159 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4160 (should (not (python-info-end-of-block-p)))
4161 (python-tests-look-at "highlight > 100:")
4162 (end-of-line)
4163 (should (not (python-info-end-of-block-p)))
4164 (python-tests-look-at "raise ValueError(")
4165 (should (not (python-info-end-of-block-p)))
4166 (end-of-line 1)
4167 (should (not (python-info-end-of-block-p)))
4168 (goto-char (point-max))
4169 (python-util-forward-comment -1)
4170 (should (python-info-end-of-block-p))))
4172 (ert-deftest python-info-dedenter-opening-block-position-1 ()
4173 (python-tests-with-temp-buffer
4175 if request.user.is_authenticated():
4176 try:
4177 profile = request.user.get_profile()
4178 except Profile.DoesNotExist:
4179 profile = Profile.objects.create(user=request.user)
4180 else:
4181 if profile.stats:
4182 profile.recalculate_stats()
4183 else:
4184 profile.clear_stats()
4185 finally:
4186 profile.views += 1
4187 profile.save()
4189 (python-tests-look-at "try:")
4190 (should (not (python-info-dedenter-opening-block-position)))
4191 (python-tests-look-at "except Profile.DoesNotExist:")
4192 (should (= (python-tests-look-at "try:" -1 t)
4193 (python-info-dedenter-opening-block-position)))
4194 (python-tests-look-at "else:")
4195 (should (= (python-tests-look-at "except Profile.DoesNotExist:" -1 t)
4196 (python-info-dedenter-opening-block-position)))
4197 (python-tests-look-at "if profile.stats:")
4198 (should (not (python-info-dedenter-opening-block-position)))
4199 (python-tests-look-at "else:")
4200 (should (= (python-tests-look-at "if profile.stats:" -1 t)
4201 (python-info-dedenter-opening-block-position)))
4202 (python-tests-look-at "finally:")
4203 (should (= (python-tests-look-at "else:" -2 t)
4204 (python-info-dedenter-opening-block-position)))))
4206 (ert-deftest python-info-dedenter-opening-block-position-2 ()
4207 (python-tests-with-temp-buffer
4209 if request.user.is_authenticated():
4210 profile = Profile.objects.get_or_create(user=request.user)
4211 if profile.stats:
4212 profile.recalculate_stats()
4214 data = {
4215 'else': 'do it'
4217 'else'
4219 (python-tests-look-at "'else': 'do it'")
4220 (should (not (python-info-dedenter-opening-block-position)))
4221 (python-tests-look-at "'else'")
4222 (should (not (python-info-dedenter-opening-block-position)))))
4224 (ert-deftest python-info-dedenter-opening-block-position-3 ()
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-position)))
4244 (python-tests-look-at "except IOError:")
4245 (should (= (python-tests-look-at "try:" -1 t)
4246 (python-info-dedenter-opening-block-position)))
4248 (python-tests-look-at "except Exception:")
4249 (should (= (python-tests-look-at "except IOError:" -1 t)
4250 (python-info-dedenter-opening-block-position)))
4252 (python-tests-look-at "if hide_details:")
4253 (should (not (python-info-dedenter-opening-block-position)))
4255 ;; check indentation modifies the detected opening block
4256 (python-tests-look-at "else")
4257 (should (= (python-tests-look-at "if hide_details:" -1 t)
4258 (python-info-dedenter-opening-block-position)))
4260 (indent-line-to 8)
4261 (should (= (python-tests-look-at "if hide_details:" -1 t)
4262 (python-info-dedenter-opening-block-position)))
4264 (indent-line-to 4)
4265 (should (= (python-tests-look-at "except Exception:" -1 t)
4266 (python-info-dedenter-opening-block-position)))
4268 (indent-line-to 0)
4269 (should (= (python-tests-look-at "if save:" -1 t)
4270 (python-info-dedenter-opening-block-position)))))
4272 (ert-deftest python-info-dedenter-opening-block-positions-1 ()
4273 (python-tests-with-temp-buffer
4275 if save:
4276 try:
4277 write_to_disk(data)
4278 except IOError:
4279 msg = 'Error saving to disk'
4280 message(msg)
4281 logger.exception(msg)
4282 except Exception:
4283 if hide_details:
4284 logger.exception('Unhandled exception')
4285 else
4286 finally:
4287 data.free()
4289 (python-tests-look-at "try:")
4290 (should (not (python-info-dedenter-opening-block-positions)))
4292 (python-tests-look-at "except IOError:")
4293 (should
4294 (equal (list
4295 (python-tests-look-at "try:" -1 t))
4296 (python-info-dedenter-opening-block-positions)))
4298 (python-tests-look-at "except Exception:")
4299 (should
4300 (equal (list
4301 (python-tests-look-at "except IOError:" -1 t))
4302 (python-info-dedenter-opening-block-positions)))
4304 (python-tests-look-at "if hide_details:")
4305 (should (not (python-info-dedenter-opening-block-positions)))
4307 ;; check indentation does not modify the detected opening blocks
4308 (python-tests-look-at "else")
4309 (should
4310 (equal (list
4311 (python-tests-look-at "if hide_details:" -1 t)
4312 (python-tests-look-at "except Exception:" -1 t)
4313 (python-tests-look-at "if save:" -1 t))
4314 (python-info-dedenter-opening-block-positions)))
4316 (indent-line-to 8)
4317 (should
4318 (equal (list
4319 (python-tests-look-at "if hide_details:" -1 t)
4320 (python-tests-look-at "except Exception:" -1 t)
4321 (python-tests-look-at "if save:" -1 t))
4322 (python-info-dedenter-opening-block-positions)))
4324 (indent-line-to 4)
4325 (should
4326 (equal (list
4327 (python-tests-look-at "if hide_details:" -1 t)
4328 (python-tests-look-at "except Exception:" -1 t)
4329 (python-tests-look-at "if save:" -1 t))
4330 (python-info-dedenter-opening-block-positions)))
4332 (indent-line-to 0)
4333 (should
4334 (equal (list
4335 (python-tests-look-at "if hide_details:" -1 t)
4336 (python-tests-look-at "except Exception:" -1 t)
4337 (python-tests-look-at "if save:" -1 t))
4338 (python-info-dedenter-opening-block-positions)))))
4340 (ert-deftest python-info-dedenter-opening-block-positions-2 ()
4341 "Test detection of opening blocks for elif."
4342 (python-tests-with-temp-buffer
4344 if var:
4345 if var2:
4346 something()
4347 elif var3:
4348 something_else()
4349 elif
4351 (python-tests-look-at "elif var3:")
4352 (should
4353 (equal (list
4354 (python-tests-look-at "if var2:" -1 t)
4355 (python-tests-look-at "if var:" -1 t))
4356 (python-info-dedenter-opening-block-positions)))
4358 (python-tests-look-at "elif\n")
4359 (should
4360 (equal (list
4361 (python-tests-look-at "elif var3:" -1 t)
4362 (python-tests-look-at "if var:" -1 t))
4363 (python-info-dedenter-opening-block-positions)))))
4365 (ert-deftest python-info-dedenter-opening-block-positions-3 ()
4366 "Test detection of opening blocks for else."
4367 (python-tests-with-temp-buffer
4369 try:
4370 something()
4371 except:
4372 if var:
4373 if var2:
4374 something()
4375 elif var3:
4376 something_else()
4377 else
4379 if var4:
4380 while var5:
4381 var4.pop()
4382 else
4384 for value in var6:
4385 if value > 0:
4386 print value
4387 else
4389 (python-tests-look-at "else\n")
4390 (should
4391 (equal (list
4392 (python-tests-look-at "elif var3:" -1 t)
4393 (python-tests-look-at "if var:" -1 t)
4394 (python-tests-look-at "except:" -1 t))
4395 (python-info-dedenter-opening-block-positions)))
4397 (python-tests-look-at "else\n")
4398 (should
4399 (equal (list
4400 (python-tests-look-at "while var5:" -1 t)
4401 (python-tests-look-at "if var4:" -1 t))
4402 (python-info-dedenter-opening-block-positions)))
4404 (python-tests-look-at "else\n")
4405 (should
4406 (equal (list
4407 (python-tests-look-at "if value > 0:" -1 t)
4408 (python-tests-look-at "for value in var6:" -1 t)
4409 (python-tests-look-at "if var4:" -1 t))
4410 (python-info-dedenter-opening-block-positions)))))
4412 (ert-deftest python-info-dedenter-opening-block-positions-4 ()
4413 "Test detection of opening blocks for except."
4414 (python-tests-with-temp-buffer
4416 try:
4417 something()
4418 except ValueError:
4419 something_else()
4420 except
4422 (python-tests-look-at "except ValueError:")
4423 (should
4424 (equal (list (python-tests-look-at "try:" -1 t))
4425 (python-info-dedenter-opening-block-positions)))
4427 (python-tests-look-at "except\n")
4428 (should
4429 (equal (list (python-tests-look-at "except ValueError:" -1 t))
4430 (python-info-dedenter-opening-block-positions)))))
4432 (ert-deftest python-info-dedenter-opening-block-positions-5 ()
4433 "Test detection of opening blocks for finally."
4434 (python-tests-with-temp-buffer
4436 try:
4437 something()
4438 finally
4440 try:
4441 something_else()
4442 except:
4443 logger.exception('something went wrong')
4444 finally
4446 try:
4447 something_else_else()
4448 except Exception:
4449 logger.exception('something else went wrong')
4450 else:
4451 print ('all good')
4452 finally
4454 (python-tests-look-at "finally\n")
4455 (should
4456 (equal (list (python-tests-look-at "try:" -1 t))
4457 (python-info-dedenter-opening-block-positions)))
4459 (python-tests-look-at "finally\n")
4460 (should
4461 (equal (list (python-tests-look-at "except:" -1 t))
4462 (python-info-dedenter-opening-block-positions)))
4464 (python-tests-look-at "finally\n")
4465 (should
4466 (equal (list (python-tests-look-at "else:" -1 t))
4467 (python-info-dedenter-opening-block-positions)))))
4469 (ert-deftest python-info-dedenter-opening-block-message-1 ()
4470 "Test dedenters inside strings are ignored."
4471 (python-tests-with-temp-buffer
4472 "'''
4473 try:
4474 something()
4475 except:
4476 logger.exception('something went wrong')
4479 (python-tests-look-at "except\n")
4480 (should (not (python-info-dedenter-opening-block-message)))))
4482 (ert-deftest python-info-dedenter-opening-block-message-2 ()
4483 "Test except keyword."
4484 (python-tests-with-temp-buffer
4486 try:
4487 something()
4488 except:
4489 logger.exception('something went wrong')
4491 (python-tests-look-at "except:")
4492 (should (string=
4493 "Closes try:"
4494 (substring-no-properties
4495 (python-info-dedenter-opening-block-message))))
4496 (end-of-line)
4497 (should (string=
4498 "Closes try:"
4499 (substring-no-properties
4500 (python-info-dedenter-opening-block-message))))))
4502 (ert-deftest python-info-dedenter-opening-block-message-3 ()
4503 "Test else keyword."
4504 (python-tests-with-temp-buffer
4506 try:
4507 something()
4508 except:
4509 logger.exception('something went wrong')
4510 else:
4511 logger.debug('all good')
4513 (python-tests-look-at "else:")
4514 (should (string=
4515 "Closes except:"
4516 (substring-no-properties
4517 (python-info-dedenter-opening-block-message))))
4518 (end-of-line)
4519 (should (string=
4520 "Closes except:"
4521 (substring-no-properties
4522 (python-info-dedenter-opening-block-message))))))
4524 (ert-deftest python-info-dedenter-opening-block-message-4 ()
4525 "Test finally keyword."
4526 (python-tests-with-temp-buffer
4528 try:
4529 something()
4530 except:
4531 logger.exception('something went wrong')
4532 else:
4533 logger.debug('all good')
4534 finally:
4535 clean()
4537 (python-tests-look-at "finally:")
4538 (should (string=
4539 "Closes else:"
4540 (substring-no-properties
4541 (python-info-dedenter-opening-block-message))))
4542 (end-of-line)
4543 (should (string=
4544 "Closes else:"
4545 (substring-no-properties
4546 (python-info-dedenter-opening-block-message))))))
4548 (ert-deftest python-info-dedenter-opening-block-message-5 ()
4549 "Test elif keyword."
4550 (python-tests-with-temp-buffer
4552 if a:
4553 something()
4554 elif b:
4556 (python-tests-look-at "elif b:")
4557 (should (string=
4558 "Closes if a:"
4559 (substring-no-properties
4560 (python-info-dedenter-opening-block-message))))
4561 (end-of-line)
4562 (should (string=
4563 "Closes if a:"
4564 (substring-no-properties
4565 (python-info-dedenter-opening-block-message))))))
4568 (ert-deftest python-info-dedenter-statement-p-1 ()
4569 "Test dedenters inside strings are ignored."
4570 (python-tests-with-temp-buffer
4571 "'''
4572 try:
4573 something()
4574 except:
4575 logger.exception('something went wrong')
4578 (python-tests-look-at "except\n")
4579 (should (not (python-info-dedenter-statement-p)))))
4581 (ert-deftest python-info-dedenter-statement-p-2 ()
4582 "Test except keyword."
4583 (python-tests-with-temp-buffer
4585 try:
4586 something()
4587 except:
4588 logger.exception('something went wrong')
4590 (python-tests-look-at "except:")
4591 (should (= (point) (python-info-dedenter-statement-p)))
4592 (end-of-line)
4593 (should (= (save-excursion
4594 (back-to-indentation)
4595 (point))
4596 (python-info-dedenter-statement-p)))))
4598 (ert-deftest python-info-dedenter-statement-p-3 ()
4599 "Test else keyword."
4600 (python-tests-with-temp-buffer
4602 try:
4603 something()
4604 except:
4605 logger.exception('something went wrong')
4606 else:
4607 logger.debug('all good')
4609 (python-tests-look-at "else:")
4610 (should (= (point) (python-info-dedenter-statement-p)))
4611 (end-of-line)
4612 (should (= (save-excursion
4613 (back-to-indentation)
4614 (point))
4615 (python-info-dedenter-statement-p)))))
4617 (ert-deftest python-info-dedenter-statement-p-4 ()
4618 "Test finally keyword."
4619 (python-tests-with-temp-buffer
4621 try:
4622 something()
4623 except:
4624 logger.exception('something went wrong')
4625 else:
4626 logger.debug('all good')
4627 finally:
4628 clean()
4630 (python-tests-look-at "finally:")
4631 (should (= (point) (python-info-dedenter-statement-p)))
4632 (end-of-line)
4633 (should (= (save-excursion
4634 (back-to-indentation)
4635 (point))
4636 (python-info-dedenter-statement-p)))))
4638 (ert-deftest python-info-dedenter-statement-p-5 ()
4639 "Test elif keyword."
4640 (python-tests-with-temp-buffer
4642 if a:
4643 something()
4644 elif b:
4646 (python-tests-look-at "elif b:")
4647 (should (= (point) (python-info-dedenter-statement-p)))
4648 (end-of-line)
4649 (should (= (save-excursion
4650 (back-to-indentation)
4651 (point))
4652 (python-info-dedenter-statement-p)))))
4654 (ert-deftest python-info-line-ends-backslash-p-1 ()
4655 (python-tests-with-temp-buffer
4657 objects = Thing.objects.all() \\
4658 .filter(
4659 type='toy',
4660 status='bought'
4661 ) \\
4662 .aggregate(
4663 Sum('amount')
4664 ) \\
4665 .values_list()
4667 (should (python-info-line-ends-backslash-p 2)) ; .filter(...
4668 (should (python-info-line-ends-backslash-p 3))
4669 (should (python-info-line-ends-backslash-p 4))
4670 (should (python-info-line-ends-backslash-p 5))
4671 (should (python-info-line-ends-backslash-p 6)) ; ) \...
4672 (should (python-info-line-ends-backslash-p 7))
4673 (should (python-info-line-ends-backslash-p 8))
4674 (should (python-info-line-ends-backslash-p 9))
4675 (should (not (python-info-line-ends-backslash-p 10))))) ; .values_list()...
4677 (ert-deftest python-info-beginning-of-backslash-1 ()
4678 (python-tests-with-temp-buffer
4680 objects = Thing.objects.all() \\
4681 .filter(
4682 type='toy',
4683 status='bought'
4684 ) \\
4685 .aggregate(
4686 Sum('amount')
4687 ) \\
4688 .values_list()
4690 (let ((first 2)
4691 (second (python-tests-look-at ".filter("))
4692 (third (python-tests-look-at ".aggregate(")))
4693 (should (= first (python-info-beginning-of-backslash 2)))
4694 (should (= second (python-info-beginning-of-backslash 3)))
4695 (should (= second (python-info-beginning-of-backslash 4)))
4696 (should (= second (python-info-beginning-of-backslash 5)))
4697 (should (= second (python-info-beginning-of-backslash 6)))
4698 (should (= third (python-info-beginning-of-backslash 7)))
4699 (should (= third (python-info-beginning-of-backslash 8)))
4700 (should (= third (python-info-beginning-of-backslash 9)))
4701 (should (not (python-info-beginning-of-backslash 10))))))
4703 (ert-deftest python-info-continuation-line-p-1 ()
4704 (python-tests-with-temp-buffer
4706 if width == 0 and height == 0 and \\
4707 color == 'red' and emphasis == 'strong' or \\
4708 highlight > 100:
4709 raise ValueError(
4710 'sorry, you lose'
4714 (python-tests-look-at "if width == 0 and height == 0 and")
4715 (should (not (python-info-continuation-line-p)))
4716 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4717 (should (python-info-continuation-line-p))
4718 (python-tests-look-at "highlight > 100:")
4719 (should (python-info-continuation-line-p))
4720 (python-tests-look-at "raise ValueError(")
4721 (should (not (python-info-continuation-line-p)))
4722 (python-tests-look-at "'sorry, you lose'")
4723 (should (python-info-continuation-line-p))
4724 (forward-line 1)
4725 (should (python-info-continuation-line-p))
4726 (python-tests-look-at ")")
4727 (should (python-info-continuation-line-p))
4728 (forward-line 1)
4729 (should (not (python-info-continuation-line-p)))))
4731 (ert-deftest python-info-block-continuation-line-p-1 ()
4732 (python-tests-with-temp-buffer
4734 if width == 0 and height == 0 and \\
4735 color == 'red' and emphasis == 'strong' or \\
4736 highlight > 100:
4737 raise ValueError(
4738 'sorry, you lose'
4742 (python-tests-look-at "if width == 0 and")
4743 (should (not (python-info-block-continuation-line-p)))
4744 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4745 (should (= (python-info-block-continuation-line-p)
4746 (python-tests-look-at "if width == 0 and" -1 t)))
4747 (python-tests-look-at "highlight > 100:")
4748 (should (not (python-info-block-continuation-line-p)))))
4750 (ert-deftest python-info-block-continuation-line-p-2 ()
4751 (python-tests-with-temp-buffer
4753 def foo(a,
4756 pass
4758 (python-tests-look-at "def foo(a,")
4759 (should (not (python-info-block-continuation-line-p)))
4760 (python-tests-look-at "b,")
4761 (should (= (python-info-block-continuation-line-p)
4762 (python-tests-look-at "def foo(a," -1 t)))
4763 (python-tests-look-at "c):")
4764 (should (not (python-info-block-continuation-line-p)))))
4766 (ert-deftest python-info-assignment-statement-p-1 ()
4767 (python-tests-with-temp-buffer
4769 data = foo(), bar() \\
4770 baz(), 4 \\
4771 5, 6
4773 (python-tests-look-at "data = foo(), bar()")
4774 (should (python-info-assignment-statement-p))
4775 (should (python-info-assignment-statement-p t))
4776 (python-tests-look-at "baz(), 4")
4777 (should (python-info-assignment-statement-p))
4778 (should (not (python-info-assignment-statement-p t)))
4779 (python-tests-look-at "5, 6")
4780 (should (python-info-assignment-statement-p))
4781 (should (not (python-info-assignment-statement-p t)))))
4783 (ert-deftest python-info-assignment-statement-p-2 ()
4784 (python-tests-with-temp-buffer
4786 data = (foo(), bar()
4787 baz(), 4
4788 5, 6)
4790 (python-tests-look-at "data = (foo(), bar()")
4791 (should (python-info-assignment-statement-p))
4792 (should (python-info-assignment-statement-p t))
4793 (python-tests-look-at "baz(), 4")
4794 (should (python-info-assignment-statement-p))
4795 (should (not (python-info-assignment-statement-p t)))
4796 (python-tests-look-at "5, 6)")
4797 (should (python-info-assignment-statement-p))
4798 (should (not (python-info-assignment-statement-p t)))))
4800 (ert-deftest python-info-assignment-statement-p-3 ()
4801 (python-tests-with-temp-buffer
4803 data '=' 42
4805 (python-tests-look-at "data '=' 42")
4806 (should (not (python-info-assignment-statement-p)))
4807 (should (not (python-info-assignment-statement-p t)))))
4809 (ert-deftest python-info-assignment-continuation-line-p-1 ()
4810 (python-tests-with-temp-buffer
4812 data = foo(), bar() \\
4813 baz(), 4 \\
4814 5, 6
4816 (python-tests-look-at "data = foo(), bar()")
4817 (should (not (python-info-assignment-continuation-line-p)))
4818 (python-tests-look-at "baz(), 4")
4819 (should (= (python-info-assignment-continuation-line-p)
4820 (python-tests-look-at "foo()," -1 t)))
4821 (python-tests-look-at "5, 6")
4822 (should (not (python-info-assignment-continuation-line-p)))))
4824 (ert-deftest python-info-assignment-continuation-line-p-2 ()
4825 (python-tests-with-temp-buffer
4827 data = (foo(), bar()
4828 baz(), 4
4829 5, 6)
4831 (python-tests-look-at "data = (foo(), bar()")
4832 (should (not (python-info-assignment-continuation-line-p)))
4833 (python-tests-look-at "baz(), 4")
4834 (should (= (python-info-assignment-continuation-line-p)
4835 (python-tests-look-at "(foo()," -1 t)))
4836 (python-tests-look-at "5, 6)")
4837 (should (not (python-info-assignment-continuation-line-p)))))
4839 (ert-deftest python-info-looking-at-beginning-of-defun-1 ()
4840 (python-tests-with-temp-buffer
4842 def decorat0r(deff):
4843 '''decorates stuff.
4845 @decorat0r
4846 def foo(arg):
4849 def wrap():
4850 deff()
4851 return wwrap
4853 (python-tests-look-at "def decorat0r(deff):")
4854 (should (python-info-looking-at-beginning-of-defun))
4855 (python-tests-look-at "def foo(arg):")
4856 (should (not (python-info-looking-at-beginning-of-defun)))
4857 (python-tests-look-at "def wrap():")
4858 (should (python-info-looking-at-beginning-of-defun))
4859 (python-tests-look-at "deff()")
4860 (should (not (python-info-looking-at-beginning-of-defun)))))
4862 (ert-deftest python-info-current-line-comment-p-1 ()
4863 (python-tests-with-temp-buffer
4865 # this is a comment
4866 foo = True # another comment
4867 '#this is a string'
4868 if foo:
4869 # more comments
4870 print ('bar') # print bar
4872 (python-tests-look-at "# this is a comment")
4873 (should (python-info-current-line-comment-p))
4874 (python-tests-look-at "foo = True # another comment")
4875 (should (not (python-info-current-line-comment-p)))
4876 (python-tests-look-at "'#this is a string'")
4877 (should (not (python-info-current-line-comment-p)))
4878 (python-tests-look-at "# more comments")
4879 (should (python-info-current-line-comment-p))
4880 (python-tests-look-at "print ('bar') # print bar")
4881 (should (not (python-info-current-line-comment-p)))))
4883 (ert-deftest python-info-current-line-empty-p ()
4884 (python-tests-with-temp-buffer
4886 # this is a comment
4888 foo = True # another comment
4890 (should (python-info-current-line-empty-p))
4891 (python-tests-look-at "# this is a comment")
4892 (should (not (python-info-current-line-empty-p)))
4893 (forward-line 1)
4894 (should (python-info-current-line-empty-p))))
4896 (ert-deftest python-info-docstring-p-1 ()
4897 "Test module docstring detection."
4898 (python-tests-with-temp-buffer
4899 "# -*- coding: utf-8 -*-
4900 #!/usr/bin/python
4903 Module Docstring Django style.
4905 u'''Additional module docstring.'''
4906 '''Not a module docstring.'''
4908 (python-tests-look-at "Module Docstring Django style.")
4909 (should (python-info-docstring-p))
4910 (python-tests-look-at "u'''Additional module docstring.'''")
4911 (should (python-info-docstring-p))
4912 (python-tests-look-at "'''Not a module docstring.'''")
4913 (should (not (python-info-docstring-p)))))
4915 (ert-deftest python-info-docstring-p-2 ()
4916 "Test variable docstring detection."
4917 (python-tests-with-temp-buffer
4919 variable = 42
4920 U'''Variable docstring.'''
4921 '''Additional variable docstring.'''
4922 '''Not a variable docstring.'''
4924 (python-tests-look-at "Variable docstring.")
4925 (should (python-info-docstring-p))
4926 (python-tests-look-at "u'''Additional variable docstring.'''")
4927 (should (python-info-docstring-p))
4928 (python-tests-look-at "'''Not a variable docstring.'''")
4929 (should (not (python-info-docstring-p)))))
4931 (ert-deftest python-info-docstring-p-3 ()
4932 "Test function docstring detection."
4933 (python-tests-with-temp-buffer
4935 def func(a, b):
4936 r'''
4937 Function docstring.
4939 onetwo style.
4941 R'''Additional function docstring.'''
4942 '''Not a function docstring.'''
4943 return a + b
4945 (python-tests-look-at "Function docstring.")
4946 (should (python-info-docstring-p))
4947 (python-tests-look-at "R'''Additional function docstring.'''")
4948 (should (python-info-docstring-p))
4949 (python-tests-look-at "'''Not a function docstring.'''")
4950 (should (not (python-info-docstring-p)))))
4952 (ert-deftest python-info-docstring-p-4 ()
4953 "Test class docstring detection."
4954 (python-tests-with-temp-buffer
4956 class Class:
4957 ur'''
4958 Class docstring.
4960 symmetric style.
4962 uR'''
4963 Additional class docstring.
4965 '''Not a class docstring.'''
4966 pass
4968 (python-tests-look-at "Class docstring.")
4969 (should (python-info-docstring-p))
4970 (python-tests-look-at "uR'''") ;; Additional class docstring
4971 (should (python-info-docstring-p))
4972 (python-tests-look-at "'''Not a class docstring.'''")
4973 (should (not (python-info-docstring-p)))))
4975 (ert-deftest python-info-docstring-p-5 ()
4976 "Test class attribute docstring detection."
4977 (python-tests-with-temp-buffer
4979 class Class:
4980 attribute = 42
4981 Ur'''
4982 Class attribute docstring.
4984 pep-257 style.
4987 UR'''
4988 Additional class attribute docstring.
4990 '''Not a class attribute docstring.'''
4991 pass
4993 (python-tests-look-at "Class attribute docstring.")
4994 (should (python-info-docstring-p))
4995 (python-tests-look-at "UR'''") ;; Additional class attr docstring
4996 (should (python-info-docstring-p))
4997 (python-tests-look-at "'''Not a class attribute docstring.'''")
4998 (should (not (python-info-docstring-p)))))
5000 (ert-deftest python-info-docstring-p-6 ()
5001 "Test class method docstring detection."
5002 (python-tests-with-temp-buffer
5004 class Class:
5006 def __init__(self, a, b):
5007 self.a = a
5008 self.b = b
5010 def __call__(self):
5011 '''Method docstring.
5013 pep-257-nn style.
5015 '''Additional method docstring.'''
5016 '''Not a method docstring.'''
5017 return self.a + self.b
5019 (python-tests-look-at "Method docstring.")
5020 (should (python-info-docstring-p))
5021 (python-tests-look-at "'''Additional method docstring.'''")
5022 (should (python-info-docstring-p))
5023 (python-tests-look-at "'''Not a method docstring.'''")
5024 (should (not (python-info-docstring-p)))))
5026 (ert-deftest python-info-encoding-from-cookie-1 ()
5027 "Should detect it on first line."
5028 (python-tests-with-temp-buffer
5029 "# coding=latin-1
5031 foo = True # another comment
5033 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5035 (ert-deftest python-info-encoding-from-cookie-2 ()
5036 "Should detect it on second line."
5037 (python-tests-with-temp-buffer
5039 # coding=latin-1
5041 foo = True # another comment
5043 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5045 (ert-deftest python-info-encoding-from-cookie-3 ()
5046 "Should not be detected on third line (and following ones)."
5047 (python-tests-with-temp-buffer
5050 # coding=latin-1
5051 foo = True # another comment
5053 (should (not (python-info-encoding-from-cookie)))))
5055 (ert-deftest python-info-encoding-from-cookie-4 ()
5056 "Should detect Emacs style."
5057 (python-tests-with-temp-buffer
5058 "# -*- coding: latin-1 -*-
5060 foo = True # another comment"
5061 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5063 (ert-deftest python-info-encoding-from-cookie-5 ()
5064 "Should detect Vim style."
5065 (python-tests-with-temp-buffer
5066 "# vim: set fileencoding=latin-1 :
5068 foo = True # another comment"
5069 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5071 (ert-deftest python-info-encoding-from-cookie-6 ()
5072 "First cookie wins."
5073 (python-tests-with-temp-buffer
5074 "# -*- coding: iso-8859-1 -*-
5075 # vim: set fileencoding=latin-1 :
5077 foo = True # another comment"
5078 (should (eq (python-info-encoding-from-cookie) 'iso-8859-1))))
5080 (ert-deftest python-info-encoding-from-cookie-7 ()
5081 "First cookie wins."
5082 (python-tests-with-temp-buffer
5083 "# vim: set fileencoding=latin-1 :
5084 # -*- coding: iso-8859-1 -*-
5086 foo = True # another comment"
5087 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
5089 (ert-deftest python-info-encoding-1 ()
5090 "Should return the detected encoding from cookie."
5091 (python-tests-with-temp-buffer
5092 "# vim: set fileencoding=latin-1 :
5094 foo = True # another comment"
5095 (should (eq (python-info-encoding) 'latin-1))))
5097 (ert-deftest python-info-encoding-2 ()
5098 "Should default to utf-8."
5099 (python-tests-with-temp-buffer
5100 "# No encoding for you
5102 foo = True # another comment"
5103 (should (eq (python-info-encoding) 'utf-8))))
5106 ;;; Utility functions
5108 (ert-deftest python-util-goto-line-1 ()
5109 (python-tests-with-temp-buffer
5110 (concat
5111 "# a comment
5112 # another comment
5113 def foo(a, b, c):
5114 pass" (make-string 20 ?\n))
5115 (python-util-goto-line 10)
5116 (should (= (line-number-at-pos) 10))
5117 (python-util-goto-line 20)
5118 (should (= (line-number-at-pos) 20))))
5120 (ert-deftest python-util-clone-local-variables-1 ()
5121 (let ((buffer (generate-new-buffer
5122 "python-util-clone-local-variables-1"))
5123 (varcons
5124 '((python-fill-docstring-style . django)
5125 (python-shell-interpreter . "python")
5126 (python-shell-interpreter-args . "manage.py shell")
5127 (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
5128 (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
5129 (python-shell-extra-pythonpaths "/home/user/pylib/")
5130 (python-shell-completion-setup-code
5131 . "from IPython.core.completerlib import module_completion")
5132 (python-shell-completion-string-code
5133 . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
5134 (python-shell-virtualenv-root
5135 . "/home/user/.virtualenvs/project"))))
5136 (with-current-buffer buffer
5137 (kill-all-local-variables)
5138 (dolist (ccons varcons)
5139 (set (make-local-variable (car ccons)) (cdr ccons))))
5140 (python-tests-with-temp-buffer
5142 (python-util-clone-local-variables buffer)
5143 (dolist (ccons varcons)
5144 (should
5145 (equal (symbol-value (car ccons)) (cdr ccons)))))
5146 (kill-buffer buffer)))
5148 (ert-deftest python-util-strip-string-1 ()
5149 (should (string= (python-util-strip-string "\t\r\n str") "str"))
5150 (should (string= (python-util-strip-string "str \n\r") "str"))
5151 (should (string= (python-util-strip-string "\t\r\n str \n\r ") "str"))
5152 (should
5153 (string= (python-util-strip-string "\n str \nin \tg \n\r") "str \nin \tg"))
5154 (should (string= (python-util-strip-string "\n \t \n\r ") ""))
5155 (should (string= (python-util-strip-string "") "")))
5157 (ert-deftest python-util-forward-comment-1 ()
5158 (python-tests-with-temp-buffer
5159 (concat
5160 "# a comment
5161 # another comment
5162 # bad indented comment
5163 # more comments" (make-string 9999 ?\n))
5164 (python-util-forward-comment 1)
5165 (should (= (point) (point-max)))
5166 (python-util-forward-comment -1)
5167 (should (= (point) (point-min)))))
5169 (ert-deftest python-util-valid-regexp-p-1 ()
5170 (should (python-util-valid-regexp-p ""))
5171 (should (python-util-valid-regexp-p python-shell-prompt-regexp))
5172 (should (not (python-util-valid-regexp-p "\\("))))
5175 ;;; Electricity
5177 (ert-deftest python-parens-electric-indent-1 ()
5178 (let ((eim electric-indent-mode))
5179 (unwind-protect
5180 (progn
5181 (python-tests-with-temp-buffer
5183 from django.conf.urls import patterns, include, url
5185 from django.contrib import admin
5187 from myapp import views
5190 urlpatterns = patterns('',
5191 url(r'^$', views.index
5194 (electric-indent-mode 1)
5195 (python-tests-look-at "views.index")
5196 (end-of-line)
5198 ;; Inserting commas within the same line should leave
5199 ;; indentation unchanged.
5200 (python-tests-self-insert ",")
5201 (should (= (current-indentation) 4))
5203 ;; As well as any other input happening within the same
5204 ;; set of parens.
5205 (python-tests-self-insert " name='index')")
5206 (should (= (current-indentation) 4))
5208 ;; But a comma outside it, should trigger indentation.
5209 (python-tests-self-insert ",")
5210 (should (= (current-indentation) 23))
5212 ;; Newline indents to the first argument column
5213 (python-tests-self-insert "\n")
5214 (should (= (current-indentation) 23))
5216 ;; All this input must not change indentation
5217 (indent-line-to 4)
5218 (python-tests-self-insert "url(r'^/login$', views.login)")
5219 (should (= (current-indentation) 4))
5221 ;; But this comma does
5222 (python-tests-self-insert ",")
5223 (should (= (current-indentation) 23))))
5224 (or eim (electric-indent-mode -1)))))
5226 (ert-deftest python-triple-quote-pairing ()
5227 (let ((epm electric-pair-mode))
5228 (unwind-protect
5229 (progn
5230 (python-tests-with-temp-buffer
5231 "\"\"\n"
5232 (or epm (electric-pair-mode 1))
5233 (goto-char (1- (point-max)))
5234 (python-tests-self-insert ?\")
5235 (should (string= (buffer-string)
5236 "\"\"\"\"\"\"\n"))
5237 (should (= (point) 4)))
5238 (python-tests-with-temp-buffer
5239 "\n"
5240 (python-tests-self-insert (list ?\" ?\" ?\"))
5241 (should (string= (buffer-string)
5242 "\"\"\"\"\"\"\n"))
5243 (should (= (point) 4)))
5244 (python-tests-with-temp-buffer
5245 "\"\n\"\"\n"
5246 (goto-char (1- (point-max)))
5247 (python-tests-self-insert ?\")
5248 (should (= (point) (1- (point-max))))
5249 (should (string= (buffer-string)
5250 "\"\n\"\"\"\n"))))
5251 (or epm (electric-pair-mode -1)))))
5254 ;;; Hideshow support
5256 (ert-deftest python-hideshow-hide-levels-1 ()
5257 "Should hide all methods when called after class start."
5258 (let ((enabled hs-minor-mode))
5259 (unwind-protect
5260 (progn
5261 (python-tests-with-temp-buffer
5263 class SomeClass:
5265 def __init__(self, arg, kwarg=1):
5266 self.arg = arg
5267 self.kwarg = kwarg
5269 def filter(self, nums):
5270 def fn(item):
5271 return item in [self.arg, self.kwarg]
5272 return filter(fn, nums)
5274 def __str__(self):
5275 return '%s-%s' % (self.arg, self.kwarg)
5277 (hs-minor-mode 1)
5278 (python-tests-look-at "class SomeClass:")
5279 (forward-line)
5280 (hs-hide-level 1)
5281 (should
5282 (string=
5283 (python-tests-visible-string)
5285 class SomeClass:
5287 def __init__(self, arg, kwarg=1):
5288 def filter(self, nums):
5289 def __str__(self):"))))
5290 (or enabled (hs-minor-mode -1)))))
5292 (ert-deftest python-hideshow-hide-levels-2 ()
5293 "Should hide nested methods and parens at end of defun."
5294 (let ((enabled hs-minor-mode))
5295 (unwind-protect
5296 (progn
5297 (python-tests-with-temp-buffer
5299 class SomeClass:
5301 def __init__(self, arg, kwarg=1):
5302 self.arg = arg
5303 self.kwarg = kwarg
5305 def filter(self, nums):
5306 def fn(item):
5307 return item in [self.arg, self.kwarg]
5308 return filter(fn, nums)
5310 def __str__(self):
5311 return '%s-%s' % (self.arg, self.kwarg)
5313 (hs-minor-mode 1)
5314 (python-tests-look-at "def fn(item):")
5315 (hs-hide-block)
5316 (should
5317 (string=
5318 (python-tests-visible-string)
5320 class SomeClass:
5322 def __init__(self, arg, kwarg=1):
5323 self.arg = arg
5324 self.kwarg = kwarg
5326 def filter(self, nums):
5327 def fn(item):
5328 return filter(fn, nums)
5330 def __str__(self):
5331 return '%s-%s' % (self.arg, self.kwarg)
5332 "))))
5333 (or enabled (hs-minor-mode -1)))))
5336 (ert-deftest python-tests--python-nav-end-of-statement--infloop ()
5337 "Checks that `python-nav-end-of-statement' doesn't infloop in a
5338 buffer with overlapping strings."
5339 (python-tests-with-temp-buffer "''' '\n''' ' '\n"
5340 (syntax-propertize (point-max))
5341 ;; Create a situation where strings nominally overlap. This
5342 ;; shouldn't happen in practice, but apparently it can happen when
5343 ;; a package calls `syntax-ppss' in a narrowed buffer during JIT
5344 ;; lock.
5345 (put-text-property 4 5 'syntax-table (string-to-syntax "|"))
5346 (remove-text-properties 8 9 '(syntax-table nil))
5347 (goto-char 4)
5348 (setq-local syntax-propertize-function nil)
5349 ;; The next form should not infloop. We have to disable
5350 ;; ‘debug-on-error’ so that ‘cl-assert’ doesn’t call the debugger.
5351 (should-error (let ((debug-on-error nil))
5352 (python-nav-end-of-statement)))
5353 (should (eolp))))
5355 ;; After call `run-python' the buffer running the python process is current.
5356 (ert-deftest python-tests--bug31398 ()
5357 "Test for https://debbugs.gnu.org/31398 ."
5358 (skip-unless (executable-find python-tests-shell-interpreter))
5359 (let ((buffer (process-buffer (run-python nil nil 'show))))
5360 (should (eq buffer (current-buffer)))
5361 (pop-to-buffer (other-buffer))
5362 (run-python nil nil 'show)
5363 (should (eq buffer (current-buffer)))))
5365 (provide 'python-tests)
5367 ;; Local Variables:
5368 ;; indent-tabs-mode: nil
5369 ;; End:
5371 ;;; python-tests.el ends here