(defun get-message-last-line ()
  "Return message buffer last line"
  (with-current-buffer (messages-buffer)
    (goto-char (point-max))
    (forward-line -1)
    (buffer-substring (line-beginning-position) (line-end-position))))

(ert-deftest elpy-profile-buffer-or-region-test-succeed ()
  (elpy-testcase ((:project project-root "test.py"))
    (find-file (f-join project-root "test.py"))
    (elpy-enable)
    (python-mode)
    (insert "a = 0\nfor i in range(10000):\n    a += (i**2 + 1)**.5")
    (let ((prof-file (elpy-profile-buffer-or-region nil t)))
      (while (string= (get-message-last-line) "[test.py] Profiling ...")
        (sleep-for 0 100))
      (should (file-exists-p prof-file))
      (should (not (file-exists-p "test.profile")))
      (should (string= (get-message-last-line) "[test.py] Profiling succeeded")))))

(ert-deftest elpy-profile-buffer-or-region-test-fail ()
  (elpy-testcase ((:project project-root "test.py"))
    (find-file (f-join project-root "test.py"))
    (elpy-enable)
    (python-mode)
    (insert "a = 0\nfor i in range(10000):\n    a += i**2 + 1)**.5")
    (let ((prof-file (elpy-profile-buffer-or-region nil t)))
      (while (string= (get-message-last-line) "[test.py] Profiling ...")
        (sleep-for 0 100))
      (should (not (file-exists-p prof-file)))
      (should (not (file-exists-p "test.profile")))
      (should (string= (get-message-last-line) "[test.py] Profiling failed")))))

(ert-deftest elpy-profile-buffer-or-region-test-indir-succeed ()
  (elpy-testcase ((:project project-root "test.py"))
    (find-file (f-join project-root "test.py"))
    (elpy-enable)
    (python-mode)
    (insert "a = 0\nfor i in range(10000):\n    a += (i**2 + 1)**.5")
    (let ((prof-file (elpy-profile-buffer-or-region t t)))
      (while (string= (get-message-last-line) "[test.py] Profiling ...")
        (sleep-for 0 100))
      (should (file-exists-p prof-file))
      (should (file-exists-p "test.profile"))
      (should (string= (get-message-last-line) "[test.py] Profiling succeeded")))))

(ert-deftest elpy-profile-buffer-or-region-test-indir-failed ()
  (elpy-testcase ((:project project-root "test.py"))
    (find-file (f-join project-root "test.py"))
    (elpy-enable)
    (python-mode)
    (insert "a = 0\nfor i in range(10000):\n    a += i**2 + 1)**.5")
    (let ((prof-file (elpy-profile-buffer-or-region t t)))
      (while (string= (get-message-last-line) "[test.py] Profiling ...")
        (sleep-for 0 100))
      (should (not (file-exists-p prof-file)))
      (should (not (file-exists-p "test.profile")))
      (should (string= (get-message-last-line) "[test.py] Profiling failed")))))
