]> code.delx.au - gnu-emacs/blob - test/automated/python-tests.el
substitute-command-keys keeps quotes’ text props
[gnu-emacs] / test / automated / python-tests.el
1 ;;; python-tests.el --- Test suite for python.el
2
3 ;; Copyright (C) 2013-2016 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
7 ;; GNU Emacs is free software: you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation, either version 3 of the License, or
10 ;; (at your option) any later version.
11
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
16
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
19
20 ;;; Commentary:
21
22 ;;; Code:
23
24 (require 'ert)
25 (require 'python)
26
27 ;; Dependencies for testing:
28 (require 'electric)
29 (require 'hideshow)
30 (require 'tramp-sh)
31
32
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)))
44
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))))
62
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)))))
96
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)))
114
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)))))
136
137 \f
138 ;;; Tests for your tests, so you can test while you test.
139
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)))))
159
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)))))
175
176 \f
177 ;;; Bindings
178
179 \f
180 ;;; Python specialized rx
181
182 \f
183 ;;; Font-lock and syntax
184
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))))))
194
195 \f
196 ;;; Indentation
197
198 ;; See: http://www.python.org/dev/peps/pep-0008/#indentation
199
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)
206 "
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))))
215
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)
224 "
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))))
242
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)
250 "
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))))
262
263 (ert-deftest python-indent-base-case ()
264 "Check base case does not trigger errors."
265 (python-tests-with-temp-buffer
266 "
267
268 "
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))))
278
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.
290 "
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))))
311
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.
321
322 comment_wins_over_ender = True
323
324 # yeah, that.
325 "
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))))
356
357 (ert-deftest python-indent-after-comment-3 ()
358 "Test after-comment in buggy case."
359 (python-tests-with-temp-buffer
360 "
361 class A(object):
362
363 def something(self, arg):
364 if True:
365 return arg
366
367 # A comment
368
369 @adecorator
370 def method(self, a, b):
371 pass
372 "
373 (python-tests-look-at "@adecorator")
374 (should (eq (car (python-indent-context)) :after-comment))
375 (should (= (python-indent-calculate-indentation) 4))))
376
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
380 "
381 data = {
382 'key':
383 {
384 'objlist': [
385 {
386 'pk': 1,
387 'name': 'first',
388 },
389 {
390 'pk': 2,
391 'name': 'second',
392 }
393 ]
394 }
395 }
396 "
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))))
446
447 (ert-deftest python-indent-inside-paren-2 ()
448 "Another more compact paren group style."
449 (python-tests-with-temp-buffer
450 "
451 data = {'key': {
452 'objlist': [
453 {'pk': 1,
454 'name': 'first'},
455 {'pk': 2,
456 'name': 'second'}
457 ]
458 }}
459 "
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))))
489
490 (ert-deftest python-indent-inside-paren-3 ()
491 "The simplest case possible."
492 (python-tests-with-temp-buffer
493 "
494 data = ('these',
495 'are',
496 'the',
497 'tokens')
498 "
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))))
511
512 (ert-deftest python-indent-inside-paren-4 ()
513 "Respect indentation of first column."
514 (python-tests-with-temp-buffer
515 "
516 data = [ [ 'these', 'are'],
517 ['the', 'tokens' ] ]
518 "
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))))
525
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
529 "
530 while ((not some_condition) and
531 another_condition):
532 do_something_interesting(
533 with_some_arg)
534 "
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))))
547
548 (ert-deftest python-indent-inside-paren-6 ()
549 "This should be aligned.."
550 (python-tests-with-temp-buffer
551 "
552 CHOICES = (('some', 'choice'),
553 ('another', 'choice'),
554 ('more', 'choices'))
555 "
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))))
565
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))))
573
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
577 "
578 def foo(a, b, c=True):
579 "
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))))
585
586 (ert-deftest python-indent-after-block-2 ()
587 "A weird (malformed) multiline block statement."
588 (python-tests-with-temp-buffer
589 "
590 def foo(a, b, c={
591 'a':
592 }):
593 "
594 (goto-char (point-max))
595 (should (eq (car (python-indent-context)) :after-block-start))
596 (should (= (python-indent-calculate-indentation) 4))))
597
598 (ert-deftest python-indent-after-block-3 ()
599 "A weird (malformed) sample, usually found in python shells."
600 (python-tests-with-temp-buffer
601 "
602 In [1]:
603 def func():
604 pass
605
606 In [2]:
607 something
608 "
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))))
616
617 (ert-deftest python-indent-after-backslash-1 ()
618 "The most common case."
619 (python-tests-with-temp-buffer
620 "
621 from foo.bar.baz import something, something_1 \\\\
622 something_2 something_3, \\\\
623 something_4, something_5
624 "
625 (python-tests-look-at "from foo.bar.baz import something, something_1")
626 (should (eq (car (python-indent-context)) :no-indent))
627 (should (= (python-indent-calculate-indentation) 0))
628 (python-tests-look-at "something_2 something_3,")
629 (should (eq (car (python-indent-context)) :after-backslash-first-line))
630 (should (= (python-indent-calculate-indentation) 4))
631 (python-tests-look-at "something_4, something_5")
632 (should (eq (car (python-indent-context)) :after-backslash))
633 (should (= (python-indent-calculate-indentation) 4))
634 (goto-char (point-max))
635 (should (eq (car (python-indent-context)) :after-line))
636 (should (= (python-indent-calculate-indentation) 0))))
637
638 (ert-deftest python-indent-after-backslash-2 ()
639 "A pretty extreme complicated case."
640 (python-tests-with-temp-buffer
641 "
642 objects = Thing.objects.all() \\\\
643 .filter(
644 type='toy',
645 status='bought'
646 ) \\\\
647 .aggregate(
648 Sum('amount')
649 ) \\\\
650 .values_list()
651 "
652 (python-tests-look-at "objects = Thing.objects.all()")
653 (should (eq (car (python-indent-context)) :no-indent))
654 (should (= (python-indent-calculate-indentation) 0))
655 (python-tests-look-at ".filter(")
656 (should (eq (car (python-indent-context))
657 :after-backslash-dotted-continuation))
658 (should (= (python-indent-calculate-indentation) 23))
659 (python-tests-look-at "type='toy',")
660 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
661 (should (= (python-indent-calculate-indentation) 27))
662 (python-tests-look-at "status='bought'")
663 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
664 (should (= (python-indent-calculate-indentation) 27))
665 (python-tests-look-at ") \\\\")
666 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
667 (should (= (python-indent-calculate-indentation) 23))
668 (python-tests-look-at ".aggregate(")
669 (should (eq (car (python-indent-context))
670 :after-backslash-dotted-continuation))
671 (should (= (python-indent-calculate-indentation) 23))
672 (python-tests-look-at "Sum('amount')")
673 (should (eq (car (python-indent-context)) :inside-paren-newline-start))
674 (should (= (python-indent-calculate-indentation) 27))
675 (python-tests-look-at ") \\\\")
676 (should (eq (car (python-indent-context)) :inside-paren-at-closing-paren))
677 (should (= (python-indent-calculate-indentation) 23))
678 (python-tests-look-at ".values_list()")
679 (should (eq (car (python-indent-context))
680 :after-backslash-dotted-continuation))
681 (should (= (python-indent-calculate-indentation) 23))
682 (forward-line 1)
683 (should (eq (car (python-indent-context)) :after-line))
684 (should (= (python-indent-calculate-indentation) 0))))
685
686 (ert-deftest python-indent-after-backslash-3 ()
687 "Backslash continuation from block start."
688 (python-tests-with-temp-buffer
689 "
690 with open('/path/to/some/file/you/want/to/read') as file_1, \\\\
691 open('/path/to/some/file/being/written', 'w') as file_2:
692 file_2.write(file_1.read())
693 "
694 (python-tests-look-at
695 "with open('/path/to/some/file/you/want/to/read') as file_1, \\\\")
696 (should (eq (car (python-indent-context)) :no-indent))
697 (should (= (python-indent-calculate-indentation) 0))
698 (python-tests-look-at
699 "open('/path/to/some/file/being/written', 'w') as file_2")
700 (should (eq (car (python-indent-context))
701 :after-backslash-block-continuation))
702 (should (= (python-indent-calculate-indentation) 5))
703 (python-tests-look-at "file_2.write(file_1.read())")
704 (should (eq (car (python-indent-context)) :after-block-start))
705 (should (= (python-indent-calculate-indentation) 4))))
706
707 (ert-deftest python-indent-after-backslash-4 ()
708 "Backslash continuation from assignment."
709 (python-tests-with-temp-buffer
710 "
711 super_awful_assignment = some_calculation() and \\\\
712 another_calculation() and \\\\
713 some_final_calculation()
714 "
715 (python-tests-look-at
716 "super_awful_assignment = some_calculation() and \\\\")
717 (should (eq (car (python-indent-context)) :no-indent))
718 (should (= (python-indent-calculate-indentation) 0))
719 (python-tests-look-at "another_calculation() and \\\\")
720 (should (eq (car (python-indent-context))
721 :after-backslash-assignment-continuation))
722 (should (= (python-indent-calculate-indentation) 25))
723 (python-tests-look-at "some_final_calculation()")
724 (should (eq (car (python-indent-context)) :after-backslash))
725 (should (= (python-indent-calculate-indentation) 25))))
726
727 (ert-deftest python-indent-after-backslash-5 ()
728 "Dotted continuation bizarre example."
729 (python-tests-with-temp-buffer
730 "
731 def delete_all_things():
732 Thing \\\\
733 .objects.all() \\\\
734 .delete()
735 "
736 (python-tests-look-at "Thing \\\\")
737 (should (eq (car (python-indent-context)) :after-block-start))
738 (should (= (python-indent-calculate-indentation) 4))
739 (python-tests-look-at ".objects.all() \\\\")
740 (should (eq (car (python-indent-context)) :after-backslash-first-line))
741 (should (= (python-indent-calculate-indentation) 8))
742 (python-tests-look-at ".delete()")
743 (should (eq (car (python-indent-context))
744 :after-backslash-dotted-continuation))
745 (should (= (python-indent-calculate-indentation) 16))))
746
747 (ert-deftest python-indent-block-enders-1 ()
748 "Test de-indentation for pass keyword."
749 (python-tests-with-temp-buffer
750 "
751 Class foo(object):
752
753 def bar(self):
754 if self.baz:
755 return (1,
756 2,
757 3)
758
759 else:
760 pass
761 "
762 (python-tests-look-at "3)")
763 (forward-line 1)
764 (should (= (python-indent-calculate-indentation) 8))
765 (python-tests-look-at "pass")
766 (forward-line 1)
767 (should (eq (car (python-indent-context)) :after-block-end))
768 (should (= (python-indent-calculate-indentation) 8))))
769
770 (ert-deftest python-indent-block-enders-2 ()
771 "Test de-indentation for return keyword."
772 (python-tests-with-temp-buffer
773 "
774 Class foo(object):
775 '''raise lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
776
777 eiusmod tempor incididunt ut labore et dolore magna aliqua.
778 '''
779 def bar(self):
780 \"return (1, 2, 3).\"
781 if self.baz:
782 return (1,
783 2,
784 3)
785 "
786 (python-tests-look-at "def")
787 (should (= (python-indent-calculate-indentation) 4))
788 (python-tests-look-at "if")
789 (should (= (python-indent-calculate-indentation) 8))
790 (python-tests-look-at "return")
791 (should (= (python-indent-calculate-indentation) 12))
792 (goto-char (point-max))
793 (should (eq (car (python-indent-context)) :after-block-end))
794 (should (= (python-indent-calculate-indentation) 8))))
795
796 (ert-deftest python-indent-block-enders-3 ()
797 "Test de-indentation for continue keyword."
798 (python-tests-with-temp-buffer
799 "
800 for element in lst:
801 if element is None:
802 continue
803 "
804 (python-tests-look-at "if")
805 (should (= (python-indent-calculate-indentation) 4))
806 (python-tests-look-at "continue")
807 (should (= (python-indent-calculate-indentation) 8))
808 (forward-line 1)
809 (should (eq (car (python-indent-context)) :after-block-end))
810 (should (= (python-indent-calculate-indentation) 4))))
811
812 (ert-deftest python-indent-block-enders-4 ()
813 "Test de-indentation for break keyword."
814 (python-tests-with-temp-buffer
815 "
816 for element in lst:
817 if element is None:
818 break
819 "
820 (python-tests-look-at "if")
821 (should (= (python-indent-calculate-indentation) 4))
822 (python-tests-look-at "break")
823 (should (= (python-indent-calculate-indentation) 8))
824 (forward-line 1)
825 (should (eq (car (python-indent-context)) :after-block-end))
826 (should (= (python-indent-calculate-indentation) 4))))
827
828 (ert-deftest python-indent-block-enders-5 ()
829 "Test de-indentation for raise keyword."
830 (python-tests-with-temp-buffer
831 "
832 for element in lst:
833 if element is None:
834 raise ValueError('Element cannot be None')
835 "
836 (python-tests-look-at "if")
837 (should (= (python-indent-calculate-indentation) 4))
838 (python-tests-look-at "raise")
839 (should (= (python-indent-calculate-indentation) 8))
840 (forward-line 1)
841 (should (eq (car (python-indent-context)) :after-block-end))
842 (should (= (python-indent-calculate-indentation) 4))))
843
844 (ert-deftest python-indent-dedenters-1 ()
845 "Test de-indentation for the elif keyword."
846 (python-tests-with-temp-buffer
847 "
848 if save:
849 try:
850 write_to_disk(data)
851 finally:
852 cleanup()
853 elif
854 "
855 (python-tests-look-at "elif\n")
856 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
857 (should (= (python-indent-calculate-indentation) 0))
858 (should (= (python-indent-calculate-indentation t) 0))))
859
860 (ert-deftest python-indent-dedenters-2 ()
861 "Test de-indentation for the else keyword."
862 (python-tests-with-temp-buffer
863 "
864 if save:
865 try:
866 write_to_disk(data)
867 except IOError:
868 msg = 'Error saving to disk'
869 message(msg)
870 logger.exception(msg)
871 except Exception:
872 if hide_details:
873 logger.exception('Unhandled exception')
874 else
875 finally:
876 data.free()
877 "
878 (python-tests-look-at "else\n")
879 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
880 (should (= (python-indent-calculate-indentation) 8))
881 (python-indent-line t)
882 (should (= (python-indent-calculate-indentation t) 4))
883 (python-indent-line t)
884 (should (= (python-indent-calculate-indentation t) 0))
885 (python-indent-line t)
886 (should (= (python-indent-calculate-indentation t) 8))))
887
888 (ert-deftest python-indent-dedenters-3 ()
889 "Test de-indentation for the except keyword."
890 (python-tests-with-temp-buffer
891 "
892 if save:
893 try:
894 write_to_disk(data)
895 except
896 "
897 (python-tests-look-at "except\n")
898 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
899 (should (= (python-indent-calculate-indentation) 4))
900 (python-indent-line t)
901 (should (= (python-indent-calculate-indentation t) 4))))
902
903 (ert-deftest python-indent-dedenters-4 ()
904 "Test de-indentation for the finally keyword."
905 (python-tests-with-temp-buffer
906 "
907 if save:
908 try:
909 write_to_disk(data)
910 finally
911 "
912 (python-tests-look-at "finally\n")
913 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
914 (should (= (python-indent-calculate-indentation) 4))
915 (python-indent-line t)
916 (should (= (python-indent-calculate-indentation) 4))))
917
918 (ert-deftest python-indent-dedenters-5 ()
919 "Test invalid levels are skipped in a complex example."
920 (python-tests-with-temp-buffer
921 "
922 if save:
923 try:
924 write_to_disk(data)
925 except IOError:
926 msg = 'Error saving to disk'
927 message(msg)
928 logger.exception(msg)
929 finally:
930 if cleanup:
931 do_cleanup()
932 else
933 "
934 (python-tests-look-at "else\n")
935 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
936 (should (= (python-indent-calculate-indentation) 8))
937 (should (= (python-indent-calculate-indentation t) 0))
938 (python-indent-line t)
939 (should (= (python-indent-calculate-indentation t) 8))))
940
941 (ert-deftest python-indent-dedenters-6 ()
942 "Test indentation is zero when no opening block for dedenter."
943 (python-tests-with-temp-buffer
944 "
945 try:
946 # if save:
947 write_to_disk(data)
948 else
949 "
950 (python-tests-look-at "else\n")
951 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
952 (should (= (python-indent-calculate-indentation) 0))
953 (should (= (python-indent-calculate-indentation t) 0))))
954
955 (ert-deftest python-indent-dedenters-7 ()
956 "Test indentation case from Bug#15163."
957 (python-tests-with-temp-buffer
958 "
959 if a:
960 if b:
961 pass
962 else:
963 pass
964 else:
965 "
966 (python-tests-look-at "else:" 2)
967 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
968 (should (= (python-indent-calculate-indentation) 0))
969 (should (= (python-indent-calculate-indentation t) 0))))
970
971 (ert-deftest python-indent-dedenters-8 ()
972 "Test indentation for Bug#18432."
973 (python-tests-with-temp-buffer
974 "
975 if (a == 1 or
976 a == 2):
977 pass
978 elif (a == 3 or
979 a == 4):
980 "
981 (python-tests-look-at "elif (a == 3 or")
982 (should (eq (car (python-indent-context)) :at-dedenter-block-start))
983 (should (= (python-indent-calculate-indentation) 0))
984 (should (= (python-indent-calculate-indentation t) 0))
985 (python-tests-look-at "a == 4):\n")
986 (should (eq (car (python-indent-context)) :inside-paren))
987 (should (= (python-indent-calculate-indentation) 6))
988 (python-indent-line)
989 (should (= (python-indent-calculate-indentation t) 4))
990 (python-indent-line t)
991 (should (= (python-indent-calculate-indentation t) 0))
992 (python-indent-line t)
993 (should (= (python-indent-calculate-indentation t) 6))))
994
995 (ert-deftest python-indent-inside-string-1 ()
996 "Test indentation for strings."
997 (python-tests-with-temp-buffer
998 "
999 multiline = '''
1000 bunch
1001 of
1002 lines
1003 '''
1004 "
1005 (python-tests-look-at "multiline = '''")
1006 (should (eq (car (python-indent-context)) :no-indent))
1007 (should (= (python-indent-calculate-indentation) 0))
1008 (python-tests-look-at "bunch")
1009 (should (eq (car (python-indent-context)) :inside-string))
1010 (should (= (python-indent-calculate-indentation) 0))
1011 (python-tests-look-at "of")
1012 (should (eq (car (python-indent-context)) :inside-string))
1013 (should (= (python-indent-calculate-indentation) 0))
1014 (python-tests-look-at "lines")
1015 (should (eq (car (python-indent-context)) :inside-string))
1016 (should (= (python-indent-calculate-indentation) 0))
1017 (python-tests-look-at "'''")
1018 (should (eq (car (python-indent-context)) :inside-string))
1019 (should (= (python-indent-calculate-indentation) 0))))
1020
1021 (ert-deftest python-indent-inside-string-2 ()
1022 "Test indentation for docstrings."
1023 (python-tests-with-temp-buffer
1024 "
1025 def fn(a, b, c=True):
1026 '''docstring
1027 bunch
1028 of
1029 lines
1030 '''
1031 "
1032 (python-tests-look-at "'''docstring")
1033 (should (eq (car (python-indent-context)) :after-block-start))
1034 (should (= (python-indent-calculate-indentation) 4))
1035 (python-tests-look-at "bunch")
1036 (should (eq (car (python-indent-context)) :inside-docstring))
1037 (should (= (python-indent-calculate-indentation) 4))
1038 (python-tests-look-at "of")
1039 (should (eq (car (python-indent-context)) :inside-docstring))
1040 ;; Any indentation deeper than the base-indent must remain unmodified.
1041 (should (= (python-indent-calculate-indentation) 8))
1042 (python-tests-look-at "lines")
1043 (should (eq (car (python-indent-context)) :inside-docstring))
1044 (should (= (python-indent-calculate-indentation) 4))
1045 (python-tests-look-at "'''")
1046 (should (eq (car (python-indent-context)) :inside-docstring))
1047 (should (= (python-indent-calculate-indentation) 4))))
1048
1049 (ert-deftest python-indent-inside-string-3 ()
1050 "Test indentation for nested strings."
1051 (python-tests-with-temp-buffer
1052 "
1053 def fn(a, b, c=True):
1054 some_var = '''
1055 bunch
1056 of
1057 lines
1058 '''
1059 "
1060 (python-tests-look-at "some_var = '''")
1061 (should (eq (car (python-indent-context)) :after-block-start))
1062 (should (= (python-indent-calculate-indentation) 4))
1063 (python-tests-look-at "bunch")
1064 (should (eq (car (python-indent-context)) :inside-string))
1065 (should (= (python-indent-calculate-indentation) 4))
1066 (python-tests-look-at "of")
1067 (should (eq (car (python-indent-context)) :inside-string))
1068 (should (= (python-indent-calculate-indentation) 4))
1069 (python-tests-look-at "lines")
1070 (should (eq (car (python-indent-context)) :inside-string))
1071 (should (= (python-indent-calculate-indentation) 4))
1072 (python-tests-look-at "'''")
1073 (should (eq (car (python-indent-context)) :inside-string))
1074 (should (= (python-indent-calculate-indentation) 4))))
1075
1076 (ert-deftest python-indent-electric-colon-1 ()
1077 "Test indentation case from Bug#18228."
1078 (python-tests-with-temp-buffer
1079 "
1080 def a():
1081 pass
1082
1083 def b()
1084 "
1085 (python-tests-look-at "def b()")
1086 (goto-char (line-end-position))
1087 (python-tests-self-insert ":")
1088 (should (= (current-indentation) 0))))
1089
1090 (ert-deftest python-indent-electric-colon-2 ()
1091 "Test indentation case for dedenter."
1092 (python-tests-with-temp-buffer
1093 "
1094 if do:
1095 something()
1096 else
1097 "
1098 (python-tests-look-at "else")
1099 (goto-char (line-end-position))
1100 (python-tests-self-insert ":")
1101 (should (= (current-indentation) 0))))
1102
1103 (ert-deftest python-indent-electric-colon-3 ()
1104 "Test indentation case for multi-line dedenter."
1105 (python-tests-with-temp-buffer
1106 "
1107 if do:
1108 something()
1109 elif (this
1110 and
1111 that)
1112 "
1113 (python-tests-look-at "that)")
1114 (goto-char (line-end-position))
1115 (python-tests-self-insert ":")
1116 (python-tests-look-at "elif" -1)
1117 (should (= (current-indentation) 0))
1118 (python-tests-look-at "and")
1119 (should (= (current-indentation) 6))
1120 (python-tests-look-at "that)")
1121 (should (= (current-indentation) 6))))
1122
1123 (ert-deftest python-indent-region-1 ()
1124 "Test indentation case from Bug#18843."
1125 (let ((contents "
1126 def foo ():
1127 try:
1128 pass
1129 except:
1130 pass
1131 "))
1132 (python-tests-with-temp-buffer
1133 contents
1134 (python-indent-region (point-min) (point-max))
1135 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1136 contents)))))
1137
1138 (ert-deftest python-indent-region-2 ()
1139 "Test region indentation on comments."
1140 (let ((contents "
1141 def f():
1142 if True:
1143 pass
1144
1145 # This is
1146 # some multiline
1147 # comment
1148 "))
1149 (python-tests-with-temp-buffer
1150 contents
1151 (python-indent-region (point-min) (point-max))
1152 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1153 contents)))))
1154
1155 (ert-deftest python-indent-region-3 ()
1156 "Test region indentation on comments."
1157 (let ((contents "
1158 def f():
1159 if True:
1160 pass
1161 # This is
1162 # some multiline
1163 # comment
1164 ")
1165 (expected "
1166 def f():
1167 if True:
1168 pass
1169 # This is
1170 # some multiline
1171 # comment
1172 "))
1173 (python-tests-with-temp-buffer
1174 contents
1175 (python-indent-region (point-min) (point-max))
1176 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1177 expected)))))
1178
1179 (ert-deftest python-indent-region-4 ()
1180 "Test region indentation block starts, dedenters and enders."
1181 (let ((contents "
1182 def f():
1183 if True:
1184 a = 5
1185 else:
1186 a = 10
1187 return a
1188 ")
1189 (expected "
1190 def f():
1191 if True:
1192 a = 5
1193 else:
1194 a = 10
1195 return a
1196 "))
1197 (python-tests-with-temp-buffer
1198 contents
1199 (python-indent-region (point-min) (point-max))
1200 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1201 expected)))))
1202
1203 (ert-deftest python-indent-region-5 ()
1204 "Test region indentation for docstrings."
1205 (let ((contents "
1206 def f():
1207 '''
1208 this is
1209 a multiline
1210 string
1211 '''
1212 x = \\
1213 '''
1214 this is an arbitrarily
1215 indented multiline
1216 string
1217 '''
1218 ")
1219 (expected "
1220 def f():
1221 '''
1222 this is
1223 a multiline
1224 string
1225 '''
1226 x = \\
1227 '''
1228 this is an arbitrarily
1229 indented multiline
1230 string
1231 '''
1232 "))
1233 (python-tests-with-temp-buffer
1234 contents
1235 (python-indent-region (point-min) (point-max))
1236 (should (string= (buffer-substring-no-properties (point-min) (point-max))
1237 expected)))))
1238
1239 \f
1240 ;;; Mark
1241
1242 (ert-deftest python-mark-defun-1 ()
1243 """Test `python-mark-defun' with point at defun symbol start."""
1244 (python-tests-with-temp-buffer
1245 "
1246 def foo(x):
1247 return x
1248
1249 class A:
1250 pass
1251
1252 class B:
1253
1254 def __init__(self):
1255 self.b = 'b'
1256
1257 def fun(self):
1258 return self.b
1259
1260 class C:
1261 '''docstring'''
1262 "
1263 (let ((expected-mark-beginning-position
1264 (progn
1265 (python-tests-look-at "class A:")
1266 (1- (point))))
1267 (expected-mark-end-position-1
1268 (save-excursion
1269 (python-tests-look-at "pass")
1270 (forward-line)
1271 (point)))
1272 (expected-mark-end-position-2
1273 (save-excursion
1274 (python-tests-look-at "return self.b")
1275 (forward-line)
1276 (point)))
1277 (expected-mark-end-position-3
1278 (save-excursion
1279 (python-tests-look-at "'''docstring'''")
1280 (forward-line)
1281 (point))))
1282 ;; Select class A only, with point at bol.
1283 (python-mark-defun 1)
1284 (should (= (point) expected-mark-beginning-position))
1285 (should (= (marker-position (mark-marker))
1286 expected-mark-end-position-1))
1287 ;; expand to class B, start position should remain the same.
1288 (python-mark-defun 1)
1289 (should (= (point) expected-mark-beginning-position))
1290 (should (= (marker-position (mark-marker))
1291 expected-mark-end-position-2))
1292 ;; expand to class C, start position should remain the same.
1293 (python-mark-defun 1)
1294 (should (= (point) expected-mark-beginning-position))
1295 (should (= (marker-position (mark-marker))
1296 expected-mark-end-position-3)))))
1297
1298 (ert-deftest python-mark-defun-2 ()
1299 """Test `python-mark-defun' with point at nested defun symbol start."""
1300 (python-tests-with-temp-buffer
1301 "
1302 def foo(x):
1303 return x
1304
1305 class A:
1306 pass
1307
1308 class B:
1309
1310 def __init__(self):
1311 self.b = 'b'
1312
1313 def fun(self):
1314 return self.b
1315
1316 class C:
1317 '''docstring'''
1318 "
1319 (let ((expected-mark-beginning-position
1320 (progn
1321 (python-tests-look-at "def __init__(self):")
1322 (1- (line-beginning-position))))
1323 (expected-mark-end-position-1
1324 (save-excursion
1325 (python-tests-look-at "self.b = 'b'")
1326 (forward-line)
1327 (point)))
1328 (expected-mark-end-position-2
1329 (save-excursion
1330 (python-tests-look-at "return self.b")
1331 (forward-line)
1332 (point)))
1333 (expected-mark-end-position-3
1334 (save-excursion
1335 (python-tests-look-at "'''docstring'''")
1336 (forward-line)
1337 (point))))
1338 ;; Select B.__init only, with point at its start.
1339 (python-mark-defun 1)
1340 (should (= (point) expected-mark-beginning-position))
1341 (should (= (marker-position (mark-marker))
1342 expected-mark-end-position-1))
1343 ;; expand to B.fun, start position should remain the same.
1344 (python-mark-defun 1)
1345 (should (= (point) expected-mark-beginning-position))
1346 (should (= (marker-position (mark-marker))
1347 expected-mark-end-position-2))
1348 ;; expand to class C, start position should remain the same.
1349 (python-mark-defun 1)
1350 (should (= (point) expected-mark-beginning-position))
1351 (should (= (marker-position (mark-marker))
1352 expected-mark-end-position-3)))))
1353
1354 (ert-deftest python-mark-defun-3 ()
1355 """Test `python-mark-defun' with point inside defun symbol."""
1356 (python-tests-with-temp-buffer
1357 "
1358 def foo(x):
1359 return x
1360
1361 class A:
1362 pass
1363
1364 class B:
1365
1366 def __init__(self):
1367 self.b = 'b'
1368
1369 def fun(self):
1370 return self.b
1371
1372 class C:
1373 '''docstring'''
1374 "
1375 (let ((expected-mark-beginning-position
1376 (progn
1377 (python-tests-look-at "def fun(self):")
1378 (python-tests-look-at "(self):")
1379 (1- (line-beginning-position))))
1380 (expected-mark-end-position
1381 (save-excursion
1382 (python-tests-look-at "return self.b")
1383 (forward-line)
1384 (point))))
1385 ;; Should select B.fun, despite point is inside the defun symbol.
1386 (python-mark-defun 1)
1387 (should (= (point) expected-mark-beginning-position))
1388 (should (= (marker-position (mark-marker))
1389 expected-mark-end-position)))))
1390
1391 \f
1392 ;;; Navigation
1393
1394 (ert-deftest python-nav-beginning-of-defun-1 ()
1395 (python-tests-with-temp-buffer
1396 "
1397 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1398 '''print decorated function call data to stdout.
1399
1400 Usage:
1401
1402 @decoratorFunctionWithArguments('arg1', 'arg2')
1403 def func(a, b, c=True):
1404 pass
1405 '''
1406
1407 def wwrap(f):
1408 print 'Inside wwrap()'
1409 def wrapped_f(*args):
1410 print 'Inside wrapped_f()'
1411 print 'Decorator arguments:', arg1, arg2, arg3
1412 f(*args)
1413 print 'After f(*args)'
1414 return wrapped_f
1415 return wwrap
1416 "
1417 (python-tests-look-at "return wrap")
1418 (should (= (save-excursion
1419 (python-nav-beginning-of-defun)
1420 (point))
1421 (save-excursion
1422 (python-tests-look-at "def wrapped_f(*args):" -1)
1423 (beginning-of-line)
1424 (point))))
1425 (python-tests-look-at "def wrapped_f(*args):" -1)
1426 (should (= (save-excursion
1427 (python-nav-beginning-of-defun)
1428 (point))
1429 (save-excursion
1430 (python-tests-look-at "def wwrap(f):" -1)
1431 (beginning-of-line)
1432 (point))))
1433 (python-tests-look-at "def wwrap(f):" -1)
1434 (should (= (save-excursion
1435 (python-nav-beginning-of-defun)
1436 (point))
1437 (save-excursion
1438 (python-tests-look-at "def decoratorFunctionWithArguments" -1)
1439 (beginning-of-line)
1440 (point))))))
1441
1442 (ert-deftest python-nav-beginning-of-defun-2 ()
1443 (python-tests-with-temp-buffer
1444 "
1445 class C(object):
1446
1447 def m(self):
1448 self.c()
1449
1450 def b():
1451 pass
1452
1453 def a():
1454 pass
1455
1456 def c(self):
1457 pass
1458 "
1459 ;; Nested defuns, are handled with care.
1460 (python-tests-look-at "def c(self):")
1461 (should (= (save-excursion
1462 (python-nav-beginning-of-defun)
1463 (point))
1464 (save-excursion
1465 (python-tests-look-at "def m(self):" -1)
1466 (beginning-of-line)
1467 (point))))
1468 ;; Defuns on same levels should be respected.
1469 (python-tests-look-at "def a():" -1)
1470 (should (= (save-excursion
1471 (python-nav-beginning-of-defun)
1472 (point))
1473 (save-excursion
1474 (python-tests-look-at "def b():" -1)
1475 (beginning-of-line)
1476 (point))))
1477 ;; Jump to a top level defun.
1478 (python-tests-look-at "def b():" -1)
1479 (should (= (save-excursion
1480 (python-nav-beginning-of-defun)
1481 (point))
1482 (save-excursion
1483 (python-tests-look-at "def m(self):" -1)
1484 (beginning-of-line)
1485 (point))))
1486 ;; Jump to a top level defun again.
1487 (python-tests-look-at "def m(self):" -1)
1488 (should (= (save-excursion
1489 (python-nav-beginning-of-defun)
1490 (point))
1491 (save-excursion
1492 (python-tests-look-at "class C(object):" -1)
1493 (beginning-of-line)
1494 (point))))))
1495
1496 (ert-deftest python-nav-end-of-defun-1 ()
1497 (python-tests-with-temp-buffer
1498 "
1499 class C(object):
1500
1501 def m(self):
1502 self.c()
1503
1504 def b():
1505 pass
1506
1507 def a():
1508 pass
1509
1510 def c(self):
1511 pass
1512 "
1513 (should (= (save-excursion
1514 (python-tests-look-at "class C(object):")
1515 (python-nav-end-of-defun)
1516 (point))
1517 (save-excursion
1518 (point-max))))
1519 (should (= (save-excursion
1520 (python-tests-look-at "def m(self):")
1521 (python-nav-end-of-defun)
1522 (point))
1523 (save-excursion
1524 (python-tests-look-at "def c(self):")
1525 (forward-line -1)
1526 (point))))
1527 (should (= (save-excursion
1528 (python-tests-look-at "def b():")
1529 (python-nav-end-of-defun)
1530 (point))
1531 (save-excursion
1532 (python-tests-look-at "def b():")
1533 (forward-line 2)
1534 (point))))
1535 (should (= (save-excursion
1536 (python-tests-look-at "def c(self):")
1537 (python-nav-end-of-defun)
1538 (point))
1539 (save-excursion
1540 (point-max))))))
1541
1542 (ert-deftest python-nav-end-of-defun-2 ()
1543 (python-tests-with-temp-buffer
1544 "
1545 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1546 '''print decorated function call data to stdout.
1547
1548 Usage:
1549
1550 @decoratorFunctionWithArguments('arg1', 'arg2')
1551 def func(a, b, c=True):
1552 pass
1553 '''
1554
1555 def wwrap(f):
1556 print 'Inside wwrap()'
1557 def wrapped_f(*args):
1558 print 'Inside wrapped_f()'
1559 print 'Decorator arguments:', arg1, arg2, arg3
1560 f(*args)
1561 print 'After f(*args)'
1562 return wrapped_f
1563 return wwrap
1564 "
1565 (should (= (save-excursion
1566 (python-tests-look-at "def decoratorFunctionWithArguments")
1567 (python-nav-end-of-defun)
1568 (point))
1569 (save-excursion
1570 (point-max))))
1571 (should (= (save-excursion
1572 (python-tests-look-at "@decoratorFunctionWithArguments")
1573 (python-nav-end-of-defun)
1574 (point))
1575 (save-excursion
1576 (point-max))))
1577 (should (= (save-excursion
1578 (python-tests-look-at "def wwrap(f):")
1579 (python-nav-end-of-defun)
1580 (point))
1581 (save-excursion
1582 (python-tests-look-at "return wwrap")
1583 (line-beginning-position))))
1584 (should (= (save-excursion
1585 (python-tests-look-at "def wrapped_f(*args):")
1586 (python-nav-end-of-defun)
1587 (point))
1588 (save-excursion
1589 (python-tests-look-at "return wrapped_f")
1590 (line-beginning-position))))
1591 (should (= (save-excursion
1592 (python-tests-look-at "f(*args)")
1593 (python-nav-end-of-defun)
1594 (point))
1595 (save-excursion
1596 (python-tests-look-at "return wrapped_f")
1597 (line-beginning-position))))))
1598
1599 (ert-deftest python-nav-backward-defun-1 ()
1600 (python-tests-with-temp-buffer
1601 "
1602 class A(object): # A
1603
1604 def a(self): # a
1605 pass
1606
1607 def b(self): # b
1608 pass
1609
1610 class B(object): # B
1611
1612 class C(object): # C
1613
1614 def d(self): # d
1615 pass
1616
1617 # def e(self): # e
1618 # pass
1619
1620 def c(self): # c
1621 pass
1622
1623 # def d(self): # d
1624 # pass
1625 "
1626 (goto-char (point-max))
1627 (should (= (save-excursion (python-nav-backward-defun))
1628 (python-tests-look-at " def c(self): # c" -1)))
1629 (should (= (save-excursion (python-nav-backward-defun))
1630 (python-tests-look-at " def d(self): # d" -1)))
1631 (should (= (save-excursion (python-nav-backward-defun))
1632 (python-tests-look-at " class C(object): # C" -1)))
1633 (should (= (save-excursion (python-nav-backward-defun))
1634 (python-tests-look-at " class B(object): # B" -1)))
1635 (should (= (save-excursion (python-nav-backward-defun))
1636 (python-tests-look-at " def b(self): # b" -1)))
1637 (should (= (save-excursion (python-nav-backward-defun))
1638 (python-tests-look-at " def a(self): # a" -1)))
1639 (should (= (save-excursion (python-nav-backward-defun))
1640 (python-tests-look-at "class A(object): # A" -1)))
1641 (should (not (python-nav-backward-defun)))))
1642
1643 (ert-deftest python-nav-backward-defun-2 ()
1644 (python-tests-with-temp-buffer
1645 "
1646 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1647 '''print decorated function call data to stdout.
1648
1649 Usage:
1650
1651 @decoratorFunctionWithArguments('arg1', 'arg2')
1652 def func(a, b, c=True):
1653 pass
1654 '''
1655
1656 def wwrap(f):
1657 print 'Inside wwrap()'
1658 def wrapped_f(*args):
1659 print 'Inside wrapped_f()'
1660 print 'Decorator arguments:', arg1, arg2, arg3
1661 f(*args)
1662 print 'After f(*args)'
1663 return wrapped_f
1664 return wwrap
1665 "
1666 (goto-char (point-max))
1667 (should (= (save-excursion (python-nav-backward-defun))
1668 (python-tests-look-at " def wrapped_f(*args):" -1)))
1669 (should (= (save-excursion (python-nav-backward-defun))
1670 (python-tests-look-at " def wwrap(f):" -1)))
1671 (should (= (save-excursion (python-nav-backward-defun))
1672 (python-tests-look-at "def decoratorFunctionWithArguments(arg1, arg2, arg3):" -1)))
1673 (should (not (python-nav-backward-defun)))))
1674
1675 (ert-deftest python-nav-backward-defun-3 ()
1676 (python-tests-with-temp-buffer
1677 "
1678 '''
1679 def u(self):
1680 pass
1681
1682 def v(self):
1683 pass
1684
1685 def w(self):
1686 pass
1687 '''
1688
1689 class A(object):
1690 pass
1691 "
1692 (goto-char (point-min))
1693 (let ((point (python-tests-look-at "class A(object):")))
1694 (should (not (python-nav-backward-defun)))
1695 (should (= point (point))))))
1696
1697 (ert-deftest python-nav-forward-defun-1 ()
1698 (python-tests-with-temp-buffer
1699 "
1700 class A(object): # A
1701
1702 def a(self): # a
1703 pass
1704
1705 def b(self): # b
1706 pass
1707
1708 class B(object): # B
1709
1710 class C(object): # C
1711
1712 def d(self): # d
1713 pass
1714
1715 # def e(self): # e
1716 # pass
1717
1718 def c(self): # c
1719 pass
1720
1721 # def d(self): # d
1722 # pass
1723 "
1724 (goto-char (point-min))
1725 (should (= (save-excursion (python-nav-forward-defun))
1726 (python-tests-look-at "(object): # A")))
1727 (should (= (save-excursion (python-nav-forward-defun))
1728 (python-tests-look-at "(self): # a")))
1729 (should (= (save-excursion (python-nav-forward-defun))
1730 (python-tests-look-at "(self): # b")))
1731 (should (= (save-excursion (python-nav-forward-defun))
1732 (python-tests-look-at "(object): # B")))
1733 (should (= (save-excursion (python-nav-forward-defun))
1734 (python-tests-look-at "(object): # C")))
1735 (should (= (save-excursion (python-nav-forward-defun))
1736 (python-tests-look-at "(self): # d")))
1737 (should (= (save-excursion (python-nav-forward-defun))
1738 (python-tests-look-at "(self): # c")))
1739 (should (not (python-nav-forward-defun)))))
1740
1741 (ert-deftest python-nav-forward-defun-2 ()
1742 (python-tests-with-temp-buffer
1743 "
1744 def decoratorFunctionWithArguments(arg1, arg2, arg3):
1745 '''print decorated function call data to stdout.
1746
1747 Usage:
1748
1749 @decoratorFunctionWithArguments('arg1', 'arg2')
1750 def func(a, b, c=True):
1751 pass
1752 '''
1753
1754 def wwrap(f):
1755 print 'Inside wwrap()'
1756 def wrapped_f(*args):
1757 print 'Inside wrapped_f()'
1758 print 'Decorator arguments:', arg1, arg2, arg3
1759 f(*args)
1760 print 'After f(*args)'
1761 return wrapped_f
1762 return wwrap
1763 "
1764 (goto-char (point-min))
1765 (should (= (save-excursion (python-nav-forward-defun))
1766 (python-tests-look-at "(arg1, arg2, arg3):")))
1767 (should (= (save-excursion (python-nav-forward-defun))
1768 (python-tests-look-at "(f):")))
1769 (should (= (save-excursion (python-nav-forward-defun))
1770 (python-tests-look-at "(*args):")))
1771 (should (not (python-nav-forward-defun)))))
1772
1773 (ert-deftest python-nav-forward-defun-3 ()
1774 (python-tests-with-temp-buffer
1775 "
1776 class A(object):
1777 pass
1778
1779 '''
1780 def u(self):
1781 pass
1782
1783 def v(self):
1784 pass
1785
1786 def w(self):
1787 pass
1788 '''
1789 "
1790 (goto-char (point-min))
1791 (let ((point (python-tests-look-at "(object):")))
1792 (should (not (python-nav-forward-defun)))
1793 (should (= point (point))))))
1794
1795 (ert-deftest python-nav-beginning-of-statement-1 ()
1796 (python-tests-with-temp-buffer
1797 "
1798 v1 = 123 + \
1799 456 + \
1800 789
1801 v2 = (value1,
1802 value2,
1803
1804 value3,
1805 value4)
1806 v3 = ('this is a string'
1807
1808 'that is continued'
1809 'between lines'
1810 'within a paren',
1811 # this is a comment, yo
1812 'continue previous line')
1813 v4 = '''
1814 a very long
1815 string
1816 '''
1817 "
1818 (python-tests-look-at "v2 =")
1819 (python-util-forward-comment -1)
1820 (should (= (save-excursion
1821 (python-nav-beginning-of-statement)
1822 (point))
1823 (python-tests-look-at "v1 =" -1 t)))
1824 (python-tests-look-at "v3 =")
1825 (python-util-forward-comment -1)
1826 (should (= (save-excursion
1827 (python-nav-beginning-of-statement)
1828 (point))
1829 (python-tests-look-at "v2 =" -1 t)))
1830 (python-tests-look-at "v4 =")
1831 (python-util-forward-comment -1)
1832 (should (= (save-excursion
1833 (python-nav-beginning-of-statement)
1834 (point))
1835 (python-tests-look-at "v3 =" -1 t)))
1836 (goto-char (point-max))
1837 (python-util-forward-comment -1)
1838 (should (= (save-excursion
1839 (python-nav-beginning-of-statement)
1840 (point))
1841 (python-tests-look-at "v4 =" -1 t)))))
1842
1843 (ert-deftest python-nav-end-of-statement-1 ()
1844 (python-tests-with-temp-buffer
1845 "
1846 v1 = 123 + \
1847 456 + \
1848 789
1849 v2 = (value1,
1850 value2,
1851
1852 value3,
1853 value4)
1854 v3 = ('this is a string'
1855
1856 'that is continued'
1857 'between lines'
1858 'within a paren',
1859 # this is a comment, yo
1860 'continue previous line')
1861 v4 = '''
1862 a very long
1863 string
1864 '''
1865 "
1866 (python-tests-look-at "v1 =")
1867 (should (= (save-excursion
1868 (python-nav-end-of-statement)
1869 (point))
1870 (save-excursion
1871 (python-tests-look-at "789")
1872 (line-end-position))))
1873 (python-tests-look-at "v2 =")
1874 (should (= (save-excursion
1875 (python-nav-end-of-statement)
1876 (point))
1877 (save-excursion
1878 (python-tests-look-at "value4)")
1879 (line-end-position))))
1880 (python-tests-look-at "v3 =")
1881 (should (= (save-excursion
1882 (python-nav-end-of-statement)
1883 (point))
1884 (save-excursion
1885 (python-tests-look-at
1886 "'continue previous line')")
1887 (line-end-position))))
1888 (python-tests-look-at "v4 =")
1889 (should (= (save-excursion
1890 (python-nav-end-of-statement)
1891 (point))
1892 (save-excursion
1893 (goto-char (point-max))
1894 (python-util-forward-comment -1)
1895 (point))))))
1896
1897 (ert-deftest python-nav-forward-statement-1 ()
1898 (python-tests-with-temp-buffer
1899 "
1900 v1 = 123 + \
1901 456 + \
1902 789
1903 v2 = (value1,
1904 value2,
1905
1906 value3,
1907 value4)
1908 v3 = ('this is a string'
1909
1910 'that is continued'
1911 'between lines'
1912 'within a paren',
1913 # this is a comment, yo
1914 'continue previous line')
1915 v4 = '''
1916 a very long
1917 string
1918 '''
1919 "
1920 (python-tests-look-at "v1 =")
1921 (should (= (save-excursion
1922 (python-nav-forward-statement)
1923 (point))
1924 (python-tests-look-at "v2 =")))
1925 (should (= (save-excursion
1926 (python-nav-forward-statement)
1927 (point))
1928 (python-tests-look-at "v3 =")))
1929 (should (= (save-excursion
1930 (python-nav-forward-statement)
1931 (point))
1932 (python-tests-look-at "v4 =")))
1933 (should (= (save-excursion
1934 (python-nav-forward-statement)
1935 (point))
1936 (point-max)))))
1937
1938 (ert-deftest python-nav-backward-statement-1 ()
1939 (python-tests-with-temp-buffer
1940 "
1941 v1 = 123 + \
1942 456 + \
1943 789
1944 v2 = (value1,
1945 value2,
1946
1947 value3,
1948 value4)
1949 v3 = ('this is a string'
1950
1951 'that is continued'
1952 'between lines'
1953 'within a paren',
1954 # this is a comment, yo
1955 'continue previous line')
1956 v4 = '''
1957 a very long
1958 string
1959 '''
1960 "
1961 (goto-char (point-max))
1962 (should (= (save-excursion
1963 (python-nav-backward-statement)
1964 (point))
1965 (python-tests-look-at "v4 =" -1)))
1966 (should (= (save-excursion
1967 (python-nav-backward-statement)
1968 (point))
1969 (python-tests-look-at "v3 =" -1)))
1970 (should (= (save-excursion
1971 (python-nav-backward-statement)
1972 (point))
1973 (python-tests-look-at "v2 =" -1)))
1974 (should (= (save-excursion
1975 (python-nav-backward-statement)
1976 (point))
1977 (python-tests-look-at "v1 =" -1)))))
1978
1979 (ert-deftest python-nav-backward-statement-2 ()
1980 :expected-result :failed
1981 (python-tests-with-temp-buffer
1982 "
1983 v1 = 123 + \
1984 456 + \
1985 789
1986 v2 = (value1,
1987 value2,
1988
1989 value3,
1990 value4)
1991 "
1992 ;; FIXME: For some reason `python-nav-backward-statement' is moving
1993 ;; back two sentences when starting from 'value4)'.
1994 (goto-char (point-max))
1995 (python-util-forward-comment -1)
1996 (should (= (save-excursion
1997 (python-nav-backward-statement)
1998 (point))
1999 (python-tests-look-at "v2 =" -1 t)))))
2000
2001 (ert-deftest python-nav-beginning-of-block-1 ()
2002 (python-tests-with-temp-buffer
2003 "
2004 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2005 '''print decorated function call data to stdout.
2006
2007 Usage:
2008
2009 @decoratorFunctionWithArguments('arg1', 'arg2')
2010 def func(a, b, c=True):
2011 pass
2012 '''
2013
2014 def wwrap(f):
2015 print 'Inside wwrap()'
2016 def wrapped_f(*args):
2017 print 'Inside wrapped_f()'
2018 print 'Decorator arguments:', arg1, arg2, arg3
2019 f(*args)
2020 print 'After f(*args)'
2021 return wrapped_f
2022 return wwrap
2023 "
2024 (python-tests-look-at "return wwrap")
2025 (should (= (save-excursion
2026 (python-nav-beginning-of-block)
2027 (point))
2028 (python-tests-look-at "def decoratorFunctionWithArguments" -1)))
2029 (python-tests-look-at "print 'Inside wwrap()'")
2030 (should (= (save-excursion
2031 (python-nav-beginning-of-block)
2032 (point))
2033 (python-tests-look-at "def wwrap(f):" -1)))
2034 (python-tests-look-at "print 'After f(*args)'")
2035 (end-of-line)
2036 (should (= (save-excursion
2037 (python-nav-beginning-of-block)
2038 (point))
2039 (python-tests-look-at "def wrapped_f(*args):" -1)))
2040 (python-tests-look-at "return wrapped_f")
2041 (should (= (save-excursion
2042 (python-nav-beginning-of-block)
2043 (point))
2044 (python-tests-look-at "def wwrap(f):" -1)))))
2045
2046 (ert-deftest python-nav-end-of-block-1 ()
2047 (python-tests-with-temp-buffer
2048 "
2049 def decoratorFunctionWithArguments(arg1, arg2, arg3):
2050 '''print decorated function call data to stdout.
2051
2052 Usage:
2053
2054 @decoratorFunctionWithArguments('arg1', 'arg2')
2055 def func(a, b, c=True):
2056 pass
2057 '''
2058
2059 def wwrap(f):
2060 print 'Inside wwrap()'
2061 def wrapped_f(*args):
2062 print 'Inside wrapped_f()'
2063 print 'Decorator arguments:', arg1, arg2, arg3
2064 f(*args)
2065 print 'After f(*args)'
2066 return wrapped_f
2067 return wwrap
2068 "
2069 (python-tests-look-at "def decoratorFunctionWithArguments")
2070 (should (= (save-excursion
2071 (python-nav-end-of-block)
2072 (point))
2073 (save-excursion
2074 (goto-char (point-max))
2075 (python-util-forward-comment -1)
2076 (point))))
2077 (python-tests-look-at "def wwrap(f):")
2078 (should (= (save-excursion
2079 (python-nav-end-of-block)
2080 (point))
2081 (save-excursion
2082 (python-tests-look-at "return wrapped_f")
2083 (line-end-position))))
2084 (end-of-line)
2085 (should (= (save-excursion
2086 (python-nav-end-of-block)
2087 (point))
2088 (save-excursion
2089 (python-tests-look-at "return wrapped_f")
2090 (line-end-position))))
2091 (python-tests-look-at "f(*args)")
2092 (should (= (save-excursion
2093 (python-nav-end-of-block)
2094 (point))
2095 (save-excursion
2096 (python-tests-look-at "print 'After f(*args)'")
2097 (line-end-position))))))
2098
2099 (ert-deftest python-nav-forward-block-1 ()
2100 "This also accounts as a test for `python-nav-backward-block'."
2101 (python-tests-with-temp-buffer
2102 "
2103 if request.user.is_authenticated():
2104 # def block():
2105 # pass
2106 try:
2107 profile = request.user.get_profile()
2108 except Profile.DoesNotExist:
2109 profile = Profile.objects.create(user=request.user)
2110 else:
2111 if profile.stats:
2112 profile.recalculate_stats()
2113 else:
2114 profile.clear_stats()
2115 finally:
2116 profile.views += 1
2117 profile.save()
2118 "
2119 (should (= (save-excursion (python-nav-forward-block))
2120 (python-tests-look-at "if request.user.is_authenticated():")))
2121 (should (= (save-excursion (python-nav-forward-block))
2122 (python-tests-look-at "try:")))
2123 (should (= (save-excursion (python-nav-forward-block))
2124 (python-tests-look-at "except Profile.DoesNotExist:")))
2125 (should (= (save-excursion (python-nav-forward-block))
2126 (python-tests-look-at "else:")))
2127 (should (= (save-excursion (python-nav-forward-block))
2128 (python-tests-look-at "if profile.stats:")))
2129 (should (= (save-excursion (python-nav-forward-block))
2130 (python-tests-look-at "else:")))
2131 (should (= (save-excursion (python-nav-forward-block))
2132 (python-tests-look-at "finally:")))
2133 ;; When point is at the last block, leave it there and return nil
2134 (should (not (save-excursion (python-nav-forward-block))))
2135 ;; Move backwards, and even if the number of moves is less than the
2136 ;; provided argument return the point.
2137 (should (= (save-excursion (python-nav-forward-block -10))
2138 (python-tests-look-at
2139 "if request.user.is_authenticated():" -1)))))
2140
2141 (ert-deftest python-nav-forward-sexp-1 ()
2142 (python-tests-with-temp-buffer
2143 "
2144 a()
2145 b()
2146 c()
2147 "
2148 (python-tests-look-at "a()")
2149 (python-nav-forward-sexp)
2150 (should (looking-at "$"))
2151 (should (save-excursion
2152 (beginning-of-line)
2153 (looking-at "a()")))
2154 (python-nav-forward-sexp)
2155 (should (looking-at "$"))
2156 (should (save-excursion
2157 (beginning-of-line)
2158 (looking-at "b()")))
2159 (python-nav-forward-sexp)
2160 (should (looking-at "$"))
2161 (should (save-excursion
2162 (beginning-of-line)
2163 (looking-at "c()")))
2164 ;; The default behavior when next to a paren should do what lisp
2165 ;; does and, otherwise `blink-matching-open' breaks.
2166 (python-nav-forward-sexp -1)
2167 (should (looking-at "()"))
2168 (should (save-excursion
2169 (beginning-of-line)
2170 (looking-at "c()")))
2171 (end-of-line)
2172 ;; Skipping parens should jump to `bolp'
2173 (python-nav-forward-sexp -1 nil t)
2174 (should (looking-at "c()"))
2175 (forward-line -1)
2176 (end-of-line)
2177 ;; b()
2178 (python-nav-forward-sexp -1)
2179 (should (looking-at "()"))
2180 (python-nav-forward-sexp -1)
2181 (should (looking-at "b()"))
2182 (end-of-line)
2183 (python-nav-forward-sexp -1 nil t)
2184 (should (looking-at "b()"))
2185 (forward-line -1)
2186 (end-of-line)
2187 ;; a()
2188 (python-nav-forward-sexp -1)
2189 (should (looking-at "()"))
2190 (python-nav-forward-sexp -1)
2191 (should (looking-at "a()"))
2192 (end-of-line)
2193 (python-nav-forward-sexp -1 nil t)
2194 (should (looking-at "a()"))))
2195
2196 (ert-deftest python-nav-forward-sexp-2 ()
2197 (python-tests-with-temp-buffer
2198 "
2199 def func():
2200 if True:
2201 aaa = bbb
2202 ccc = ddd
2203 eee = fff
2204 return ggg
2205 "
2206 (python-tests-look-at "aa =")
2207 (python-nav-forward-sexp)
2208 (should (looking-at " = bbb"))
2209 (python-nav-forward-sexp)
2210 (should (looking-at "$"))
2211 (should (save-excursion
2212 (back-to-indentation)
2213 (looking-at "aaa = bbb")))
2214 (python-nav-forward-sexp)
2215 (should (looking-at "$"))
2216 (should (save-excursion
2217 (back-to-indentation)
2218 (looking-at "ccc = ddd")))
2219 (python-nav-forward-sexp)
2220 (should (looking-at "$"))
2221 (should (save-excursion
2222 (back-to-indentation)
2223 (looking-at "eee = fff")))
2224 (python-nav-forward-sexp)
2225 (should (looking-at "$"))
2226 (should (save-excursion
2227 (back-to-indentation)
2228 (looking-at "return ggg")))
2229 (python-nav-forward-sexp -1)
2230 (should (looking-at "def func():"))))
2231
2232 (ert-deftest python-nav-forward-sexp-3 ()
2233 (python-tests-with-temp-buffer
2234 "
2235 from some_module import some_sub_module
2236 from another_module import another_sub_module
2237
2238 def another_statement():
2239 pass
2240 "
2241 (python-tests-look-at "some_module")
2242 (python-nav-forward-sexp)
2243 (should (looking-at " import"))
2244 (python-nav-forward-sexp)
2245 (should (looking-at " some_sub_module"))
2246 (python-nav-forward-sexp)
2247 (should (looking-at "$"))
2248 (should
2249 (save-excursion
2250 (back-to-indentation)
2251 (looking-at
2252 "from some_module import some_sub_module")))
2253 (python-nav-forward-sexp)
2254 (should (looking-at "$"))
2255 (should
2256 (save-excursion
2257 (back-to-indentation)
2258 (looking-at
2259 "from another_module import another_sub_module")))
2260 (python-nav-forward-sexp)
2261 (should (looking-at "$"))
2262 (should
2263 (save-excursion
2264 (back-to-indentation)
2265 (looking-at
2266 "pass")))
2267 (python-nav-forward-sexp -1)
2268 (should (looking-at "def another_statement():"))
2269 (python-nav-forward-sexp -1)
2270 (should (looking-at "from another_module import another_sub_module"))
2271 (python-nav-forward-sexp -1)
2272 (should (looking-at "from some_module import some_sub_module"))))
2273
2274 (ert-deftest python-nav-forward-sexp-safe-1 ()
2275 (python-tests-with-temp-buffer
2276 "
2277 profile = Profile.objects.create(user=request.user)
2278 profile.notify()
2279 "
2280 (python-tests-look-at "profile =")
2281 (python-nav-forward-sexp-safe 1)
2282 (should (looking-at "$"))
2283 (beginning-of-line 1)
2284 (python-tests-look-at "user=request.user")
2285 (python-nav-forward-sexp-safe -1)
2286 (should (looking-at "(user=request.user)"))
2287 (python-nav-forward-sexp-safe -4)
2288 (should (looking-at "profile ="))
2289 (python-tests-look-at "user=request.user")
2290 (python-nav-forward-sexp-safe 3)
2291 (should (looking-at ")"))
2292 (python-nav-forward-sexp-safe 1)
2293 (should (looking-at "$"))
2294 (python-nav-forward-sexp-safe 1)
2295 (should (looking-at "$"))))
2296
2297 (ert-deftest python-nav-up-list-1 ()
2298 (python-tests-with-temp-buffer
2299 "
2300 def f():
2301 if True:
2302 return [i for i in range(3)]
2303 "
2304 (python-tests-look-at "3)]")
2305 (python-nav-up-list)
2306 (should (looking-at "]"))
2307 (python-nav-up-list)
2308 (should (looking-at "$"))))
2309
2310 (ert-deftest python-nav-backward-up-list-1 ()
2311 :expected-result :failed
2312 (python-tests-with-temp-buffer
2313 "
2314 def f():
2315 if True:
2316 return [i for i in range(3)]
2317 "
2318 (python-tests-look-at "3)]")
2319 (python-nav-backward-up-list)
2320 (should (looking-at "(3)\\]"))
2321 (python-nav-backward-up-list)
2322 (should (looking-at
2323 "\\[i for i in range(3)\\]"))
2324 ;; FIXME: Need to move to beginning-of-statement.
2325 (python-nav-backward-up-list)
2326 (should (looking-at
2327 "return \\[i for i in range(3)\\]"))
2328 (python-nav-backward-up-list)
2329 (should (looking-at "if True:"))
2330 (python-nav-backward-up-list)
2331 (should (looking-at "def f():"))))
2332
2333 (ert-deftest python-indent-dedent-line-backspace-1 ()
2334 "Check de-indentation on first call. Bug#18319."
2335 (python-tests-with-temp-buffer
2336 "
2337 if True:
2338 x ()
2339 if False:
2340 "
2341 (python-tests-look-at "if False:")
2342 (call-interactively #'python-indent-dedent-line-backspace)
2343 (should (zerop (current-indentation)))
2344 ;; XXX: This should be a call to `undo' but it's triggering errors.
2345 (insert " ")
2346 (should (= (current-indentation) 4))
2347 (call-interactively #'python-indent-dedent-line-backspace)
2348 (should (zerop (current-indentation)))))
2349
2350 (ert-deftest python-indent-dedent-line-backspace-2 ()
2351 "Check de-indentation with tabs. Bug#19730."
2352 (let ((tab-width 8))
2353 (python-tests-with-temp-buffer
2354 "
2355 if x:
2356 \tabcdefg
2357 "
2358 (python-tests-look-at "abcdefg")
2359 (goto-char (line-end-position))
2360 (call-interactively #'python-indent-dedent-line-backspace)
2361 (should
2362 (string= (buffer-substring-no-properties
2363 (line-beginning-position) (line-end-position))
2364 "\tabcdef")))))
2365
2366 (ert-deftest python-indent-dedent-line-backspace-3 ()
2367 "Paranoid check of de-indentation with tabs. Bug#19730."
2368 (let ((tab-width 8))
2369 (python-tests-with-temp-buffer
2370 "
2371 if x:
2372 \tif y:
2373 \t abcdefg
2374 "
2375 (python-tests-look-at "abcdefg")
2376 (goto-char (line-end-position))
2377 (call-interactively #'python-indent-dedent-line-backspace)
2378 (should
2379 (string= (buffer-substring-no-properties
2380 (line-beginning-position) (line-end-position))
2381 "\t abcdef"))
2382 (back-to-indentation)
2383 (call-interactively #'python-indent-dedent-line-backspace)
2384 (should
2385 (string= (buffer-substring-no-properties
2386 (line-beginning-position) (line-end-position))
2387 "\tabcdef"))
2388 (call-interactively #'python-indent-dedent-line-backspace)
2389 (should
2390 (string= (buffer-substring-no-properties
2391 (line-beginning-position) (line-end-position))
2392 " abcdef"))
2393 (call-interactively #'python-indent-dedent-line-backspace)
2394 (should
2395 (string= (buffer-substring-no-properties
2396 (line-beginning-position) (line-end-position))
2397 "abcdef")))))
2398
2399 \f
2400 ;;; Shell integration
2401
2402 (defvar python-tests-shell-interpreter "python")
2403
2404 (ert-deftest python-shell-get-process-name-1 ()
2405 "Check process name calculation sans `buffer-file-name'."
2406 (python-tests-with-temp-buffer
2407 ""
2408 (should (string= (python-shell-get-process-name nil)
2409 python-shell-buffer-name))
2410 (should (string= (python-shell-get-process-name t)
2411 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2412
2413 (ert-deftest python-shell-get-process-name-2 ()
2414 "Check process name calculation with `buffer-file-name'."
2415 (python-tests-with-temp-file
2416 ""
2417 ;; `buffer-file-name' is non-nil but the dedicated flag is nil and
2418 ;; should be respected.
2419 (should (string= (python-shell-get-process-name nil)
2420 python-shell-buffer-name))
2421 (should (string=
2422 (python-shell-get-process-name t)
2423 (format "%s[%s]" python-shell-buffer-name (buffer-name))))))
2424
2425 (ert-deftest python-shell-internal-get-process-name-1 ()
2426 "Check the internal process name is buffer-unique sans `buffer-file-name'."
2427 (python-tests-with-temp-buffer
2428 ""
2429 (should (string= (python-shell-internal-get-process-name)
2430 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2431
2432 (ert-deftest python-shell-internal-get-process-name-2 ()
2433 "Check the internal process name is buffer-unique with `buffer-file-name'."
2434 (python-tests-with-temp-file
2435 ""
2436 (should (string= (python-shell-internal-get-process-name)
2437 (format "%s[%s]" python-shell-internal-buffer-name (buffer-name))))))
2438
2439 (ert-deftest python-shell-calculate-command-1 ()
2440 "Check the command to execute is calculated correctly.
2441 Using `python-shell-interpreter' and
2442 `python-shell-interpreter-args'."
2443 (skip-unless (executable-find python-tests-shell-interpreter))
2444 (let ((python-shell-interpreter (executable-find
2445 python-tests-shell-interpreter))
2446 (python-shell-interpreter-args "-B"))
2447 (should (string=
2448 (format "%s %s"
2449 (shell-quote-argument python-shell-interpreter)
2450 python-shell-interpreter-args)
2451 (python-shell-calculate-command)))))
2452
2453 (ert-deftest python-shell-calculate-pythonpath-1 ()
2454 "Test PYTHONPATH calculation."
2455 (let ((process-environment '("PYTHONPATH=/path0"))
2456 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2457 (should (string= (python-shell-calculate-pythonpath)
2458 (concat "/path1" path-separator
2459 "/path2" path-separator "/path0")))))
2460
2461 (ert-deftest python-shell-calculate-pythonpath-2 ()
2462 "Test existing paths are moved to front."
2463 (let ((process-environment
2464 (list (concat "PYTHONPATH=/path0" path-separator "/path1")))
2465 (python-shell-extra-pythonpaths '("/path1" "/path2")))
2466 (should (string= (python-shell-calculate-pythonpath)
2467 (concat "/path1" path-separator
2468 "/path2" path-separator "/path0")))))
2469
2470 (ert-deftest python-shell-calculate-process-environment-1 ()
2471 "Test `python-shell-process-environment' modification."
2472 (let* ((python-shell-process-environment
2473 '("TESTVAR1=value1" "TESTVAR2=value2"))
2474 (process-environment (python-shell-calculate-process-environment)))
2475 (should (equal (getenv "TESTVAR1") "value1"))
2476 (should (equal (getenv "TESTVAR2") "value2"))))
2477
2478 (ert-deftest python-shell-calculate-process-environment-2 ()
2479 "Test `python-shell-extra-pythonpaths' modification."
2480 (let* ((process-environment process-environment)
2481 (original-pythonpath (setenv "PYTHONPATH" "/path0"))
2482 (python-shell-extra-pythonpaths '("/path1" "/path2"))
2483 (process-environment (python-shell-calculate-process-environment)))
2484 (should (equal (getenv "PYTHONPATH")
2485 (concat "/path1" path-separator
2486 "/path2" path-separator "/path0")))))
2487
2488 (ert-deftest python-shell-calculate-process-environment-3 ()
2489 "Test `python-shell-virtualenv-root' modification."
2490 (let* ((python-shell-virtualenv-root "/env")
2491 (process-environment
2492 (let (process-environment process-environment)
2493 (setenv "PYTHONHOME" "/home")
2494 (setenv "VIRTUAL_ENV")
2495 (python-shell-calculate-process-environment))))
2496 (should (not (getenv "PYTHONHOME")))
2497 (should (string= (getenv "VIRTUAL_ENV") "/env"))))
2498
2499 (ert-deftest python-shell-calculate-process-environment-4 ()
2500 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is non-nil."
2501 (let* ((python-shell-unbuffered t)
2502 (process-environment
2503 (let ((process-environment process-environment))
2504 (setenv "PYTHONUNBUFFERED")
2505 (python-shell-calculate-process-environment))))
2506 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2507
2508 (ert-deftest python-shell-calculate-process-environment-5 ()
2509 "Test PYTHONUNBUFFERED when `python-shell-unbuffered' is nil."
2510 (let* ((python-shell-unbuffered nil)
2511 (process-environment
2512 (let ((process-environment process-environment))
2513 (setenv "PYTHONUNBUFFERED")
2514 (python-shell-calculate-process-environment))))
2515 (should (not (getenv "PYTHONUNBUFFERED")))))
2516
2517 (ert-deftest python-shell-calculate-process-environment-6 ()
2518 "Test PYTHONUNBUFFERED=1 when `python-shell-unbuffered' is nil."
2519 (let* ((python-shell-unbuffered nil)
2520 (process-environment
2521 (let ((process-environment process-environment))
2522 (setenv "PYTHONUNBUFFERED" "1")
2523 (python-shell-calculate-process-environment))))
2524 ;; User default settings must remain untouched:
2525 (should (string= (getenv "PYTHONUNBUFFERED") "1"))))
2526
2527 (ert-deftest python-shell-calculate-process-environment-7 ()
2528 "Test no side-effects on `process-environment'."
2529 (let* ((python-shell-process-environment
2530 '("TESTVAR1=value1" "TESTVAR2=value2"))
2531 (python-shell-virtualenv-root "/env")
2532 (python-shell-unbuffered t)
2533 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2534 (original-process-environment (copy-sequence process-environment)))
2535 (python-shell-calculate-process-environment)
2536 (should (equal process-environment original-process-environment))))
2537
2538 (ert-deftest python-shell-calculate-process-environment-8 ()
2539 "Test no side-effects on `tramp-remote-process-environment'."
2540 (let* ((default-directory "/ssh::/example/dir/")
2541 (python-shell-process-environment
2542 '("TESTVAR1=value1" "TESTVAR2=value2"))
2543 (python-shell-virtualenv-root "/env")
2544 (python-shell-unbuffered t)
2545 (python-shell-extra-pythonpaths'("/path1" "/path2"))
2546 (original-process-environment
2547 (copy-sequence tramp-remote-process-environment)))
2548 (python-shell-calculate-process-environment)
2549 (should (equal tramp-remote-process-environment original-process-environment))))
2550
2551 (ert-deftest python-shell-calculate-exec-path-1 ()
2552 "Test `python-shell-exec-path' modification."
2553 (let* ((exec-path '("/path0"))
2554 (python-shell-exec-path '("/path1" "/path2"))
2555 (new-exec-path (python-shell-calculate-exec-path)))
2556 (should (equal new-exec-path '("/path1" "/path2" "/path0")))))
2557
2558 (ert-deftest python-shell-calculate-exec-path-2 ()
2559 "Test `python-shell-virtualenv-root' modification."
2560 (let* ((exec-path '("/path0"))
2561 (python-shell-virtualenv-root "/env")
2562 (new-exec-path (python-shell-calculate-exec-path)))
2563 (should (equal new-exec-path
2564 (list (expand-file-name "/env/bin") "/path0")))))
2565
2566 (ert-deftest python-shell-calculate-exec-path-3 ()
2567 "Test complete `python-shell-virtualenv-root' modification."
2568 (let* ((exec-path '("/path0"))
2569 (python-shell-exec-path '("/path1" "/path2"))
2570 (python-shell-virtualenv-root "/env")
2571 (new-exec-path (python-shell-calculate-exec-path)))
2572 (should (equal new-exec-path
2573 (list (expand-file-name "/env/bin")
2574 "/path1" "/path2" "/path0")))))
2575
2576 (ert-deftest python-shell-calculate-exec-path-4 ()
2577 "Test complete `python-shell-virtualenv-root' with remote."
2578 (let* ((default-directory "/ssh::/example/dir/")
2579 (python-shell-remote-exec-path '("/path0"))
2580 (python-shell-exec-path '("/path1" "/path2"))
2581 (python-shell-virtualenv-root "/env")
2582 (new-exec-path (python-shell-calculate-exec-path)))
2583 (should (equal new-exec-path
2584 (list (expand-file-name "/env/bin")
2585 "/path1" "/path2" "/path0")))))
2586
2587 (ert-deftest python-shell-calculate-exec-path-5 ()
2588 "Test no side-effects on `exec-path'."
2589 (let* ((exec-path '("/path0"))
2590 (python-shell-exec-path '("/path1" "/path2"))
2591 (python-shell-virtualenv-root "/env")
2592 (original-exec-path (copy-sequence exec-path)))
2593 (python-shell-calculate-exec-path)
2594 (should (equal exec-path original-exec-path))))
2595
2596 (ert-deftest python-shell-calculate-exec-path-6 ()
2597 "Test no side-effects on `python-shell-remote-exec-path'."
2598 (let* ((default-directory "/ssh::/example/dir/")
2599 (python-shell-remote-exec-path '("/path0"))
2600 (python-shell-exec-path '("/path1" "/path2"))
2601 (python-shell-virtualenv-root "/env")
2602 (original-exec-path (copy-sequence python-shell-remote-exec-path)))
2603 (python-shell-calculate-exec-path)
2604 (should (equal python-shell-remote-exec-path original-exec-path))))
2605
2606 (ert-deftest python-shell-with-environment-1 ()
2607 "Test environment with local `default-directory'."
2608 (let* ((exec-path '("/path0"))
2609 (python-shell-exec-path '("/path1" "/path2"))
2610 (original-exec-path exec-path)
2611 (python-shell-virtualenv-root "/env"))
2612 (python-shell-with-environment
2613 (should (equal exec-path
2614 (list (expand-file-name "/env/bin")
2615 "/path1" "/path2" "/path0")))
2616 (should (not (getenv "PYTHONHOME")))
2617 (should (string= (getenv "VIRTUAL_ENV") "/env")))
2618 (should (equal exec-path original-exec-path))))
2619
2620 (ert-deftest python-shell-with-environment-2 ()
2621 "Test environment with remote `default-directory'."
2622 (let* ((default-directory "/ssh::/example/dir/")
2623 (python-shell-remote-exec-path '("/remote1" "/remote2"))
2624 (python-shell-exec-path '("/path1" "/path2"))
2625 (tramp-remote-process-environment '("EMACS=t"))
2626 (original-process-environment (copy-sequence tramp-remote-process-environment))
2627 (python-shell-virtualenv-root "/env"))
2628 (python-shell-with-environment
2629 (should (equal (python-shell-calculate-exec-path)
2630 (list (expand-file-name "/env/bin")
2631 "/path1" "/path2" "/remote1" "/remote2")))
2632 (let ((process-environment (python-shell-calculate-process-environment)))
2633 (should (not (getenv "PYTHONHOME")))
2634 (should (string= (getenv "VIRTUAL_ENV") "/env"))
2635 (should (equal tramp-remote-process-environment process-environment))))
2636 (should (equal tramp-remote-process-environment original-process-environment))))
2637
2638 (ert-deftest python-shell-with-environment-3 ()
2639 "Test `python-shell-with-environment' is idempotent."
2640 (let* ((python-shell-extra-pythonpaths '("/example/dir/"))
2641 (python-shell-exec-path '("path1" "path2"))
2642 (python-shell-virtualenv-root "/home/user/env")
2643 (single-call
2644 (python-shell-with-environment
2645 (list exec-path process-environment)))
2646 (nested-call
2647 (python-shell-with-environment
2648 (python-shell-with-environment
2649 (list exec-path process-environment)))))
2650 (should (equal single-call nested-call))))
2651
2652 (ert-deftest python-shell-make-comint-1 ()
2653 "Check comint creation for global shell buffer."
2654 (skip-unless (executable-find python-tests-shell-interpreter))
2655 ;; The interpreter can get killed too quickly to allow it to clean
2656 ;; up the tempfiles that the default python-shell-setup-codes create,
2657 ;; so it leaves tempfiles behind, which is a minor irritation.
2658 (let* ((python-shell-setup-codes nil)
2659 (python-shell-interpreter
2660 (executable-find python-tests-shell-interpreter))
2661 (proc-name (python-shell-get-process-name nil))
2662 (shell-buffer
2663 (python-tests-with-temp-buffer
2664 "" (python-shell-make-comint
2665 (python-shell-calculate-command) proc-name)))
2666 (process (get-buffer-process shell-buffer)))
2667 (unwind-protect
2668 (progn
2669 (set-process-query-on-exit-flag process nil)
2670 (should (process-live-p process))
2671 (with-current-buffer shell-buffer
2672 (should (eq major-mode 'inferior-python-mode))
2673 (should (string= (buffer-name) (format "*%s*" proc-name)))))
2674 (kill-buffer shell-buffer))))
2675
2676 (ert-deftest python-shell-make-comint-2 ()
2677 "Check comint creation for internal shell buffer."
2678 (skip-unless (executable-find python-tests-shell-interpreter))
2679 (let* ((python-shell-setup-codes nil)
2680 (python-shell-interpreter
2681 (executable-find python-tests-shell-interpreter))
2682 (proc-name (python-shell-internal-get-process-name))
2683 (shell-buffer
2684 (python-tests-with-temp-buffer
2685 "" (python-shell-make-comint
2686 (python-shell-calculate-command) proc-name nil t)))
2687 (process (get-buffer-process shell-buffer)))
2688 (unwind-protect
2689 (progn
2690 (set-process-query-on-exit-flag process nil)
2691 (should (process-live-p process))
2692 (with-current-buffer shell-buffer
2693 (should (eq major-mode 'inferior-python-mode))
2694 (should (string= (buffer-name) (format " *%s*" proc-name)))))
2695 (kill-buffer shell-buffer))))
2696
2697 (ert-deftest python-shell-make-comint-3 ()
2698 "Check comint creation with overridden python interpreter and args.
2699 The command passed to `python-shell-make-comint' as argument must
2700 locally override global values set in `python-shell-interpreter'
2701 and `python-shell-interpreter-args' in the new shell buffer."
2702 (skip-unless (executable-find python-tests-shell-interpreter))
2703 (let* ((python-shell-setup-codes nil)
2704 (python-shell-interpreter "interpreter")
2705 (python-shell-interpreter-args "--some-args")
2706 (proc-name (python-shell-get-process-name nil))
2707 (interpreter-override
2708 (concat (executable-find python-tests-shell-interpreter) " " "-i"))
2709 (shell-buffer
2710 (python-tests-with-temp-buffer
2711 "" (python-shell-make-comint interpreter-override proc-name nil)))
2712 (process (get-buffer-process shell-buffer)))
2713 (unwind-protect
2714 (progn
2715 (set-process-query-on-exit-flag process nil)
2716 (should (process-live-p process))
2717 (with-current-buffer shell-buffer
2718 (should (eq major-mode 'inferior-python-mode))
2719 (should (file-equal-p
2720 python-shell-interpreter
2721 (executable-find python-tests-shell-interpreter)))
2722 (should (string= python-shell-interpreter-args "-i"))))
2723 (kill-buffer shell-buffer))))
2724
2725 (ert-deftest python-shell-make-comint-4 ()
2726 "Check shell calculated prompts regexps are set."
2727 (skip-unless (executable-find python-tests-shell-interpreter))
2728 (let* ((process-environment process-environment)
2729 (python-shell-setup-codes nil)
2730 (python-shell-interpreter
2731 (executable-find python-tests-shell-interpreter))
2732 (python-shell-interpreter-args "-i")
2733 (python-shell--prompt-calculated-input-regexp nil)
2734 (python-shell--prompt-calculated-output-regexp nil)
2735 (python-shell-prompt-detect-enabled t)
2736 (python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
2737 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
2738 (python-shell-prompt-regexp "in")
2739 (python-shell-prompt-block-regexp "block")
2740 (python-shell-prompt-pdb-regexp "pdf")
2741 (python-shell-prompt-output-regexp "output")
2742 (startup-code (concat "import sys\n"
2743 "sys.ps1 = 'py> '\n"
2744 "sys.ps2 = '..> '\n"
2745 "sys.ps3 = 'out '\n"))
2746 (startup-file (python-shell--save-temp-file startup-code))
2747 (proc-name (python-shell-get-process-name nil))
2748 (shell-buffer
2749 (progn
2750 (setenv "PYTHONSTARTUP" startup-file)
2751 (python-tests-with-temp-buffer
2752 "" (python-shell-make-comint
2753 (python-shell-calculate-command) proc-name nil))))
2754 (process (get-buffer-process shell-buffer)))
2755 (unwind-protect
2756 (progn
2757 (set-process-query-on-exit-flag process nil)
2758 (should (process-live-p process))
2759 (with-current-buffer shell-buffer
2760 (should (eq major-mode 'inferior-python-mode))
2761 (should (string=
2762 python-shell--prompt-calculated-input-regexp
2763 (concat "^\\(extralargeinputprompt\\|\\.\\.> \\|"
2764 "block\\|py> \\|pdf\\|sml\\|in\\)")))
2765 (should (string=
2766 python-shell--prompt-calculated-output-regexp
2767 "^\\(extralargeoutputprompt\\|output\\|out \\|sml\\)"))))
2768 (delete-file startup-file)
2769 (kill-buffer shell-buffer))))
2770
2771 (ert-deftest python-shell-get-process-1 ()
2772 "Check dedicated shell process preference over global."
2773 (skip-unless (executable-find python-tests-shell-interpreter))
2774 (python-tests-with-temp-file
2775 ""
2776 (let* ((python-shell-setup-codes nil)
2777 (python-shell-interpreter
2778 (executable-find python-tests-shell-interpreter))
2779 (global-proc-name (python-shell-get-process-name nil))
2780 (dedicated-proc-name (python-shell-get-process-name t))
2781 (global-shell-buffer
2782 (python-shell-make-comint
2783 (python-shell-calculate-command) global-proc-name))
2784 (dedicated-shell-buffer
2785 (python-shell-make-comint
2786 (python-shell-calculate-command) dedicated-proc-name))
2787 (global-process (get-buffer-process global-shell-buffer))
2788 (dedicated-process (get-buffer-process dedicated-shell-buffer)))
2789 (unwind-protect
2790 (progn
2791 (set-process-query-on-exit-flag global-process nil)
2792 (set-process-query-on-exit-flag dedicated-process nil)
2793 ;; Prefer dedicated if global also exists.
2794 (should (equal (python-shell-get-process) dedicated-process))
2795 (kill-buffer dedicated-shell-buffer)
2796 ;; If there's only global, use it.
2797 (should (equal (python-shell-get-process) global-process))
2798 (kill-buffer global-shell-buffer)
2799 ;; No buffer available.
2800 (should (not (python-shell-get-process))))
2801 (ignore-errors (kill-buffer global-shell-buffer))
2802 (ignore-errors (kill-buffer dedicated-shell-buffer))))))
2803
2804 (ert-deftest python-shell-internal-get-or-create-process-1 ()
2805 "Check internal shell process creation fallback."
2806 (skip-unless (executable-find python-tests-shell-interpreter))
2807 (python-tests-with-temp-file
2808 ""
2809 (should (not (process-live-p (python-shell-internal-get-process-name))))
2810 (let* ((python-shell-interpreter
2811 (executable-find python-tests-shell-interpreter))
2812 (internal-process-name (python-shell-internal-get-process-name))
2813 (internal-process (python-shell-internal-get-or-create-process))
2814 (internal-shell-buffer (process-buffer internal-process)))
2815 (unwind-protect
2816 (progn
2817 (set-process-query-on-exit-flag internal-process nil)
2818 (should (equal (process-name internal-process)
2819 internal-process-name))
2820 (should (equal internal-process
2821 (python-shell-internal-get-or-create-process)))
2822 ;; Assert the internal process is not a user process
2823 (should (not (python-shell-get-process)))
2824 (kill-buffer internal-shell-buffer))
2825 (ignore-errors (kill-buffer internal-shell-buffer))))))
2826
2827 (ert-deftest python-shell-prompt-detect-1 ()
2828 "Check prompt autodetection."
2829 (skip-unless (executable-find python-tests-shell-interpreter))
2830 (let ((process-environment process-environment))
2831 ;; Ensure no startup file is enabled
2832 (setenv "PYTHONSTARTUP" "")
2833 (should python-shell-prompt-detect-enabled)
2834 (should (equal (python-shell-prompt-detect) '(">>> " "... " "")))))
2835
2836 (ert-deftest python-shell-prompt-detect-2 ()
2837 "Check prompt autodetection with startup file. Bug#17370."
2838 (skip-unless (executable-find python-tests-shell-interpreter))
2839 (let* ((process-environment process-environment)
2840 (startup-code (concat "import sys\n"
2841 "sys.ps1 = 'py> '\n"
2842 "sys.ps2 = '..> '\n"
2843 "sys.ps3 = 'out '\n"))
2844 (startup-file (python-shell--save-temp-file startup-code)))
2845 (unwind-protect
2846 (progn
2847 ;; Ensure startup file is enabled
2848 (setenv "PYTHONSTARTUP" startup-file)
2849 (should python-shell-prompt-detect-enabled)
2850 (should (equal (python-shell-prompt-detect) '("py> " "..> " "out "))))
2851 (ignore-errors (delete-file startup-file)))))
2852
2853 (ert-deftest python-shell-prompt-detect-3 ()
2854 "Check prompts are not autodetected when feature is disabled."
2855 (skip-unless (executable-find python-tests-shell-interpreter))
2856 (let ((process-environment process-environment)
2857 (python-shell-prompt-detect-enabled nil))
2858 ;; Ensure no startup file is enabled
2859 (should (not python-shell-prompt-detect-enabled))
2860 (should (not (python-shell-prompt-detect)))))
2861
2862 (ert-deftest python-shell-prompt-detect-4 ()
2863 "Check warning is shown when detection fails."
2864 (skip-unless (executable-find python-tests-shell-interpreter))
2865 (let* ((process-environment process-environment)
2866 ;; Trigger failure by removing prompts in the startup file
2867 (startup-code (concat "import sys\n"
2868 "sys.ps1 = ''\n"
2869 "sys.ps2 = ''\n"
2870 "sys.ps3 = ''\n"))
2871 (startup-file (python-shell--save-temp-file startup-code)))
2872 (unwind-protect
2873 (progn
2874 (kill-buffer (get-buffer-create "*Warnings*"))
2875 (should (not (get-buffer "*Warnings*")))
2876 (setenv "PYTHONSTARTUP" startup-file)
2877 (should python-shell-prompt-detect-failure-warning)
2878 (should python-shell-prompt-detect-enabled)
2879 (should (not (python-shell-prompt-detect)))
2880 (should (get-buffer "*Warnings*")))
2881 (ignore-errors (delete-file startup-file)))))
2882
2883 (ert-deftest python-shell-prompt-detect-5 ()
2884 "Check disabled warnings are not shown when detection fails."
2885 (skip-unless (executable-find python-tests-shell-interpreter))
2886 (let* ((process-environment process-environment)
2887 (startup-code (concat "import sys\n"
2888 "sys.ps1 = ''\n"
2889 "sys.ps2 = ''\n"
2890 "sys.ps3 = ''\n"))
2891 (startup-file (python-shell--save-temp-file startup-code))
2892 (python-shell-prompt-detect-failure-warning nil))
2893 (unwind-protect
2894 (progn
2895 (kill-buffer (get-buffer-create "*Warnings*"))
2896 (should (not (get-buffer "*Warnings*")))
2897 (setenv "PYTHONSTARTUP" startup-file)
2898 (should (not python-shell-prompt-detect-failure-warning))
2899 (should python-shell-prompt-detect-enabled)
2900 (should (not (python-shell-prompt-detect)))
2901 (should (not (get-buffer "*Warnings*"))))
2902 (ignore-errors (delete-file startup-file)))))
2903
2904 (ert-deftest python-shell-prompt-detect-6 ()
2905 "Warnings are not shown when detection is disabled."
2906 (skip-unless (executable-find python-tests-shell-interpreter))
2907 (let* ((process-environment process-environment)
2908 (startup-code (concat "import sys\n"
2909 "sys.ps1 = ''\n"
2910 "sys.ps2 = ''\n"
2911 "sys.ps3 = ''\n"))
2912 (startup-file (python-shell--save-temp-file startup-code))
2913 (python-shell-prompt-detect-failure-warning t)
2914 (python-shell-prompt-detect-enabled nil))
2915 (unwind-protect
2916 (progn
2917 (kill-buffer (get-buffer-create "*Warnings*"))
2918 (should (not (get-buffer "*Warnings*")))
2919 (setenv "PYTHONSTARTUP" startup-file)
2920 (should python-shell-prompt-detect-failure-warning)
2921 (should (not python-shell-prompt-detect-enabled))
2922 (should (not (python-shell-prompt-detect)))
2923 (should (not (get-buffer "*Warnings*"))))
2924 (ignore-errors (delete-file startup-file)))))
2925
2926 (ert-deftest python-shell-prompt-validate-regexps-1 ()
2927 "Check `python-shell-prompt-input-regexps' are validated."
2928 (let* ((python-shell-prompt-input-regexps '("\\("))
2929 (error-data (should-error (python-shell-prompt-validate-regexps)
2930 :type 'user-error)))
2931 (should
2932 (string= (cadr error-data)
2933 (format-message
2934 "Invalid regexp \\( in `python-shell-prompt-input-regexps'")))))
2935
2936 (ert-deftest python-shell-prompt-validate-regexps-2 ()
2937 "Check `python-shell-prompt-output-regexps' are validated."
2938 (let* ((python-shell-prompt-output-regexps '("\\("))
2939 (error-data (should-error (python-shell-prompt-validate-regexps)
2940 :type 'user-error)))
2941 (should
2942 (string= (cadr error-data)
2943 (format-message
2944 "Invalid regexp \\( in `python-shell-prompt-output-regexps'")))))
2945
2946 (ert-deftest python-shell-prompt-validate-regexps-3 ()
2947 "Check `python-shell-prompt-regexp' is validated."
2948 (let* ((python-shell-prompt-regexp "\\(")
2949 (error-data (should-error (python-shell-prompt-validate-regexps)
2950 :type 'user-error)))
2951 (should
2952 (string= (cadr error-data)
2953 (format-message
2954 "Invalid regexp \\( in `python-shell-prompt-regexp'")))))
2955
2956 (ert-deftest python-shell-prompt-validate-regexps-4 ()
2957 "Check `python-shell-prompt-block-regexp' is validated."
2958 (let* ((python-shell-prompt-block-regexp "\\(")
2959 (error-data (should-error (python-shell-prompt-validate-regexps)
2960 :type 'user-error)))
2961 (should
2962 (string= (cadr error-data)
2963 (format-message
2964 "Invalid regexp \\( in `python-shell-prompt-block-regexp'")))))
2965
2966 (ert-deftest python-shell-prompt-validate-regexps-5 ()
2967 "Check `python-shell-prompt-pdb-regexp' is validated."
2968 (let* ((python-shell-prompt-pdb-regexp "\\(")
2969 (error-data (should-error (python-shell-prompt-validate-regexps)
2970 :type 'user-error)))
2971 (should
2972 (string= (cadr error-data)
2973 (format-message
2974 "Invalid regexp \\( in `python-shell-prompt-pdb-regexp'")))))
2975
2976 (ert-deftest python-shell-prompt-validate-regexps-6 ()
2977 "Check `python-shell-prompt-output-regexp' is validated."
2978 (let* ((python-shell-prompt-output-regexp "\\(")
2979 (error-data (should-error (python-shell-prompt-validate-regexps)
2980 :type 'user-error)))
2981 (should
2982 (string= (cadr error-data)
2983 (format-message
2984 "Invalid regexp \\( in `python-shell-prompt-output-regexp'")))))
2985
2986 (ert-deftest python-shell-prompt-validate-regexps-7 ()
2987 "Check default regexps are valid."
2988 ;; should not signal error
2989 (python-shell-prompt-validate-regexps))
2990
2991 (ert-deftest python-shell-prompt-set-calculated-regexps-1 ()
2992 "Check regexps are validated."
2993 (let* ((python-shell-prompt-output-regexp '("\\("))
2994 (python-shell--prompt-calculated-input-regexp nil)
2995 (python-shell--prompt-calculated-output-regexp nil)
2996 (python-shell-prompt-detect-enabled nil)
2997 (error-data (should-error (python-shell-prompt-set-calculated-regexps)
2998 :type 'user-error)))
2999 (should
3000 (string= (cadr error-data)
3001 (format-message
3002 "Invalid regexp \\( in `python-shell-prompt-output-regexp'")))))
3003
3004 (ert-deftest python-shell-prompt-set-calculated-regexps-2 ()
3005 "Check `python-shell-prompt-input-regexps' are set."
3006 (let* ((python-shell-prompt-input-regexps '("my" "prompt"))
3007 (python-shell-prompt-output-regexps '(""))
3008 (python-shell-prompt-regexp "")
3009 (python-shell-prompt-block-regexp "")
3010 (python-shell-prompt-pdb-regexp "")
3011 (python-shell-prompt-output-regexp "")
3012 (python-shell--prompt-calculated-input-regexp nil)
3013 (python-shell--prompt-calculated-output-regexp nil)
3014 (python-shell-prompt-detect-enabled nil))
3015 (python-shell-prompt-set-calculated-regexps)
3016 (should (string= python-shell--prompt-calculated-input-regexp
3017 "^\\(prompt\\|my\\|\\)"))))
3018
3019 (ert-deftest python-shell-prompt-set-calculated-regexps-3 ()
3020 "Check `python-shell-prompt-output-regexps' are set."
3021 (let* ((python-shell-prompt-input-regexps '(""))
3022 (python-shell-prompt-output-regexps '("my" "prompt"))
3023 (python-shell-prompt-regexp "")
3024 (python-shell-prompt-block-regexp "")
3025 (python-shell-prompt-pdb-regexp "")
3026 (python-shell-prompt-output-regexp "")
3027 (python-shell--prompt-calculated-input-regexp nil)
3028 (python-shell--prompt-calculated-output-regexp nil)
3029 (python-shell-prompt-detect-enabled nil))
3030 (python-shell-prompt-set-calculated-regexps)
3031 (should (string= python-shell--prompt-calculated-output-regexp
3032 "^\\(prompt\\|my\\|\\)"))))
3033
3034 (ert-deftest python-shell-prompt-set-calculated-regexps-4 ()
3035 "Check user defined prompts are set."
3036 (let* ((python-shell-prompt-input-regexps '(""))
3037 (python-shell-prompt-output-regexps '(""))
3038 (python-shell-prompt-regexp "prompt")
3039 (python-shell-prompt-block-regexp "block")
3040 (python-shell-prompt-pdb-regexp "pdb")
3041 (python-shell-prompt-output-regexp "output")
3042 (python-shell--prompt-calculated-input-regexp nil)
3043 (python-shell--prompt-calculated-output-regexp nil)
3044 (python-shell-prompt-detect-enabled nil))
3045 (python-shell-prompt-set-calculated-regexps)
3046 (should (string= python-shell--prompt-calculated-input-regexp
3047 "^\\(prompt\\|block\\|pdb\\|\\)"))
3048 (should (string= python-shell--prompt-calculated-output-regexp
3049 "^\\(output\\|\\)"))))
3050
3051 (ert-deftest python-shell-prompt-set-calculated-regexps-5 ()
3052 "Check order of regexps (larger first)."
3053 (let* ((python-shell-prompt-input-regexps '("extralargeinputprompt" "sml"))
3054 (python-shell-prompt-output-regexps '("extralargeoutputprompt" "sml"))
3055 (python-shell-prompt-regexp "in")
3056 (python-shell-prompt-block-regexp "block")
3057 (python-shell-prompt-pdb-regexp "pdf")
3058 (python-shell-prompt-output-regexp "output")
3059 (python-shell--prompt-calculated-input-regexp nil)
3060 (python-shell--prompt-calculated-output-regexp nil)
3061 (python-shell-prompt-detect-enabled nil))
3062 (python-shell-prompt-set-calculated-regexps)
3063 (should (string= python-shell--prompt-calculated-input-regexp
3064 "^\\(extralargeinputprompt\\|block\\|pdf\\|sml\\|in\\)"))
3065 (should (string= python-shell--prompt-calculated-output-regexp
3066 "^\\(extralargeoutputprompt\\|output\\|sml\\)"))))
3067
3068 (ert-deftest python-shell-prompt-set-calculated-regexps-6 ()
3069 "Check detected prompts are included `regexp-quote'd."
3070 (skip-unless (executable-find python-tests-shell-interpreter))
3071 (let* ((python-shell-prompt-input-regexps '(""))
3072 (python-shell-prompt-output-regexps '(""))
3073 (python-shell-prompt-regexp "")
3074 (python-shell-prompt-block-regexp "")
3075 (python-shell-prompt-pdb-regexp "")
3076 (python-shell-prompt-output-regexp "")
3077 (python-shell--prompt-calculated-input-regexp nil)
3078 (python-shell--prompt-calculated-output-regexp nil)
3079 (python-shell-prompt-detect-enabled t)
3080 (process-environment process-environment)
3081 (startup-code (concat "import sys\n"
3082 "sys.ps1 = 'p.> '\n"
3083 "sys.ps2 = '..> '\n"
3084 "sys.ps3 = 'o.t '\n"))
3085 (startup-file (python-shell--save-temp-file startup-code)))
3086 (unwind-protect
3087 (progn
3088 (setenv "PYTHONSTARTUP" startup-file)
3089 (python-shell-prompt-set-calculated-regexps)
3090 (should (string= python-shell--prompt-calculated-input-regexp
3091 "^\\(\\.\\.> \\|p\\.> \\|\\)"))
3092 (should (string= python-shell--prompt-calculated-output-regexp
3093 "^\\(o\\.t \\|\\)")))
3094 (ignore-errors (delete-file startup-file)))))
3095
3096 (ert-deftest python-shell-buffer-substring-1 ()
3097 "Selecting a substring of the whole buffer must match its contents."
3098 (python-tests-with-temp-buffer
3099 "
3100 class Foo(models.Model):
3101 pass
3102
3103
3104 class Bar(models.Model):
3105 pass
3106 "
3107 (should (string= (buffer-string)
3108 (python-shell-buffer-substring (point-min) (point-max))))))
3109
3110 (ert-deftest python-shell-buffer-substring-2 ()
3111 "Main block should be removed if NOMAIN is non-nil."
3112 (python-tests-with-temp-buffer
3113 "
3114 class Foo(models.Model):
3115 pass
3116
3117 class Bar(models.Model):
3118 pass
3119
3120 if __name__ == \"__main__\":
3121 foo = Foo()
3122 print (foo)
3123 "
3124 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3125 "
3126 class Foo(models.Model):
3127 pass
3128
3129 class Bar(models.Model):
3130 pass
3131
3132
3133
3134
3135 "))))
3136
3137 (ert-deftest python-shell-buffer-substring-3 ()
3138 "Main block should be removed if NOMAIN is non-nil."
3139 (python-tests-with-temp-buffer
3140 "
3141 class Foo(models.Model):
3142 pass
3143
3144 if __name__ == \"__main__\":
3145 foo = Foo()
3146 print (foo)
3147
3148 class Bar(models.Model):
3149 pass
3150 "
3151 (should (string= (python-shell-buffer-substring (point-min) (point-max) t)
3152 "
3153 class Foo(models.Model):
3154 pass
3155
3156
3157
3158
3159
3160 class Bar(models.Model):
3161 pass
3162 "))))
3163
3164 (ert-deftest python-shell-buffer-substring-4 ()
3165 "Coding cookie should be added for substrings."
3166 (python-tests-with-temp-buffer
3167 "# coding: latin-1
3168
3169 class Foo(models.Model):
3170 pass
3171
3172 if __name__ == \"__main__\":
3173 foo = Foo()
3174 print (foo)
3175
3176 class Bar(models.Model):
3177 pass
3178 "
3179 (should (string= (python-shell-buffer-substring
3180 (python-tests-look-at "class Foo(models.Model):")
3181 (progn (python-nav-forward-sexp) (point)))
3182 "# -*- coding: latin-1 -*-
3183
3184 class Foo(models.Model):
3185 pass"))))
3186
3187 (ert-deftest python-shell-buffer-substring-5 ()
3188 "The proper amount of blank lines is added for a substring."
3189 (python-tests-with-temp-buffer
3190 "# coding: latin-1
3191
3192 class Foo(models.Model):
3193 pass
3194
3195 if __name__ == \"__main__\":
3196 foo = Foo()
3197 print (foo)
3198
3199 class Bar(models.Model):
3200 pass
3201 "
3202 (should (string= (python-shell-buffer-substring
3203 (python-tests-look-at "class Bar(models.Model):")
3204 (progn (python-nav-forward-sexp) (point)))
3205 "# -*- coding: latin-1 -*-
3206
3207
3208
3209
3210
3211
3212
3213
3214 class Bar(models.Model):
3215 pass"))))
3216
3217 (ert-deftest python-shell-buffer-substring-6 ()
3218 "Handle substring with coding cookie in the second line."
3219 (python-tests-with-temp-buffer
3220 "
3221 # coding: latin-1
3222
3223 class Foo(models.Model):
3224 pass
3225
3226 if __name__ == \"__main__\":
3227 foo = Foo()
3228 print (foo)
3229
3230 class Bar(models.Model):
3231 pass
3232 "
3233 (should (string= (python-shell-buffer-substring
3234 (python-tests-look-at "# coding: latin-1")
3235 (python-tests-look-at "if __name__ == \"__main__\":"))
3236 "# -*- coding: latin-1 -*-
3237
3238
3239 class Foo(models.Model):
3240 pass
3241
3242 "))))
3243
3244 (ert-deftest python-shell-buffer-substring-7 ()
3245 "Ensure first coding cookie gets precedence."
3246 (python-tests-with-temp-buffer
3247 "# coding: utf-8
3248 # coding: latin-1
3249
3250 class Foo(models.Model):
3251 pass
3252
3253 if __name__ == \"__main__\":
3254 foo = Foo()
3255 print (foo)
3256
3257 class Bar(models.Model):
3258 pass
3259 "
3260 (should (string= (python-shell-buffer-substring
3261 (python-tests-look-at "# coding: latin-1")
3262 (python-tests-look-at "if __name__ == \"__main__\":"))
3263 "# -*- coding: utf-8 -*-
3264
3265
3266 class Foo(models.Model):
3267 pass
3268
3269 "))))
3270
3271 (ert-deftest python-shell-buffer-substring-8 ()
3272 "Ensure first coding cookie gets precedence when sending whole buffer."
3273 (python-tests-with-temp-buffer
3274 "# coding: utf-8
3275 # coding: latin-1
3276
3277 class Foo(models.Model):
3278 pass
3279 "
3280 (should (string= (python-shell-buffer-substring (point-min) (point-max))
3281 "# coding: utf-8
3282
3283
3284 class Foo(models.Model):
3285 pass
3286 "))))
3287
3288 (ert-deftest python-shell-buffer-substring-9 ()
3289 "Check substring starting from `point-min'."
3290 (python-tests-with-temp-buffer
3291 "# coding: utf-8
3292
3293 class Foo(models.Model):
3294 pass
3295
3296 class Bar(models.Model):
3297 pass
3298 "
3299 (should (string= (python-shell-buffer-substring
3300 (point-min)
3301 (python-tests-look-at "class Bar(models.Model):"))
3302 "# coding: utf-8
3303
3304 class Foo(models.Model):
3305 pass
3306
3307 "))))
3308
3309 (ert-deftest python-shell-buffer-substring-10 ()
3310 "Check substring from partial block."
3311 (python-tests-with-temp-buffer
3312 "
3313 def foo():
3314 print ('a')
3315 "
3316 (should (string= (python-shell-buffer-substring
3317 (python-tests-look-at "print ('a')")
3318 (point-max))
3319 "if True:
3320
3321 print ('a')
3322 "))))
3323
3324 (ert-deftest python-shell-buffer-substring-11 ()
3325 "Check substring from partial block and point within indentation."
3326 (python-tests-with-temp-buffer
3327 "
3328 def foo():
3329 print ('a')
3330 "
3331 (should (string= (python-shell-buffer-substring
3332 (progn
3333 (python-tests-look-at "print ('a')")
3334 (backward-char 1)
3335 (point))
3336 (point-max))
3337 "if True:
3338
3339 print ('a')
3340 "))))
3341
3342 (ert-deftest python-shell-buffer-substring-12 ()
3343 "Check substring from partial block and point in whitespace."
3344 (python-tests-with-temp-buffer
3345 "
3346 def foo():
3347
3348 # Whitespace
3349
3350 print ('a')
3351 "
3352 (should (string= (python-shell-buffer-substring
3353 (python-tests-look-at "# Whitespace")
3354 (point-max))
3355 "if True:
3356
3357
3358 # Whitespace
3359
3360 print ('a')
3361 "))))
3362
3363
3364 \f
3365 ;;; Shell completion
3366
3367 (ert-deftest python-shell-completion-native-interpreter-disabled-p-1 ()
3368 (let* ((python-shell-completion-native-disabled-interpreters (list "pypy"))
3369 (python-shell-interpreter "/some/path/to/bin/pypy"))
3370 (should (python-shell-completion-native-interpreter-disabled-p))))
3371
3372
3373
3374 \f
3375 ;;; PDB Track integration
3376
3377 \f
3378 ;;; Symbol completion
3379
3380 \f
3381 ;;; Fill paragraph
3382
3383 \f
3384 ;;; Skeletons
3385
3386 \f
3387 ;;; FFAP
3388
3389 \f
3390 ;;; Code check
3391
3392 \f
3393 ;;; Eldoc
3394
3395 (ert-deftest python-eldoc--get-symbol-at-point-1 ()
3396 "Test paren handling."
3397 (python-tests-with-temp-buffer
3398 "
3399 map(xx
3400 map(codecs.open('somefile'
3401 "
3402 (python-tests-look-at "ap(xx")
3403 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3404 (goto-char (line-end-position))
3405 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3406 (python-tests-look-at "('somefile'")
3407 (should (string= (python-eldoc--get-symbol-at-point) "map"))
3408 (goto-char (line-end-position))
3409 (should (string= (python-eldoc--get-symbol-at-point) "codecs.open"))))
3410
3411 (ert-deftest python-eldoc--get-symbol-at-point-2 ()
3412 "Ensure self is replaced with the class name."
3413 (python-tests-with-temp-buffer
3414 "
3415 class TheClass:
3416
3417 def some_method(self, n):
3418 return n
3419
3420 def other(self):
3421 return self.some_method(1234)
3422
3423 "
3424 (python-tests-look-at "self.some_method")
3425 (should (string= (python-eldoc--get-symbol-at-point)
3426 "TheClass.some_method"))
3427 (python-tests-look-at "1234)")
3428 (should (string= (python-eldoc--get-symbol-at-point)
3429 "TheClass.some_method"))))
3430
3431 (ert-deftest python-eldoc--get-symbol-at-point-3 ()
3432 "Ensure symbol is found when point is at end of buffer."
3433 (python-tests-with-temp-buffer
3434 "
3435 some_symbol
3436
3437 "
3438 (goto-char (point-max))
3439 (should (string= (python-eldoc--get-symbol-at-point)
3440 "some_symbol"))))
3441
3442 (ert-deftest python-eldoc--get-symbol-at-point-4 ()
3443 "Ensure symbol is found when point is at whitespace."
3444 (python-tests-with-temp-buffer
3445 "
3446 some_symbol some_other_symbol
3447 "
3448 (python-tests-look-at " some_other_symbol")
3449 (should (string= (python-eldoc--get-symbol-at-point)
3450 "some_symbol"))))
3451
3452 \f
3453 ;;; Imenu
3454
3455 (ert-deftest python-imenu-create-index-1 ()
3456 (python-tests-with-temp-buffer
3457 "
3458 class Foo(models.Model):
3459 pass
3460
3461
3462 class Bar(models.Model):
3463 pass
3464
3465
3466 def decorator(arg1, arg2, arg3):
3467 '''print decorated function call data to stdout.
3468
3469 Usage:
3470
3471 @decorator('arg1', 'arg2')
3472 def func(a, b, c=True):
3473 pass
3474 '''
3475
3476 def wrap(f):
3477 print ('wrap')
3478 def wrapped_f(*args):
3479 print ('wrapped_f')
3480 print ('Decorator arguments:', arg1, arg2, arg3)
3481 f(*args)
3482 print ('called f(*args)')
3483 return wrapped_f
3484 return wrap
3485
3486
3487 class Baz(object):
3488
3489 def a(self):
3490 pass
3491
3492 def b(self):
3493 pass
3494
3495 class Frob(object):
3496
3497 def c(self):
3498 pass
3499 "
3500 (goto-char (point-max))
3501 (should (equal
3502 (list
3503 (cons "Foo (class)" (copy-marker 2))
3504 (cons "Bar (class)" (copy-marker 38))
3505 (list
3506 "decorator (def)"
3507 (cons "*function definition*" (copy-marker 74))
3508 (list
3509 "wrap (def)"
3510 (cons "*function definition*" (copy-marker 254))
3511 (cons "wrapped_f (def)" (copy-marker 294))))
3512 (list
3513 "Baz (class)"
3514 (cons "*class definition*" (copy-marker 519))
3515 (cons "a (def)" (copy-marker 539))
3516 (cons "b (def)" (copy-marker 570))
3517 (list
3518 "Frob (class)"
3519 (cons "*class definition*" (copy-marker 601))
3520 (cons "c (def)" (copy-marker 626)))))
3521 (python-imenu-create-index)))))
3522
3523 (ert-deftest python-imenu-create-index-2 ()
3524 (python-tests-with-temp-buffer
3525 "
3526 class Foo(object):
3527 def foo(self):
3528 def foo1():
3529 pass
3530
3531 def foobar(self):
3532 pass
3533 "
3534 (goto-char (point-max))
3535 (should (equal
3536 (list
3537 (list
3538 "Foo (class)"
3539 (cons "*class definition*" (copy-marker 2))
3540 (list
3541 "foo (def)"
3542 (cons "*function definition*" (copy-marker 21))
3543 (cons "foo1 (def)" (copy-marker 40)))
3544 (cons "foobar (def)" (copy-marker 78))))
3545 (python-imenu-create-index)))))
3546
3547 (ert-deftest python-imenu-create-index-3 ()
3548 (python-tests-with-temp-buffer
3549 "
3550 class Foo(object):
3551 def foo(self):
3552 def foo1():
3553 pass
3554 def foo2():
3555 pass
3556 "
3557 (goto-char (point-max))
3558 (should (equal
3559 (list
3560 (list
3561 "Foo (class)"
3562 (cons "*class definition*" (copy-marker 2))
3563 (list
3564 "foo (def)"
3565 (cons "*function definition*" (copy-marker 21))
3566 (cons "foo1 (def)" (copy-marker 40))
3567 (cons "foo2 (def)" (copy-marker 77)))))
3568 (python-imenu-create-index)))))
3569
3570 (ert-deftest python-imenu-create-index-4 ()
3571 (python-tests-with-temp-buffer
3572 "
3573 class Foo(object):
3574 class Bar(object):
3575 def __init__(self):
3576 pass
3577
3578 def __str__(self):
3579 pass
3580
3581 def __init__(self):
3582 pass
3583 "
3584 (goto-char (point-max))
3585 (should (equal
3586 (list
3587 (list
3588 "Foo (class)"
3589 (cons "*class definition*" (copy-marker 2))
3590 (list
3591 "Bar (class)"
3592 (cons "*class definition*" (copy-marker 21))
3593 (cons "__init__ (def)" (copy-marker 44))
3594 (cons "__str__ (def)" (copy-marker 90)))
3595 (cons "__init__ (def)" (copy-marker 135))))
3596 (python-imenu-create-index)))))
3597
3598 (ert-deftest python-imenu-create-flat-index-1 ()
3599 (python-tests-with-temp-buffer
3600 "
3601 class Foo(models.Model):
3602 pass
3603
3604
3605 class Bar(models.Model):
3606 pass
3607
3608
3609 def decorator(arg1, arg2, arg3):
3610 '''print decorated function call data to stdout.
3611
3612 Usage:
3613
3614 @decorator('arg1', 'arg2')
3615 def func(a, b, c=True):
3616 pass
3617 '''
3618
3619 def wrap(f):
3620 print ('wrap')
3621 def wrapped_f(*args):
3622 print ('wrapped_f')
3623 print ('Decorator arguments:', arg1, arg2, arg3)
3624 f(*args)
3625 print ('called f(*args)')
3626 return wrapped_f
3627 return wrap
3628
3629
3630 class Baz(object):
3631
3632 def a(self):
3633 pass
3634
3635 def b(self):
3636 pass
3637
3638 class Frob(object):
3639
3640 def c(self):
3641 pass
3642 "
3643 (goto-char (point-max))
3644 (should (equal
3645 (list (cons "Foo" (copy-marker 2))
3646 (cons "Bar" (copy-marker 38))
3647 (cons "decorator" (copy-marker 74))
3648 (cons "decorator.wrap" (copy-marker 254))
3649 (cons "decorator.wrap.wrapped_f" (copy-marker 294))
3650 (cons "Baz" (copy-marker 519))
3651 (cons "Baz.a" (copy-marker 539))
3652 (cons "Baz.b" (copy-marker 570))
3653 (cons "Baz.Frob" (copy-marker 601))
3654 (cons "Baz.Frob.c" (copy-marker 626)))
3655 (python-imenu-create-flat-index)))))
3656
3657 (ert-deftest python-imenu-create-flat-index-2 ()
3658 (python-tests-with-temp-buffer
3659 "
3660 class Foo(object):
3661 class Bar(object):
3662 def __init__(self):
3663 pass
3664
3665 def __str__(self):
3666 pass
3667
3668 def __init__(self):
3669 pass
3670 "
3671 (goto-char (point-max))
3672 (should (equal
3673 (list
3674 (cons "Foo" (copy-marker 2))
3675 (cons "Foo.Bar" (copy-marker 21))
3676 (cons "Foo.Bar.__init__" (copy-marker 44))
3677 (cons "Foo.Bar.__str__" (copy-marker 90))
3678 (cons "Foo.__init__" (copy-marker 135)))
3679 (python-imenu-create-flat-index)))))
3680
3681 \f
3682 ;;; Misc helpers
3683
3684 (ert-deftest python-info-current-defun-1 ()
3685 (python-tests-with-temp-buffer
3686 "
3687 def foo(a, b):
3688 "
3689 (forward-line 1)
3690 (should (string= "foo" (python-info-current-defun)))
3691 (should (string= "def foo" (python-info-current-defun t)))
3692 (forward-line 1)
3693 (should (not (python-info-current-defun)))
3694 (indent-for-tab-command)
3695 (should (string= "foo" (python-info-current-defun)))
3696 (should (string= "def foo" (python-info-current-defun t)))))
3697
3698 (ert-deftest python-info-current-defun-2 ()
3699 (python-tests-with-temp-buffer
3700 "
3701 class C(object):
3702
3703 def m(self):
3704 if True:
3705 return [i for i in range(3)]
3706 else:
3707 return []
3708
3709 def b():
3710 do_b()
3711
3712 def a():
3713 do_a()
3714
3715 def c(self):
3716 do_c()
3717 "
3718 (forward-line 1)
3719 (should (string= "C" (python-info-current-defun)))
3720 (should (string= "class C" (python-info-current-defun t)))
3721 (python-tests-look-at "return [i for ")
3722 (should (string= "C.m" (python-info-current-defun)))
3723 (should (string= "def C.m" (python-info-current-defun t)))
3724 (python-tests-look-at "def b():")
3725 (should (string= "C.m.b" (python-info-current-defun)))
3726 (should (string= "def C.m.b" (python-info-current-defun t)))
3727 (forward-line 2)
3728 (indent-for-tab-command)
3729 (python-indent-dedent-line-backspace 1)
3730 (should (string= "C.m" (python-info-current-defun)))
3731 (should (string= "def C.m" (python-info-current-defun t)))
3732 (python-tests-look-at "def c(self):")
3733 (forward-line -1)
3734 (indent-for-tab-command)
3735 (should (string= "C.m.a" (python-info-current-defun)))
3736 (should (string= "def C.m.a" (python-info-current-defun t)))
3737 (python-indent-dedent-line-backspace 1)
3738 (should (string= "C.m" (python-info-current-defun)))
3739 (should (string= "def C.m" (python-info-current-defun t)))
3740 (python-indent-dedent-line-backspace 1)
3741 (should (string= "C" (python-info-current-defun)))
3742 (should (string= "class C" (python-info-current-defun t)))
3743 (python-tests-look-at "def c(self):")
3744 (should (string= "C.c" (python-info-current-defun)))
3745 (should (string= "def C.c" (python-info-current-defun t)))
3746 (python-tests-look-at "do_c()")
3747 (should (string= "C.c" (python-info-current-defun)))
3748 (should (string= "def C.c" (python-info-current-defun t)))))
3749
3750 (ert-deftest python-info-current-defun-3 ()
3751 (python-tests-with-temp-buffer
3752 "
3753 def decoratorFunctionWithArguments(arg1, arg2, arg3):
3754 '''print decorated function call data to stdout.
3755
3756 Usage:
3757
3758 @decoratorFunctionWithArguments('arg1', 'arg2')
3759 def func(a, b, c=True):
3760 pass
3761 '''
3762
3763 def wwrap(f):
3764 print 'Inside wwrap()'
3765 def wrapped_f(*args):
3766 print 'Inside wrapped_f()'
3767 print 'Decorator arguments:', arg1, arg2, arg3
3768 f(*args)
3769 print 'After f(*args)'
3770 return wrapped_f
3771 return wwrap
3772 "
3773 (python-tests-look-at "def wwrap(f):")
3774 (forward-line -1)
3775 (should (not (python-info-current-defun)))
3776 (indent-for-tab-command 1)
3777 (should (string= (python-info-current-defun)
3778 "decoratorFunctionWithArguments"))
3779 (should (string= (python-info-current-defun t)
3780 "def decoratorFunctionWithArguments"))
3781 (python-tests-look-at "def wrapped_f(*args):")
3782 (should (string= (python-info-current-defun)
3783 "decoratorFunctionWithArguments.wwrap.wrapped_f"))
3784 (should (string= (python-info-current-defun t)
3785 "def decoratorFunctionWithArguments.wwrap.wrapped_f"))
3786 (python-tests-look-at "return wrapped_f")
3787 (should (string= (python-info-current-defun)
3788 "decoratorFunctionWithArguments.wwrap"))
3789 (should (string= (python-info-current-defun t)
3790 "def decoratorFunctionWithArguments.wwrap"))
3791 (end-of-line 1)
3792 (python-tests-look-at "return wwrap")
3793 (should (string= (python-info-current-defun)
3794 "decoratorFunctionWithArguments"))
3795 (should (string= (python-info-current-defun t)
3796 "def decoratorFunctionWithArguments"))))
3797
3798 (ert-deftest python-info-current-symbol-1 ()
3799 (python-tests-with-temp-buffer
3800 "
3801 class C(object):
3802
3803 def m(self):
3804 self.c()
3805
3806 def c(self):
3807 print ('a')
3808 "
3809 (python-tests-look-at "self.c()")
3810 (should (string= "self.c" (python-info-current-symbol)))
3811 (should (string= "C.c" (python-info-current-symbol t)))))
3812
3813 (ert-deftest python-info-current-symbol-2 ()
3814 (python-tests-with-temp-buffer
3815 "
3816 class C(object):
3817
3818 class M(object):
3819
3820 def a(self):
3821 self.c()
3822
3823 def c(self):
3824 pass
3825 "
3826 (python-tests-look-at "self.c()")
3827 (should (string= "self.c" (python-info-current-symbol)))
3828 (should (string= "C.M.c" (python-info-current-symbol t)))))
3829
3830 (ert-deftest python-info-current-symbol-3 ()
3831 "Keywords should not be considered symbols."
3832 :expected-result :failed
3833 (python-tests-with-temp-buffer
3834 "
3835 class C(object):
3836 pass
3837 "
3838 ;; FIXME: keywords are not symbols.
3839 (python-tests-look-at "class C")
3840 (should (not (python-info-current-symbol)))
3841 (should (not (python-info-current-symbol t)))
3842 (python-tests-look-at "C(object)")
3843 (should (string= "C" (python-info-current-symbol)))
3844 (should (string= "class C" (python-info-current-symbol t)))))
3845
3846 (ert-deftest python-info-statement-starts-block-p-1 ()
3847 (python-tests-with-temp-buffer
3848 "
3849 def long_function_name(
3850 var_one, var_two, var_three,
3851 var_four):
3852 print (var_one)
3853 "
3854 (python-tests-look-at "def long_function_name")
3855 (should (python-info-statement-starts-block-p))
3856 (python-tests-look-at "print (var_one)")
3857 (python-util-forward-comment -1)
3858 (should (python-info-statement-starts-block-p))))
3859
3860 (ert-deftest python-info-statement-starts-block-p-2 ()
3861 (python-tests-with-temp-buffer
3862 "
3863 if width == 0 and height == 0 and \\\\
3864 color == 'red' and emphasis == 'strong' or \\\\
3865 highlight > 100:
3866 raise ValueError('sorry, you lose')
3867 "
3868 (python-tests-look-at "if width == 0 and")
3869 (should (python-info-statement-starts-block-p))
3870 (python-tests-look-at "raise ValueError(")
3871 (python-util-forward-comment -1)
3872 (should (python-info-statement-starts-block-p))))
3873
3874 (ert-deftest python-info-statement-ends-block-p-1 ()
3875 (python-tests-with-temp-buffer
3876 "
3877 def long_function_name(
3878 var_one, var_two, var_three,
3879 var_four):
3880 print (var_one)
3881 "
3882 (python-tests-look-at "print (var_one)")
3883 (should (python-info-statement-ends-block-p))))
3884
3885 (ert-deftest python-info-statement-ends-block-p-2 ()
3886 (python-tests-with-temp-buffer
3887 "
3888 if width == 0 and height == 0 and \\\\
3889 color == 'red' and emphasis == 'strong' or \\\\
3890 highlight > 100:
3891 raise ValueError(
3892 'sorry, you lose'
3893
3894 )
3895 "
3896 (python-tests-look-at "raise ValueError(")
3897 (should (python-info-statement-ends-block-p))))
3898
3899 (ert-deftest python-info-beginning-of-statement-p-1 ()
3900 (python-tests-with-temp-buffer
3901 "
3902 def long_function_name(
3903 var_one, var_two, var_three,
3904 var_four):
3905 print (var_one)
3906 "
3907 (python-tests-look-at "def long_function_name")
3908 (should (python-info-beginning-of-statement-p))
3909 (forward-char 10)
3910 (should (not (python-info-beginning-of-statement-p)))
3911 (python-tests-look-at "print (var_one)")
3912 (should (python-info-beginning-of-statement-p))
3913 (goto-char (line-beginning-position))
3914 (should (not (python-info-beginning-of-statement-p)))))
3915
3916 (ert-deftest python-info-beginning-of-statement-p-2 ()
3917 (python-tests-with-temp-buffer
3918 "
3919 if width == 0 and height == 0 and \\\\
3920 color == 'red' and emphasis == 'strong' or \\\\
3921 highlight > 100:
3922 raise ValueError(
3923 'sorry, you lose'
3924
3925 )
3926 "
3927 (python-tests-look-at "if width == 0 and")
3928 (should (python-info-beginning-of-statement-p))
3929 (forward-char 10)
3930 (should (not (python-info-beginning-of-statement-p)))
3931 (python-tests-look-at "raise ValueError(")
3932 (should (python-info-beginning-of-statement-p))
3933 (goto-char (line-beginning-position))
3934 (should (not (python-info-beginning-of-statement-p)))))
3935
3936 (ert-deftest python-info-end-of-statement-p-1 ()
3937 (python-tests-with-temp-buffer
3938 "
3939 def long_function_name(
3940 var_one, var_two, var_three,
3941 var_four):
3942 print (var_one)
3943 "
3944 (python-tests-look-at "def long_function_name")
3945 (should (not (python-info-end-of-statement-p)))
3946 (end-of-line)
3947 (should (not (python-info-end-of-statement-p)))
3948 (python-tests-look-at "print (var_one)")
3949 (python-util-forward-comment -1)
3950 (should (python-info-end-of-statement-p))
3951 (python-tests-look-at "print (var_one)")
3952 (should (not (python-info-end-of-statement-p)))
3953 (end-of-line)
3954 (should (python-info-end-of-statement-p))))
3955
3956 (ert-deftest python-info-end-of-statement-p-2 ()
3957 (python-tests-with-temp-buffer
3958 "
3959 if width == 0 and height == 0 and \\\\
3960 color == 'red' and emphasis == 'strong' or \\\\
3961 highlight > 100:
3962 raise ValueError(
3963 'sorry, you lose'
3964
3965 )
3966 "
3967 (python-tests-look-at "if width == 0 and")
3968 (should (not (python-info-end-of-statement-p)))
3969 (end-of-line)
3970 (should (not (python-info-end-of-statement-p)))
3971 (python-tests-look-at "raise ValueError(")
3972 (python-util-forward-comment -1)
3973 (should (python-info-end-of-statement-p))
3974 (python-tests-look-at "raise ValueError(")
3975 (should (not (python-info-end-of-statement-p)))
3976 (end-of-line)
3977 (should (not (python-info-end-of-statement-p)))
3978 (goto-char (point-max))
3979 (python-util-forward-comment -1)
3980 (should (python-info-end-of-statement-p))))
3981
3982 (ert-deftest python-info-beginning-of-block-p-1 ()
3983 (python-tests-with-temp-buffer
3984 "
3985 def long_function_name(
3986 var_one, var_two, var_three,
3987 var_four):
3988 print (var_one)
3989 "
3990 (python-tests-look-at "def long_function_name")
3991 (should (python-info-beginning-of-block-p))
3992 (python-tests-look-at "var_one, var_two, var_three,")
3993 (should (not (python-info-beginning-of-block-p)))
3994 (python-tests-look-at "print (var_one)")
3995 (should (not (python-info-beginning-of-block-p)))))
3996
3997 (ert-deftest python-info-beginning-of-block-p-2 ()
3998 (python-tests-with-temp-buffer
3999 "
4000 if width == 0 and height == 0 and \\\\
4001 color == 'red' and emphasis == 'strong' or \\\\
4002 highlight > 100:
4003 raise ValueError(
4004 'sorry, you lose'
4005
4006 )
4007 "
4008 (python-tests-look-at "if width == 0 and")
4009 (should (python-info-beginning-of-block-p))
4010 (python-tests-look-at "color == 'red' and emphasis")
4011 (should (not (python-info-beginning-of-block-p)))
4012 (python-tests-look-at "raise ValueError(")
4013 (should (not (python-info-beginning-of-block-p)))))
4014
4015 (ert-deftest python-info-end-of-block-p-1 ()
4016 (python-tests-with-temp-buffer
4017 "
4018 def long_function_name(
4019 var_one, var_two, var_three,
4020 var_four):
4021 print (var_one)
4022 "
4023 (python-tests-look-at "def long_function_name")
4024 (should (not (python-info-end-of-block-p)))
4025 (python-tests-look-at "var_one, var_two, var_three,")
4026 (should (not (python-info-end-of-block-p)))
4027 (python-tests-look-at "var_four):")
4028 (end-of-line)
4029 (should (not (python-info-end-of-block-p)))
4030 (python-tests-look-at "print (var_one)")
4031 (should (not (python-info-end-of-block-p)))
4032 (end-of-line 1)
4033 (should (python-info-end-of-block-p))))
4034
4035 (ert-deftest python-info-end-of-block-p-2 ()
4036 (python-tests-with-temp-buffer
4037 "
4038 if width == 0 and height == 0 and \\\\
4039 color == 'red' and emphasis == 'strong' or \\\\
4040 highlight > 100:
4041 raise ValueError(
4042 'sorry, you lose'
4043
4044 )
4045 "
4046 (python-tests-look-at "if width == 0 and")
4047 (should (not (python-info-end-of-block-p)))
4048 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4049 (should (not (python-info-end-of-block-p)))
4050 (python-tests-look-at "highlight > 100:")
4051 (end-of-line)
4052 (should (not (python-info-end-of-block-p)))
4053 (python-tests-look-at "raise ValueError(")
4054 (should (not (python-info-end-of-block-p)))
4055 (end-of-line 1)
4056 (should (not (python-info-end-of-block-p)))
4057 (goto-char (point-max))
4058 (python-util-forward-comment -1)
4059 (should (python-info-end-of-block-p))))
4060
4061 (ert-deftest python-info-dedenter-opening-block-position-1 ()
4062 (python-tests-with-temp-buffer
4063 "
4064 if request.user.is_authenticated():
4065 try:
4066 profile = request.user.get_profile()
4067 except Profile.DoesNotExist:
4068 profile = Profile.objects.create(user=request.user)
4069 else:
4070 if profile.stats:
4071 profile.recalculate_stats()
4072 else:
4073 profile.clear_stats()
4074 finally:
4075 profile.views += 1
4076 profile.save()
4077 "
4078 (python-tests-look-at "try:")
4079 (should (not (python-info-dedenter-opening-block-position)))
4080 (python-tests-look-at "except Profile.DoesNotExist:")
4081 (should (= (python-tests-look-at "try:" -1 t)
4082 (python-info-dedenter-opening-block-position)))
4083 (python-tests-look-at "else:")
4084 (should (= (python-tests-look-at "except Profile.DoesNotExist:" -1 t)
4085 (python-info-dedenter-opening-block-position)))
4086 (python-tests-look-at "if profile.stats:")
4087 (should (not (python-info-dedenter-opening-block-position)))
4088 (python-tests-look-at "else:")
4089 (should (= (python-tests-look-at "if profile.stats:" -1 t)
4090 (python-info-dedenter-opening-block-position)))
4091 (python-tests-look-at "finally:")
4092 (should (= (python-tests-look-at "else:" -2 t)
4093 (python-info-dedenter-opening-block-position)))))
4094
4095 (ert-deftest python-info-dedenter-opening-block-position-2 ()
4096 (python-tests-with-temp-buffer
4097 "
4098 if request.user.is_authenticated():
4099 profile = Profile.objects.get_or_create(user=request.user)
4100 if profile.stats:
4101 profile.recalculate_stats()
4102
4103 data = {
4104 'else': 'do it'
4105 }
4106 'else'
4107 "
4108 (python-tests-look-at "'else': 'do it'")
4109 (should (not (python-info-dedenter-opening-block-position)))
4110 (python-tests-look-at "'else'")
4111 (should (not (python-info-dedenter-opening-block-position)))))
4112
4113 (ert-deftest python-info-dedenter-opening-block-position-3 ()
4114 (python-tests-with-temp-buffer
4115 "
4116 if save:
4117 try:
4118 write_to_disk(data)
4119 except IOError:
4120 msg = 'Error saving to disk'
4121 message(msg)
4122 logger.exception(msg)
4123 except Exception:
4124 if hide_details:
4125 logger.exception('Unhandled exception')
4126 else
4127 finally:
4128 data.free()
4129 "
4130 (python-tests-look-at "try:")
4131 (should (not (python-info-dedenter-opening-block-position)))
4132
4133 (python-tests-look-at "except IOError:")
4134 (should (= (python-tests-look-at "try:" -1 t)
4135 (python-info-dedenter-opening-block-position)))
4136
4137 (python-tests-look-at "except Exception:")
4138 (should (= (python-tests-look-at "except IOError:" -1 t)
4139 (python-info-dedenter-opening-block-position)))
4140
4141 (python-tests-look-at "if hide_details:")
4142 (should (not (python-info-dedenter-opening-block-position)))
4143
4144 ;; check indentation modifies the detected opening block
4145 (python-tests-look-at "else")
4146 (should (= (python-tests-look-at "if hide_details:" -1 t)
4147 (python-info-dedenter-opening-block-position)))
4148
4149 (indent-line-to 8)
4150 (should (= (python-tests-look-at "if hide_details:" -1 t)
4151 (python-info-dedenter-opening-block-position)))
4152
4153 (indent-line-to 4)
4154 (should (= (python-tests-look-at "except Exception:" -1 t)
4155 (python-info-dedenter-opening-block-position)))
4156
4157 (indent-line-to 0)
4158 (should (= (python-tests-look-at "if save:" -1 t)
4159 (python-info-dedenter-opening-block-position)))))
4160
4161 (ert-deftest python-info-dedenter-opening-block-positions-1 ()
4162 (python-tests-with-temp-buffer
4163 "
4164 if save:
4165 try:
4166 write_to_disk(data)
4167 except IOError:
4168 msg = 'Error saving to disk'
4169 message(msg)
4170 logger.exception(msg)
4171 except Exception:
4172 if hide_details:
4173 logger.exception('Unhandled exception')
4174 else
4175 finally:
4176 data.free()
4177 "
4178 (python-tests-look-at "try:")
4179 (should (not (python-info-dedenter-opening-block-positions)))
4180
4181 (python-tests-look-at "except IOError:")
4182 (should
4183 (equal (list
4184 (python-tests-look-at "try:" -1 t))
4185 (python-info-dedenter-opening-block-positions)))
4186
4187 (python-tests-look-at "except Exception:")
4188 (should
4189 (equal (list
4190 (python-tests-look-at "except IOError:" -1 t))
4191 (python-info-dedenter-opening-block-positions)))
4192
4193 (python-tests-look-at "if hide_details:")
4194 (should (not (python-info-dedenter-opening-block-positions)))
4195
4196 ;; check indentation does not modify the detected opening blocks
4197 (python-tests-look-at "else")
4198 (should
4199 (equal (list
4200 (python-tests-look-at "if hide_details:" -1 t)
4201 (python-tests-look-at "except Exception:" -1 t)
4202 (python-tests-look-at "if save:" -1 t))
4203 (python-info-dedenter-opening-block-positions)))
4204
4205 (indent-line-to 8)
4206 (should
4207 (equal (list
4208 (python-tests-look-at "if hide_details:" -1 t)
4209 (python-tests-look-at "except Exception:" -1 t)
4210 (python-tests-look-at "if save:" -1 t))
4211 (python-info-dedenter-opening-block-positions)))
4212
4213 (indent-line-to 4)
4214 (should
4215 (equal (list
4216 (python-tests-look-at "if hide_details:" -1 t)
4217 (python-tests-look-at "except Exception:" -1 t)
4218 (python-tests-look-at "if save:" -1 t))
4219 (python-info-dedenter-opening-block-positions)))
4220
4221 (indent-line-to 0)
4222 (should
4223 (equal (list
4224 (python-tests-look-at "if hide_details:" -1 t)
4225 (python-tests-look-at "except Exception:" -1 t)
4226 (python-tests-look-at "if save:" -1 t))
4227 (python-info-dedenter-opening-block-positions)))))
4228
4229 (ert-deftest python-info-dedenter-opening-block-positions-2 ()
4230 "Test detection of opening blocks for elif."
4231 (python-tests-with-temp-buffer
4232 "
4233 if var:
4234 if var2:
4235 something()
4236 elif var3:
4237 something_else()
4238 elif
4239 "
4240 (python-tests-look-at "elif var3:")
4241 (should
4242 (equal (list
4243 (python-tests-look-at "if var2:" -1 t)
4244 (python-tests-look-at "if var:" -1 t))
4245 (python-info-dedenter-opening-block-positions)))
4246
4247 (python-tests-look-at "elif\n")
4248 (should
4249 (equal (list
4250 (python-tests-look-at "elif var3:" -1 t)
4251 (python-tests-look-at "if var:" -1 t))
4252 (python-info-dedenter-opening-block-positions)))))
4253
4254 (ert-deftest python-info-dedenter-opening-block-positions-3 ()
4255 "Test detection of opening blocks for else."
4256 (python-tests-with-temp-buffer
4257 "
4258 try:
4259 something()
4260 except:
4261 if var:
4262 if var2:
4263 something()
4264 elif var3:
4265 something_else()
4266 else
4267
4268 if var4:
4269 while var5:
4270 var4.pop()
4271 else
4272
4273 for value in var6:
4274 if value > 0:
4275 print value
4276 else
4277 "
4278 (python-tests-look-at "else\n")
4279 (should
4280 (equal (list
4281 (python-tests-look-at "elif var3:" -1 t)
4282 (python-tests-look-at "if var:" -1 t)
4283 (python-tests-look-at "except:" -1 t))
4284 (python-info-dedenter-opening-block-positions)))
4285
4286 (python-tests-look-at "else\n")
4287 (should
4288 (equal (list
4289 (python-tests-look-at "while var5:" -1 t)
4290 (python-tests-look-at "if var4:" -1 t))
4291 (python-info-dedenter-opening-block-positions)))
4292
4293 (python-tests-look-at "else\n")
4294 (should
4295 (equal (list
4296 (python-tests-look-at "if value > 0:" -1 t)
4297 (python-tests-look-at "for value in var6:" -1 t)
4298 (python-tests-look-at "if var4:" -1 t))
4299 (python-info-dedenter-opening-block-positions)))))
4300
4301 (ert-deftest python-info-dedenter-opening-block-positions-4 ()
4302 "Test detection of opening blocks for except."
4303 (python-tests-with-temp-buffer
4304 "
4305 try:
4306 something()
4307 except ValueError:
4308 something_else()
4309 except
4310 "
4311 (python-tests-look-at "except ValueError:")
4312 (should
4313 (equal (list (python-tests-look-at "try:" -1 t))
4314 (python-info-dedenter-opening-block-positions)))
4315
4316 (python-tests-look-at "except\n")
4317 (should
4318 (equal (list (python-tests-look-at "except ValueError:" -1 t))
4319 (python-info-dedenter-opening-block-positions)))))
4320
4321 (ert-deftest python-info-dedenter-opening-block-positions-5 ()
4322 "Test detection of opening blocks for finally."
4323 (python-tests-with-temp-buffer
4324 "
4325 try:
4326 something()
4327 finally
4328
4329 try:
4330 something_else()
4331 except:
4332 logger.exception('something went wrong')
4333 finally
4334
4335 try:
4336 something_else_else()
4337 except Exception:
4338 logger.exception('something else went wrong')
4339 else:
4340 print ('all good')
4341 finally
4342 "
4343 (python-tests-look-at "finally\n")
4344 (should
4345 (equal (list (python-tests-look-at "try:" -1 t))
4346 (python-info-dedenter-opening-block-positions)))
4347
4348 (python-tests-look-at "finally\n")
4349 (should
4350 (equal (list (python-tests-look-at "except:" -1 t))
4351 (python-info-dedenter-opening-block-positions)))
4352
4353 (python-tests-look-at "finally\n")
4354 (should
4355 (equal (list (python-tests-look-at "else:" -1 t))
4356 (python-info-dedenter-opening-block-positions)))))
4357
4358 (ert-deftest python-info-dedenter-opening-block-message-1 ()
4359 "Test dedenters inside strings are ignored."
4360 (python-tests-with-temp-buffer
4361 "'''
4362 try:
4363 something()
4364 except:
4365 logger.exception('something went wrong')
4366 '''
4367 "
4368 (python-tests-look-at "except\n")
4369 (should (not (python-info-dedenter-opening-block-message)))))
4370
4371 (ert-deftest python-info-dedenter-opening-block-message-2 ()
4372 "Test except keyword."
4373 (python-tests-with-temp-buffer
4374 "
4375 try:
4376 something()
4377 except:
4378 logger.exception('something went wrong')
4379 "
4380 (python-tests-look-at "except:")
4381 (should (string=
4382 "Closes try:"
4383 (substring-no-properties
4384 (python-info-dedenter-opening-block-message))))
4385 (end-of-line)
4386 (should (string=
4387 "Closes try:"
4388 (substring-no-properties
4389 (python-info-dedenter-opening-block-message))))))
4390
4391 (ert-deftest python-info-dedenter-opening-block-message-3 ()
4392 "Test else keyword."
4393 (python-tests-with-temp-buffer
4394 "
4395 try:
4396 something()
4397 except:
4398 logger.exception('something went wrong')
4399 else:
4400 logger.debug('all good')
4401 "
4402 (python-tests-look-at "else:")
4403 (should (string=
4404 "Closes except:"
4405 (substring-no-properties
4406 (python-info-dedenter-opening-block-message))))
4407 (end-of-line)
4408 (should (string=
4409 "Closes except:"
4410 (substring-no-properties
4411 (python-info-dedenter-opening-block-message))))))
4412
4413 (ert-deftest python-info-dedenter-opening-block-message-4 ()
4414 "Test finally keyword."
4415 (python-tests-with-temp-buffer
4416 "
4417 try:
4418 something()
4419 except:
4420 logger.exception('something went wrong')
4421 else:
4422 logger.debug('all good')
4423 finally:
4424 clean()
4425 "
4426 (python-tests-look-at "finally:")
4427 (should (string=
4428 "Closes else:"
4429 (substring-no-properties
4430 (python-info-dedenter-opening-block-message))))
4431 (end-of-line)
4432 (should (string=
4433 "Closes else:"
4434 (substring-no-properties
4435 (python-info-dedenter-opening-block-message))))))
4436
4437 (ert-deftest python-info-dedenter-opening-block-message-5 ()
4438 "Test elif keyword."
4439 (python-tests-with-temp-buffer
4440 "
4441 if a:
4442 something()
4443 elif b:
4444 "
4445 (python-tests-look-at "elif b:")
4446 (should (string=
4447 "Closes if a:"
4448 (substring-no-properties
4449 (python-info-dedenter-opening-block-message))))
4450 (end-of-line)
4451 (should (string=
4452 "Closes if a:"
4453 (substring-no-properties
4454 (python-info-dedenter-opening-block-message))))))
4455
4456
4457 (ert-deftest python-info-dedenter-statement-p-1 ()
4458 "Test dedenters inside strings are ignored."
4459 (python-tests-with-temp-buffer
4460 "'''
4461 try:
4462 something()
4463 except:
4464 logger.exception('something went wrong')
4465 '''
4466 "
4467 (python-tests-look-at "except\n")
4468 (should (not (python-info-dedenter-statement-p)))))
4469
4470 (ert-deftest python-info-dedenter-statement-p-2 ()
4471 "Test except keyword."
4472 (python-tests-with-temp-buffer
4473 "
4474 try:
4475 something()
4476 except:
4477 logger.exception('something went wrong')
4478 "
4479 (python-tests-look-at "except:")
4480 (should (= (point) (python-info-dedenter-statement-p)))
4481 (end-of-line)
4482 (should (= (save-excursion
4483 (back-to-indentation)
4484 (point))
4485 (python-info-dedenter-statement-p)))))
4486
4487 (ert-deftest python-info-dedenter-statement-p-3 ()
4488 "Test else keyword."
4489 (python-tests-with-temp-buffer
4490 "
4491 try:
4492 something()
4493 except:
4494 logger.exception('something went wrong')
4495 else:
4496 logger.debug('all good')
4497 "
4498 (python-tests-look-at "else:")
4499 (should (= (point) (python-info-dedenter-statement-p)))
4500 (end-of-line)
4501 (should (= (save-excursion
4502 (back-to-indentation)
4503 (point))
4504 (python-info-dedenter-statement-p)))))
4505
4506 (ert-deftest python-info-dedenter-statement-p-4 ()
4507 "Test finally keyword."
4508 (python-tests-with-temp-buffer
4509 "
4510 try:
4511 something()
4512 except:
4513 logger.exception('something went wrong')
4514 else:
4515 logger.debug('all good')
4516 finally:
4517 clean()
4518 "
4519 (python-tests-look-at "finally:")
4520 (should (= (point) (python-info-dedenter-statement-p)))
4521 (end-of-line)
4522 (should (= (save-excursion
4523 (back-to-indentation)
4524 (point))
4525 (python-info-dedenter-statement-p)))))
4526
4527 (ert-deftest python-info-dedenter-statement-p-5 ()
4528 "Test elif keyword."
4529 (python-tests-with-temp-buffer
4530 "
4531 if a:
4532 something()
4533 elif b:
4534 "
4535 (python-tests-look-at "elif b:")
4536 (should (= (point) (python-info-dedenter-statement-p)))
4537 (end-of-line)
4538 (should (= (save-excursion
4539 (back-to-indentation)
4540 (point))
4541 (python-info-dedenter-statement-p)))))
4542
4543 (ert-deftest python-info-line-ends-backslash-p-1 ()
4544 (python-tests-with-temp-buffer
4545 "
4546 objects = Thing.objects.all() \\\\
4547 .filter(
4548 type='toy',
4549 status='bought'
4550 ) \\\\
4551 .aggregate(
4552 Sum('amount')
4553 ) \\\\
4554 .values_list()
4555 "
4556 (should (python-info-line-ends-backslash-p 2)) ; .filter(...
4557 (should (python-info-line-ends-backslash-p 3))
4558 (should (python-info-line-ends-backslash-p 4))
4559 (should (python-info-line-ends-backslash-p 5))
4560 (should (python-info-line-ends-backslash-p 6)) ; ) \...
4561 (should (python-info-line-ends-backslash-p 7))
4562 (should (python-info-line-ends-backslash-p 8))
4563 (should (python-info-line-ends-backslash-p 9))
4564 (should (not (python-info-line-ends-backslash-p 10))))) ; .values_list()...
4565
4566 (ert-deftest python-info-beginning-of-backslash-1 ()
4567 (python-tests-with-temp-buffer
4568 "
4569 objects = Thing.objects.all() \\\\
4570 .filter(
4571 type='toy',
4572 status='bought'
4573 ) \\\\
4574 .aggregate(
4575 Sum('amount')
4576 ) \\\\
4577 .values_list()
4578 "
4579 (let ((first 2)
4580 (second (python-tests-look-at ".filter("))
4581 (third (python-tests-look-at ".aggregate(")))
4582 (should (= first (python-info-beginning-of-backslash 2)))
4583 (should (= second (python-info-beginning-of-backslash 3)))
4584 (should (= second (python-info-beginning-of-backslash 4)))
4585 (should (= second (python-info-beginning-of-backslash 5)))
4586 (should (= second (python-info-beginning-of-backslash 6)))
4587 (should (= third (python-info-beginning-of-backslash 7)))
4588 (should (= third (python-info-beginning-of-backslash 8)))
4589 (should (= third (python-info-beginning-of-backslash 9)))
4590 (should (not (python-info-beginning-of-backslash 10))))))
4591
4592 (ert-deftest python-info-continuation-line-p-1 ()
4593 (python-tests-with-temp-buffer
4594 "
4595 if width == 0 and height == 0 and \\\\
4596 color == 'red' and emphasis == 'strong' or \\\\
4597 highlight > 100:
4598 raise ValueError(
4599 'sorry, you lose'
4600
4601 )
4602 "
4603 (python-tests-look-at "if width == 0 and height == 0 and")
4604 (should (not (python-info-continuation-line-p)))
4605 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4606 (should (python-info-continuation-line-p))
4607 (python-tests-look-at "highlight > 100:")
4608 (should (python-info-continuation-line-p))
4609 (python-tests-look-at "raise ValueError(")
4610 (should (not (python-info-continuation-line-p)))
4611 (python-tests-look-at "'sorry, you lose'")
4612 (should (python-info-continuation-line-p))
4613 (forward-line 1)
4614 (should (python-info-continuation-line-p))
4615 (python-tests-look-at ")")
4616 (should (python-info-continuation-line-p))
4617 (forward-line 1)
4618 (should (not (python-info-continuation-line-p)))))
4619
4620 (ert-deftest python-info-block-continuation-line-p-1 ()
4621 (python-tests-with-temp-buffer
4622 "
4623 if width == 0 and height == 0 and \\\\
4624 color == 'red' and emphasis == 'strong' or \\\\
4625 highlight > 100:
4626 raise ValueError(
4627 'sorry, you lose'
4628
4629 )
4630 "
4631 (python-tests-look-at "if width == 0 and")
4632 (should (not (python-info-block-continuation-line-p)))
4633 (python-tests-look-at "color == 'red' and emphasis == 'strong' or")
4634 (should (= (python-info-block-continuation-line-p)
4635 (python-tests-look-at "if width == 0 and" -1 t)))
4636 (python-tests-look-at "highlight > 100:")
4637 (should (not (python-info-block-continuation-line-p)))))
4638
4639 (ert-deftest python-info-block-continuation-line-p-2 ()
4640 (python-tests-with-temp-buffer
4641 "
4642 def foo(a,
4643 b,
4644 c):
4645 pass
4646 "
4647 (python-tests-look-at "def foo(a,")
4648 (should (not (python-info-block-continuation-line-p)))
4649 (python-tests-look-at "b,")
4650 (should (= (python-info-block-continuation-line-p)
4651 (python-tests-look-at "def foo(a," -1 t)))
4652 (python-tests-look-at "c):")
4653 (should (not (python-info-block-continuation-line-p)))))
4654
4655 (ert-deftest python-info-assignment-statement-p-1 ()
4656 (python-tests-with-temp-buffer
4657 "
4658 data = foo(), bar() \\\\
4659 baz(), 4 \\\\
4660 5, 6
4661 "
4662 (python-tests-look-at "data = foo(), bar()")
4663 (should (python-info-assignment-statement-p))
4664 (should (python-info-assignment-statement-p t))
4665 (python-tests-look-at "baz(), 4")
4666 (should (python-info-assignment-statement-p))
4667 (should (not (python-info-assignment-statement-p t)))
4668 (python-tests-look-at "5, 6")
4669 (should (python-info-assignment-statement-p))
4670 (should (not (python-info-assignment-statement-p t)))))
4671
4672 (ert-deftest python-info-assignment-statement-p-2 ()
4673 (python-tests-with-temp-buffer
4674 "
4675 data = (foo(), bar()
4676 baz(), 4
4677 5, 6)
4678 "
4679 (python-tests-look-at "data = (foo(), bar()")
4680 (should (python-info-assignment-statement-p))
4681 (should (python-info-assignment-statement-p t))
4682 (python-tests-look-at "baz(), 4")
4683 (should (python-info-assignment-statement-p))
4684 (should (not (python-info-assignment-statement-p t)))
4685 (python-tests-look-at "5, 6)")
4686 (should (python-info-assignment-statement-p))
4687 (should (not (python-info-assignment-statement-p t)))))
4688
4689 (ert-deftest python-info-assignment-statement-p-3 ()
4690 (python-tests-with-temp-buffer
4691 "
4692 data '=' 42
4693 "
4694 (python-tests-look-at "data '=' 42")
4695 (should (not (python-info-assignment-statement-p)))
4696 (should (not (python-info-assignment-statement-p t)))))
4697
4698 (ert-deftest python-info-assignment-continuation-line-p-1 ()
4699 (python-tests-with-temp-buffer
4700 "
4701 data = foo(), bar() \\\\
4702 baz(), 4 \\\\
4703 5, 6
4704 "
4705 (python-tests-look-at "data = foo(), bar()")
4706 (should (not (python-info-assignment-continuation-line-p)))
4707 (python-tests-look-at "baz(), 4")
4708 (should (= (python-info-assignment-continuation-line-p)
4709 (python-tests-look-at "foo()," -1 t)))
4710 (python-tests-look-at "5, 6")
4711 (should (not (python-info-assignment-continuation-line-p)))))
4712
4713 (ert-deftest python-info-assignment-continuation-line-p-2 ()
4714 (python-tests-with-temp-buffer
4715 "
4716 data = (foo(), bar()
4717 baz(), 4
4718 5, 6)
4719 "
4720 (python-tests-look-at "data = (foo(), bar()")
4721 (should (not (python-info-assignment-continuation-line-p)))
4722 (python-tests-look-at "baz(), 4")
4723 (should (= (python-info-assignment-continuation-line-p)
4724 (python-tests-look-at "(foo()," -1 t)))
4725 (python-tests-look-at "5, 6)")
4726 (should (not (python-info-assignment-continuation-line-p)))))
4727
4728 (ert-deftest python-info-looking-at-beginning-of-defun-1 ()
4729 (python-tests-with-temp-buffer
4730 "
4731 def decorat0r(deff):
4732 '''decorates stuff.
4733
4734 @decorat0r
4735 def foo(arg):
4736 ...
4737 '''
4738 def wrap():
4739 deff()
4740 return wwrap
4741 "
4742 (python-tests-look-at "def decorat0r(deff):")
4743 (should (python-info-looking-at-beginning-of-defun))
4744 (python-tests-look-at "def foo(arg):")
4745 (should (not (python-info-looking-at-beginning-of-defun)))
4746 (python-tests-look-at "def wrap():")
4747 (should (python-info-looking-at-beginning-of-defun))
4748 (python-tests-look-at "deff()")
4749 (should (not (python-info-looking-at-beginning-of-defun)))))
4750
4751 (ert-deftest python-info-current-line-comment-p-1 ()
4752 (python-tests-with-temp-buffer
4753 "
4754 # this is a comment
4755 foo = True # another comment
4756 '#this is a string'
4757 if foo:
4758 # more comments
4759 print ('bar') # print bar
4760 "
4761 (python-tests-look-at "# this is a comment")
4762 (should (python-info-current-line-comment-p))
4763 (python-tests-look-at "foo = True # another comment")
4764 (should (not (python-info-current-line-comment-p)))
4765 (python-tests-look-at "'#this is a string'")
4766 (should (not (python-info-current-line-comment-p)))
4767 (python-tests-look-at "# more comments")
4768 (should (python-info-current-line-comment-p))
4769 (python-tests-look-at "print ('bar') # print bar")
4770 (should (not (python-info-current-line-comment-p)))))
4771
4772 (ert-deftest python-info-current-line-empty-p ()
4773 (python-tests-with-temp-buffer
4774 "
4775 # this is a comment
4776
4777 foo = True # another comment
4778 "
4779 (should (python-info-current-line-empty-p))
4780 (python-tests-look-at "# this is a comment")
4781 (should (not (python-info-current-line-empty-p)))
4782 (forward-line 1)
4783 (should (python-info-current-line-empty-p))))
4784
4785 (ert-deftest python-info-docstring-p-1 ()
4786 "Test module docstring detection."
4787 (python-tests-with-temp-buffer
4788 "# -*- coding: utf-8 -*-
4789 #!/usr/bin/python
4790
4791 '''
4792 Module Docstring Django style.
4793 '''
4794 u'''Additional module docstring.'''
4795 '''Not a module docstring.'''
4796 "
4797 (python-tests-look-at "Module Docstring Django style.")
4798 (should (python-info-docstring-p))
4799 (python-tests-look-at "u'''Additional module docstring.'''")
4800 (should (python-info-docstring-p))
4801 (python-tests-look-at "'''Not a module docstring.'''")
4802 (should (not (python-info-docstring-p)))))
4803
4804 (ert-deftest python-info-docstring-p-2 ()
4805 "Test variable docstring detection."
4806 (python-tests-with-temp-buffer
4807 "
4808 variable = 42
4809 U'''Variable docstring.'''
4810 '''Additional variable docstring.'''
4811 '''Not a variable docstring.'''
4812 "
4813 (python-tests-look-at "Variable docstring.")
4814 (should (python-info-docstring-p))
4815 (python-tests-look-at "u'''Additional variable docstring.'''")
4816 (should (python-info-docstring-p))
4817 (python-tests-look-at "'''Not a variable docstring.'''")
4818 (should (not (python-info-docstring-p)))))
4819
4820 (ert-deftest python-info-docstring-p-3 ()
4821 "Test function docstring detection."
4822 (python-tests-with-temp-buffer
4823 "
4824 def func(a, b):
4825 r'''
4826 Function docstring.
4827
4828 onetwo style.
4829 '''
4830 R'''Additional function docstring.'''
4831 '''Not a function docstring.'''
4832 return a + b
4833 "
4834 (python-tests-look-at "Function docstring.")
4835 (should (python-info-docstring-p))
4836 (python-tests-look-at "R'''Additional function docstring.'''")
4837 (should (python-info-docstring-p))
4838 (python-tests-look-at "'''Not a function docstring.'''")
4839 (should (not (python-info-docstring-p)))))
4840
4841 (ert-deftest python-info-docstring-p-4 ()
4842 "Test class docstring detection."
4843 (python-tests-with-temp-buffer
4844 "
4845 class Class:
4846 ur'''
4847 Class docstring.
4848
4849 symmetric style.
4850 '''
4851 uR'''
4852 Additional class docstring.
4853 '''
4854 '''Not a class docstring.'''
4855 pass
4856 "
4857 (python-tests-look-at "Class docstring.")
4858 (should (python-info-docstring-p))
4859 (python-tests-look-at "uR'''") ;; Additional class docstring
4860 (should (python-info-docstring-p))
4861 (python-tests-look-at "'''Not a class docstring.'''")
4862 (should (not (python-info-docstring-p)))))
4863
4864 (ert-deftest python-info-docstring-p-5 ()
4865 "Test class attribute docstring detection."
4866 (python-tests-with-temp-buffer
4867 "
4868 class Class:
4869 attribute = 42
4870 Ur'''
4871 Class attribute docstring.
4872
4873 pep-257 style.
4874
4875 '''
4876 UR'''
4877 Additional class attribute docstring.
4878 '''
4879 '''Not a class attribute docstring.'''
4880 pass
4881 "
4882 (python-tests-look-at "Class attribute docstring.")
4883 (should (python-info-docstring-p))
4884 (python-tests-look-at "UR'''") ;; Additional class attr docstring
4885 (should (python-info-docstring-p))
4886 (python-tests-look-at "'''Not a class attribute docstring.'''")
4887 (should (not (python-info-docstring-p)))))
4888
4889 (ert-deftest python-info-docstring-p-6 ()
4890 "Test class method docstring detection."
4891 (python-tests-with-temp-buffer
4892 "
4893 class Class:
4894
4895 def __init__(self, a, b):
4896 self.a = a
4897 self.b = b
4898
4899 def __call__(self):
4900 '''Method docstring.
4901
4902 pep-257-nn style.
4903 '''
4904 '''Additional method docstring.'''
4905 '''Not a method docstring.'''
4906 return self.a + self.b
4907 "
4908 (python-tests-look-at "Method docstring.")
4909 (should (python-info-docstring-p))
4910 (python-tests-look-at "'''Additional method docstring.'''")
4911 (should (python-info-docstring-p))
4912 (python-tests-look-at "'''Not a method docstring.'''")
4913 (should (not (python-info-docstring-p)))))
4914
4915 (ert-deftest python-info-encoding-from-cookie-1 ()
4916 "Should detect it on first line."
4917 (python-tests-with-temp-buffer
4918 "# coding=latin-1
4919
4920 foo = True # another comment
4921 "
4922 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4923
4924 (ert-deftest python-info-encoding-from-cookie-2 ()
4925 "Should detect it on second line."
4926 (python-tests-with-temp-buffer
4927 "
4928 # coding=latin-1
4929
4930 foo = True # another comment
4931 "
4932 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4933
4934 (ert-deftest python-info-encoding-from-cookie-3 ()
4935 "Should not be detected on third line (and following ones)."
4936 (python-tests-with-temp-buffer
4937 "
4938
4939 # coding=latin-1
4940 foo = True # another comment
4941 "
4942 (should (not (python-info-encoding-from-cookie)))))
4943
4944 (ert-deftest python-info-encoding-from-cookie-4 ()
4945 "Should detect Emacs style."
4946 (python-tests-with-temp-buffer
4947 "# -*- coding: latin-1 -*-
4948
4949 foo = True # another comment"
4950 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4951
4952 (ert-deftest python-info-encoding-from-cookie-5 ()
4953 "Should detect Vim style."
4954 (python-tests-with-temp-buffer
4955 "# vim: set fileencoding=latin-1 :
4956
4957 foo = True # another comment"
4958 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4959
4960 (ert-deftest python-info-encoding-from-cookie-6 ()
4961 "First cookie wins."
4962 (python-tests-with-temp-buffer
4963 "# -*- coding: iso-8859-1 -*-
4964 # vim: set fileencoding=latin-1 :
4965
4966 foo = True # another comment"
4967 (should (eq (python-info-encoding-from-cookie) 'iso-8859-1))))
4968
4969 (ert-deftest python-info-encoding-from-cookie-7 ()
4970 "First cookie wins."
4971 (python-tests-with-temp-buffer
4972 "# vim: set fileencoding=latin-1 :
4973 # -*- coding: iso-8859-1 -*-
4974
4975 foo = True # another comment"
4976 (should (eq (python-info-encoding-from-cookie) 'latin-1))))
4977
4978 (ert-deftest python-info-encoding-1 ()
4979 "Should return the detected encoding from cookie."
4980 (python-tests-with-temp-buffer
4981 "# vim: set fileencoding=latin-1 :
4982
4983 foo = True # another comment"
4984 (should (eq (python-info-encoding) 'latin-1))))
4985
4986 (ert-deftest python-info-encoding-2 ()
4987 "Should default to utf-8."
4988 (python-tests-with-temp-buffer
4989 "# No encoding for you
4990
4991 foo = True # another comment"
4992 (should (eq (python-info-encoding) 'utf-8))))
4993
4994 \f
4995 ;;; Utility functions
4996
4997 (ert-deftest python-util-goto-line-1 ()
4998 (python-tests-with-temp-buffer
4999 (concat
5000 "# a comment
5001 # another comment
5002 def foo(a, b, c):
5003 pass" (make-string 20 ?\n))
5004 (python-util-goto-line 10)
5005 (should (= (line-number-at-pos) 10))
5006 (python-util-goto-line 20)
5007 (should (= (line-number-at-pos) 20))))
5008
5009 (ert-deftest python-util-clone-local-variables-1 ()
5010 (let ((buffer (generate-new-buffer
5011 "python-util-clone-local-variables-1"))
5012 (varcons
5013 '((python-fill-docstring-style . django)
5014 (python-shell-interpreter . "python")
5015 (python-shell-interpreter-args . "manage.py shell")
5016 (python-shell-prompt-regexp . "In \\[[0-9]+\\]: ")
5017 (python-shell-prompt-output-regexp . "Out\\[[0-9]+\\]: ")
5018 (python-shell-extra-pythonpaths "/home/user/pylib/")
5019 (python-shell-completion-setup-code
5020 . "from IPython.core.completerlib import module_completion")
5021 (python-shell-completion-string-code
5022 . "';'.join(get_ipython().Completer.all_completions('''%s'''))\n")
5023 (python-shell-virtualenv-root
5024 . "/home/user/.virtualenvs/project"))))
5025 (with-current-buffer buffer
5026 (kill-all-local-variables)
5027 (dolist (ccons varcons)
5028 (set (make-local-variable (car ccons)) (cdr ccons))))
5029 (python-tests-with-temp-buffer
5030 ""
5031 (python-util-clone-local-variables buffer)
5032 (dolist (ccons varcons)
5033 (should
5034 (equal (symbol-value (car ccons)) (cdr ccons)))))
5035 (kill-buffer buffer)))
5036
5037 (ert-deftest python-util-strip-string-1 ()
5038 (should (string= (python-util-strip-string "\t\r\n str") "str"))
5039 (should (string= (python-util-strip-string "str \n\r") "str"))
5040 (should (string= (python-util-strip-string "\t\r\n str \n\r ") "str"))
5041 (should
5042 (string= (python-util-strip-string "\n str \nin \tg \n\r") "str \nin \tg"))
5043 (should (string= (python-util-strip-string "\n \t \n\r ") ""))
5044 (should (string= (python-util-strip-string "") "")))
5045
5046 (ert-deftest python-util-forward-comment-1 ()
5047 (python-tests-with-temp-buffer
5048 (concat
5049 "# a comment
5050 # another comment
5051 # bad indented comment
5052 # more comments" (make-string 9999 ?\n))
5053 (python-util-forward-comment 1)
5054 (should (= (point) (point-max)))
5055 (python-util-forward-comment -1)
5056 (should (= (point) (point-min)))))
5057
5058 (ert-deftest python-util-valid-regexp-p-1 ()
5059 (should (python-util-valid-regexp-p ""))
5060 (should (python-util-valid-regexp-p python-shell-prompt-regexp))
5061 (should (not (python-util-valid-regexp-p "\\("))))
5062
5063 \f
5064 ;;; Electricity
5065
5066 (ert-deftest python-parens-electric-indent-1 ()
5067 (let ((eim electric-indent-mode))
5068 (unwind-protect
5069 (progn
5070 (python-tests-with-temp-buffer
5071 "
5072 from django.conf.urls import patterns, include, url
5073
5074 from django.contrib import admin
5075
5076 from myapp import views
5077
5078
5079 urlpatterns = patterns('',
5080 url(r'^$', views.index
5081 )
5082 "
5083 (electric-indent-mode 1)
5084 (python-tests-look-at "views.index")
5085 (end-of-line)
5086
5087 ;; Inserting commas within the same line should leave
5088 ;; indentation unchanged.
5089 (python-tests-self-insert ",")
5090 (should (= (current-indentation) 4))
5091
5092 ;; As well as any other input happening within the same
5093 ;; set of parens.
5094 (python-tests-self-insert " name='index')")
5095 (should (= (current-indentation) 4))
5096
5097 ;; But a comma outside it, should trigger indentation.
5098 (python-tests-self-insert ",")
5099 (should (= (current-indentation) 23))
5100
5101 ;; Newline indents to the first argument column
5102 (python-tests-self-insert "\n")
5103 (should (= (current-indentation) 23))
5104
5105 ;; All this input must not change indentation
5106 (indent-line-to 4)
5107 (python-tests-self-insert "url(r'^/login$', views.login)")
5108 (should (= (current-indentation) 4))
5109
5110 ;; But this comma does
5111 (python-tests-self-insert ",")
5112 (should (= (current-indentation) 23))))
5113 (or eim (electric-indent-mode -1)))))
5114
5115 (ert-deftest python-triple-quote-pairing ()
5116 (let ((epm electric-pair-mode))
5117 (unwind-protect
5118 (progn
5119 (python-tests-with-temp-buffer
5120 "\"\"\n"
5121 (or epm (electric-pair-mode 1))
5122 (goto-char (1- (point-max)))
5123 (python-tests-self-insert ?\")
5124 (should (string= (buffer-string)
5125 "\"\"\"\"\"\"\n"))
5126 (should (= (point) 4)))
5127 (python-tests-with-temp-buffer
5128 "\n"
5129 (python-tests-self-insert (list ?\" ?\" ?\"))
5130 (should (string= (buffer-string)
5131 "\"\"\"\"\"\"\n"))
5132 (should (= (point) 4)))
5133 (python-tests-with-temp-buffer
5134 "\"\n\"\"\n"
5135 (goto-char (1- (point-max)))
5136 (python-tests-self-insert ?\")
5137 (should (= (point) (1- (point-max))))
5138 (should (string= (buffer-string)
5139 "\"\n\"\"\"\n"))))
5140 (or epm (electric-pair-mode -1)))))
5141
5142 \f
5143 ;;; Hideshow support
5144
5145 (ert-deftest python-hideshow-hide-levels-1 ()
5146 "Should hide all methods when called after class start."
5147 (let ((enabled hs-minor-mode))
5148 (unwind-protect
5149 (progn
5150 (python-tests-with-temp-buffer
5151 "
5152 class SomeClass:
5153
5154 def __init__(self, arg, kwarg=1):
5155 self.arg = arg
5156 self.kwarg = kwarg
5157
5158 def filter(self, nums):
5159 def fn(item):
5160 return item in [self.arg, self.kwarg]
5161 return filter(fn, nums)
5162
5163 def __str__(self):
5164 return '%s-%s' % (self.arg, self.kwarg)
5165 "
5166 (hs-minor-mode 1)
5167 (python-tests-look-at "class SomeClass:")
5168 (forward-line)
5169 (hs-hide-level 1)
5170 (should
5171 (string=
5172 (python-tests-visible-string)
5173 "
5174 class SomeClass:
5175
5176 def __init__(self, arg, kwarg=1):
5177 def filter(self, nums):
5178 def __str__(self):"))))
5179 (or enabled (hs-minor-mode -1)))))
5180
5181 (ert-deftest python-hideshow-hide-levels-2 ()
5182 "Should hide nested methods and parens at end of defun."
5183 (let ((enabled hs-minor-mode))
5184 (unwind-protect
5185 (progn
5186 (python-tests-with-temp-buffer
5187 "
5188 class SomeClass:
5189
5190 def __init__(self, arg, kwarg=1):
5191 self.arg = arg
5192 self.kwarg = kwarg
5193
5194 def filter(self, nums):
5195 def fn(item):
5196 return item in [self.arg, self.kwarg]
5197 return filter(fn, nums)
5198
5199 def __str__(self):
5200 return '%s-%s' % (self.arg, self.kwarg)
5201 "
5202 (hs-minor-mode 1)
5203 (python-tests-look-at "def fn(item):")
5204 (hs-hide-block)
5205 (should
5206 (string=
5207 (python-tests-visible-string)
5208 "
5209 class SomeClass:
5210
5211 def __init__(self, arg, kwarg=1):
5212 self.arg = arg
5213 self.kwarg = kwarg
5214
5215 def filter(self, nums):
5216 def fn(item):
5217 return filter(fn, nums)
5218
5219 def __str__(self):
5220 return '%s-%s' % (self.arg, self.kwarg)
5221 "))))
5222 (or enabled (hs-minor-mode -1)))))
5223
5224
5225
5226 (provide 'python-tests)
5227
5228 ;; Local Variables:
5229 ;; indent-tabs-mode: nil
5230 ;; End:
5231
5232 ;;; python-tests.el ends here