Coder Social home page Coder Social logo

emacs-python-pytest's Introduction

python-pytest.el

melpa badge

melpa stable badge

overview

python-pytest.el is an emacs package to integrate the python pytest test runner.

most functionality can be used via a dispatcher popup menu built using transient, which gives a look and feel similar to the fantastic magit package.

features

python-pytest.el offers these awesome features:

  • various commands with ‘do what i mean’ (dwim) behaviour, using heuristics to automatically detect test files and test functions:
    • run all tests
    • rerun previous failures
    • repeat the last invocation
    • run only tests for the current python (test) module
    • run only tests for the current (test) function
  • easy way to change common switches and options, e.g. toggling output capture, failing after the first error, and so on.
  • edit the automatically generated command line before executing, by invoking commands with a prefix argument (C-u).
  • basic debugger integration using the pdb tracking support from the built-in python-mode package, which will automatically open source files at the right location.
  • work simultaneously on multiple python projects. each project will use its own dedicated pytest output buffer.
  • various customisation options, e.g. to change whether a generated command line should be shown for editing by default.
  • hooks that get run before and after running pytest, which can be used to add custom behaviour.

screenshot

Output
 -c color (--color)
 -q quiet (--quiet)
 -s no output capture (--capture=no)
 -v verbosity ([--verbose|--verbose --verbose])

Selection, filtering, ordering
 -k only names matching expression (-k=)      --dm run doctests (--doctest-modules)
 -m only marks matching expression (-m=)      --nf new first (--new-first)
                                              --sw stepwise (--stepwise)

Failures, errors, debugging
 -l show locals (--showlocals)                --ff failed first (--failed-first)
 -p debug on error (--pdb)                    --ft full tracebacks (--full-trace)
 -x exit after first failure (--exitfirst)    --mf exit after N failures or errors (--maxfail=10)
                                              --rx run xfail tests (--runxfail)
                                              --tb traceback style (--tb=)
                                              --tr debug on each test (--trace)

Run tests
 t all    r repeat         f file (dwim)    m files          d def/class (dwim)
          x last failed    F file (this)    M directories    D def/class (this)

installation

python-pytest.el is available from melpa.

with use-package:

(use-package python-pytest)

install manually:

M-x package-install RET python-pytest RET

note that python-pytest.el uses projectile for some of its features, e.g. finding associated test files. this package is intended to work correctly even without any projectile configuration, since it will likely do the right thing if a project has a conventional layout.

usage

basics

the typical usage pattern is to invoke the popup menu, named python-pytest-dispatch. it is a good idea to create a dedicated keybinding for this command, but it can also be run manually:

M-x python-pytest-dispatch

this shows a dispatcher menu. change some switches and options, then run one of the actions.

a dedicated pytest comint buffer will open, showing the output in real time, and allowing interaction with debuggers.

using the correct environment

this package ultimately invokes pytest. python-pytest.el does not guess execution environments, so emacs needs to use the right exec-path, taking into account python virtual environments, and so on.

to manage the execution environment, consider using direnv: it can change (and revert) paths and environment variables, simply by switching to a project directory, making it perfect for automatically ‘activating’ a virtualenv. use emacs-direnv and possibly exec-path-from-shell to achieve the same inside emacs.

working in a monorepo

by default, pytest is run from the project root directory. if your package is not at the root of your repository, pytest might not find your modules.

a workaround is to add the the package root to PYTHONPATH before running the tests. this can be found by adding a dummy file in the package root. the following hook looks for a .pyroot file in parent directories. if found, it adds the directory of the file to PYTHONPATH.

(add-hook 'python-mode-hook
          (lambda ()
            (when-let ((r (locate-dominating-file default-directory ".pyroot")))
              (setq python-pytest-executable
                    (concat "PYTHONPATH=" r " " "pytest")))))

editing and repeating

to edit the command line before running it, use a prefix argument before calling the action, e.g.type C-u t instead of just t in the popup menu.

when the popup menu itself is invoked with a prefix argument, this will run python-pytest-repeat to rerun pytest. this means a single key binding can be used for both an initial run (via the popup), and for repeated calls. this is great for quick ‘edit, test, edit, test` cycles.

available commands

the available commands are:

  • python-pytest
  • python-pytest-file
  • python-pytest-file-dwim
  • python-pytest-files
  • python-pytest-function
  • python-pytest-function-dwim
  • python-pytest-last-failed
  • python-pytest-repeat

all of these are available via the popup menu, but can also be executed directly (or bound to a key).

heuristics

this package uses a few heuristics for its ‘do what i mean’ behaviour.

test file heuristics

the python-pytest-file-dwim command tries to do the right thing both when editing the actual code and its associated test module. for instance, when editing foo/bar.py, this will automatically detect tests/test_bar.py (thanks to the projectile package), and only run the tests from that test module.

test function heuristics

the python-pytest-function-dwim command tries to run only tests related to the function close to the cursor position (‘point’ in emacs terminology).

when editing a test module, this runs only a single test function, namely the one currently being edited.

when editing the code itself, things are more complicated. this command will make a guess to only run the right test functions. the matching behaviour can be tweaked using python-pytest-strict-test-name-matching (see configuration below).

by default, the current function name will be used as a pattern to match the corresponding tests. for example, when editing foo() inside utils.py, this will match test_foo() as well as test_foo_xyz(), by invoking pytest test_utils.py -k test_foo. if a pattern was specified in the popup (the -k option), it will try to make a combined pattern, by invoking pytest test_utils.py -k 'test_foo and other_filter'.

on the other hand, when python-pytest-strict-test-name-matching is non-nil, only test_foo() will match, and nothing else, by invoking pytest test_utils.py::test_foo.

configuration

settings

the behaviour of this package can be tweaked by customising a few defcustom variables. use the customize interface to explore those (each will show a description and possible values):

M-x customize-group RET python-pytest RET

to set those permanently without using the customize interface, use something like this in init.el:

(use-package python-pytest
 :custom
 (python-pytest-confirm t))

the available variables are:

  • python-pytest-confirm

    whether to ask for confirmation (allowing editing) by default. this inverts the prefix argument (C-u) behaviour.

  • python-pytest-strict-test-name-matching

    Whether to require a strict match for the ‘test this function’ heuristic.

  • python-pytest-executable

    the name of the pytest executable (pytest by default)

  • python-pytest-unsaved-buffers-behavior

    whether to ask whether unsaved buffers should be saved before running pytest. the check for unsaved buffers can be for only the current buffer, or for all project buffers, and those can be saved directly, or after confirmation. valid values: ask-all, ask-current, save-all, save-current, or nil.

  • python-pytest-setup-hook, python-pytest-started-hook, and python-pytest-finished-hook

    hooks run before starting pytest, after starting pytest, and after pytest finished.

  • python-pytest-buffer-name and python-pytest-project-name-in-buffer-name

    the defaults result in *pytest*<project-name>.

  • python-pytest-pdb-track

    whether to enable the pdb tracking support

extending the popup

when using pytest plugins that provide extra switches, it may be useful to integrate those into the popup. see the transient manual for more information.

as an example, this will add a -z switch that, when enabled, will invoke pytest --zzz:

(use-package python-pytest
 :config
 ;; just an extra `-y' after the `-x' suffix
 (transient-append-suffix
   'python-pytest-dispatch
   "-x"
   '("-y" "The Y" "-y"))
 ;; group with `-z' after second from the last group,
 ;; that is before `Run tests'
 (transient-append-suffix
   'python-pytest-dispatch
   '(-2)
   ["My Z"
    ("-z" "The Z" "-z")]))

transient lets you save defaults you want for it. just select all options on python-pytest-dispatch and then

  • C-x C-s to save current settings as default and make them persistent,
  • C-x s to save current settings as default for the current emacs session.

contributing

praise? complaints? bugs? questions? ideas?

please use the github issue tracker.

credits

this package was created by wouter bolsterlee. i am @wbolster on github and twitter.

history

note: melpa automatically ships the latest code from the git main branch, while melpa stable only contains tagged (released) versions.

development branch

  • use completing-read-multiple for multiple files selection (#72)

3.4.0 (2024-03-14)

  • add windows support (#68)
  • add -W argument to ignore warnings (#70)
  • add --collect-only option (#65)

3.3.0 (2022-10-18)

  • add dispatch options for pytest-xdist (#54)
  • respect projectile-compilation-dir if it exists (#59)
  • Use read-shell-command instead of read-from-minibuffer (#60)
  • add 0 as a valid argument that can be passed to -n (#61)
  • switch to compilation-mode after pytest process finishes (#62)
  • fix saving of verbosity setting (#64)

3.2.0 (2021-11-11)

  • do not use melpa unstable versions in package-requires (#52)

3.1.0 (2021-11-09)

  • make python-pytest-files show all files if no test files are found (#38)
  • display buffer window before starting comint to fix size detection (#48)
  • correctly handle -m and -k flags (#37)
  • fix clearing test output buffer (#15)

3.0.0 (2020-08-10)

  • redesign the menu: use better groupings, use multi-column visual layout, add some more flags, make all flags start with either - or -- (mostly mimicking pytest flags) (#28)
  • add a python-pytest-directories command with interactive multi-directory selection (#21, #31)

2.0.0 (2020-08-04)

  • switch to transient (magit-popup replacement); the command for the menu is now python-pytest-dispatch (#18, #26)
  • add python-pytest-files command with interactive multi-file selection
  • improve python-pytest-file-dwim heuristic for nested functions/classes
  • make next-error and related-commands work
  • add a -w shortcut for very verbose (--verbose --verbose) (#24)

1.0.0 (2018-06-14)

  • this package is useful for quite a few people. time to celebrate with a 1.x release!
  • save (or ask to save) modified buffers before running pytest (#4)
  • put customizable variables in the right group

0.3.1 (2018–03-07)

  • fix package version number for melpa stable

0.3.0 (2018–03-07)

  • repopulate the popup with the previously used values when running python-pytest-dispatch from an output buffer. (#3)

0.2.2 (2018-02-26)

  • avoid -as-> macro since the dash.el version currently on melpa stable does not have it. (#2)

0.2.1 (2018-02-22)

  • fix autoloading for python-pytest-popup command

0.2.0 (2018-02-19)

  • now available from melpa (#1)
  • more docs
  • various ‘dwim’ improvements
  • renamed and added a few popup flags
  • improved relative path handling
  • improved hooks
  • improved history
  • better shell escaping
  • remember current command in output buffer to make repeating work
  • misc other tweaks and fixes

0.1.0 (2018-02-03)

  • initial release

license

(this is the osi approved 3-clause "new bsd license".)

copyright 2018 wouter bolsterlee

all rights reserved.

redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  • redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  • neither the name of the author nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission.

this software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. in no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.

emacs-python-pytest's People

Contributors

basil-conto avatar cipherself avatar cvdub avatar fredrikmeyer avatar gamboz avatar jeff-phil avatar juergenhoetzel avatar m-novikov avatar pkryger avatar r-zip avatar randomneo avatar rassie avatar spookylukey avatar tarsius avatar wbolster avatar zyxir avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

emacs-python-pytest's Issues

Make test failures clickable with

thanks for working on this package - I enjoy using it. One thing I noticed is the lack of support to go from $FILE_NAME:$LINE_NUMBER for every error to opening it in the other window. Example output below

test_my_appy.py .FF                                                      [100%]

=================================== FAILURES ===================================
________________________________ test_will_fail ________________________________

    def test_will_fail():
>       assert False
E       assert False

test_my_appy.py:9: AssertionError
_____________________________ test_will_fail_hard ______________________________

    def test_will_fail_hard():
    
        x = 12 + 7
        print("Hello")
    
>       assert x == 20
E       assert 19 == 20

test_my_appy.py:17: AssertionError

rustic-mode implements that by defining own regexes to match warnings and errors in the compilation-mode output.
https://github.com/brotzeit/rustic/blob/master/rustic-compile.el#L116-L181

Doing that would also allow disabling the colour (sic!) pytest cmdline arg with emacs font-locks instead of ANSI, which might break over tramp. [Aside I sometimes experience projectile-related problems with pytest over tramp]

Was wondering if you would be open to me contributing a definition of the compilation mode?

I was thinking about the following as a first pass:
python-pytest-error to match test_my_appy.py:9 and test_my_appy.py:17 and allow users to hit Enter and open the buffer with that file on line 9 or 17 respectively.

Broken with Emacs 28.x

Emacs 28.x updates the signature of define-obsolete-function-alias to make a previously optional parameter required (emacs-mirror/emacs@32c6732). Since emacs-python-pytest uses the old syntax, it's broken with Emacs 28.x.

Extending the popup section of the readme

Hi, firstly thanks for a really useful package!

I am struggling to understand how to add new pytest flags to my init.el since the switch to transient, I tried copying the example in the readme, namely:

  (use-package python-pytest
    :config
    ;; just an extra `-y' after the `-x' suffix
    (transient-append-suffix
      'python-pytest-dispatch
      "-x"
      ("-y" "The Y" "-y"))
    ;; group with `-z' after second from the last group,
    ;; that is before `Run tests'
    (transient-append-suffix
      'python-pytest-dispatch
      '(-2)
      ["My Z"
       ("-z" "The Z" "-z")]))

but this errors with:

Error (use-package): python-pytest/:config: Invalid function: "-y"

if you have a spare minute I think it would be great to clarify how the extra switches work.

Please let me know if there is anything I can do to help - although my elisp is awful.

Thanks

Projectile test file filtering

The documentation surrounding the use of projectile to filter test files could be improved. My test directory wasn't recognized by projectile and therefore the projectile-test-files function used in python-pytest--select-test-files was filtering out everything and I just got "No test files found" messages without further explanation.

Possibly have a configuration variable that allows turning off the projectile-test-files filtering, or just add a blurb about ensuring projectile's test-dir is properly set in the docs or the error message.

Make python-pytest work on Microsoft Windows

Currently comint is called with sh as the shell command, which is not available on Windows. This could be changed to cmd if Windows is detected as the current OS:

(let ((shell-command "sh")
     (shell-command-switch "-c"))
  (when (eq system-type 'windows-nt)
    (setq shell-command "cmd")
    (setq shell-command-switch "/c"))
  (make-comint-in-buffer "pytest" buffer shell-command nil shell-command-switch command))

Add mode CLI args

Hi! I would like to add the -s switch in order to capture stdout/stderr. How can I do that with your package?

Thanks in advance.

Text is read-only

I run python-pytest-popup, press t for Test all, and it runs. Then I try to do it again, perhaps after changing some code, and I get Text is read-only in the minibuffer, and the tests won't run unless I kill the pytest buffer and re-run python-pytest-popup.

Could you help me understand what I'm doing wrong?

emacs-python-pytest 0.3.1
GNU Emacs 25.2.2 (x86_64-pc-linux-gnu, GTK+ Version 3.22.21) of 2017-09-22, modified by Debian
Ubuntu 17.10
python 3.6.3
pytest 3.5.0

Don't require a project root

Feature request: allow testing of any file or directory. If I'm not in a project tree, just use the directory for the current file.

Customise window size and fit content to it

It would be really great if one were able to define the size of the window created to display the pytest buffer. Often half of the screen is more than enough when running a test, and in my case I'd like to limit the width of the created buffer to some maximum size.

Similarly, the content inside the buffer is formatted to match the size of the fully maximised window size. This means when the tests are running, they run off the window and out of view. Similarly, the progress percentages are never in view because of this. It would be preferable if the shell running pytest was initially aware of the size of the window it's filling, so that the content can be printed accordingly, similarly to how it works in an actual terminal session.

Thanks!

Use `completing-read-multiple` for multiple files selection

I would prefer if the package used completing-read-multiple in python-pytest--select-test-files rather than just completing-read in a while loop with an extra candidate to finish completion. In python-pytest--select-test-files, the final part of the function body could be simplified to (completing-read-multiple "Choose test files: " candidates). The user can then just use normal interactive completion to select a file and if they want to select multiple files, they just enter a comma or whatever their value of crm-separator is. The advantage is that it requires less user inputs if the user just wants to select a single file or diretory and you don't need to rely on the user finding the special "finish completion" candidate.

Rerun last, but allow changing options

This package supports the following usecases:

  • rerun the last run immediately, exactly as is
  • start configuring a new run from scratch

Now, a common pattern is to request "run the last invocation, but with the verbose flag turned on". It would be nice if this package supported that. The easiest way I think would be to show the pytest menu with all the previous run's flags enabled.

Common shortcuts in run buffer

Hi Wouter,

Really nice package!

It would be nice to have some common keyboard bindings in the test buffer. The mains ones I'm missing are:

  • q burry buffer
  • g refresh buffer, I'd expect the current test invocation to be re-run.

If you're not against this for some reason I could even try and see if i can learn some elisp myself to add this in a PR, it doesn't sound like it should be overly complicated but who knows.

fix linter warnings about python-pytest-arguments variable

as a result of #18, there are now a few warnings about a variable that no longer exists:

 python-…   320  23 warning         reference to free variable ‘python-pytest-arguments’ (emacs-lisp)
 python-…   389  13 warning         assignment to free variable ‘python-pytest-arguments’ (emacs-lisp)

Dismissable, read-only results

Currently the results buffer is derived from comint-mode to facilitate using the debugger. This makes the buffer less user friendly in normal use.

In the current workflow running a test opens a new editable results window, which (for me at least) is out of focus. To close it I need to switch focus C-x o and then hide that window C-x 0.

An improved situation would be if the results window took focus, much like a compilation buffer and was read-only (special-mode maybe?). This could then easily be dismissed by pressing q.

To make this work the buffer would have to toggle read-only states when writing test results and disable it when a debugger is in-use.

Update from `magit-popup` to `transient`

Just wondering what you think of this. magit now uses transient instead of magit-popup. The migration is fairly prosaic. There are backward compatibility problems of course, but magit has gone for it.

DWIM commands aren't working

Hey! Thanks for creating this awesome package.

I'm having a weird issue that's not a huge deal, but none of the DWIM commands are working for me, but the non-DWIM ones are.

The outout of any DWIM command is No test file found

Any idea what could be causing this?

Also, as an unrelated question, is there any way to control which buffer pytest will send its output to?

Thanks in advance!

Double verbosity setting saving broken

I'm finding that I can't permanently save the -vv (double verbosity) via C-x C-s. All the other settings I've used (such as -x and --ff save fine, but when I close and open emacs, the verbosity setting always reverts to -v.

Further details:

  • Running Doom Emacs on OSX.
  • Occurs regardless of the test mode (all, file, repeat)
  • Double verbosity persists during repetitions, but not after that.

python -m pytest functionality

I want to add the current directory to sys.path which happens to be the case when i run 'python -m pytest'. How to achieve the same functionality with emacs-python-pytest ?

Dependency transient-20200719 not in MELPA

I tried to install python-pytest today and MELPA will not let me install it because it depends on transient-20200719 rather than transient-0.3.7 and the former is not present in MELPA. I am not sure how to install transient-20200719 except from its own git repo perhaps.

Any advice would be welcome.

running tests from popup does not work with venv from poetry-tracking-mode

I use poetry for dependency management.
poetry-mode has poetry-tracking-mode that automatically activates the poetry created venv which is located in ~/.cache/pypoetrey/virtualenvs/...

running the test directly with M-x python-pytest-file works as expected.
Going through the popup and then F to run the tests on a file fails with /usr/bin/sh: 1: pytest: not found
I have pytest only installed as a dev dependency through poetry.

I am fairly new to pytest and emacs so please let me know how I can provide more relevant logs or details.

ipdb break points not supported

Even when running the tests with -s, there's no way to debug anything since the terminal used throws a lot of random symbols at the user: "?1l�[6n�[?2004h�[?25l�[0m�[?7l�" and the likes. It's similar with trying to run pytest in M-x shell.

Suggested fix: use M-x term or ansi-term since there's no problem there.

incorrect handling of -m and -k flags

the -k and -m flags are broken, and result in pytest invocations like this:

pytest --color=yes --verbose -k '=foo'

... which results in an error, e.g.:

ERROR: Wrong expression passed to '-k': =foo: at column 1: unexpected character "="

make next-error work

some next-error integration would be nice, since pytest produces file names and line numbers.

Pytest Exe Not Found Using envrc and direnv

I see in your readme that you recommend the direnv.el to help with my type of setup, but I have had very good luck with the envrc.el plugin (which is tightly integrated with Doom Emacs) and would prefer not to switch if possible. However I understand if my configuration simply isn't supported and appreciate your contributions to the Emacs and Python communities.


I am using lorri with direnv to setup my dev environment. I also use the latest stable Doom Emacs distro.

Here are the contents of my shell.nix file:

{ pkgs ? import <nixpkgs> {} }:

pkgs.mkShell {
  buildInputs = [
    pkgs.hello
    pkgs.python3
    pkgs.poetry
    pkgs.pyright
    pkgs.python39Packages.pytest
    pkgs.python39Packages.pytestrunner

    # keep this line if you use bash
    pkgs.bashInteractive
  ];
}

Here are the contents of my .envrc file:

eval "$(lorri direnv)"

What I would like to do is execute the python-pytest-file command from a buffer called matrix.py that is in the same directory as a file called matrix_test.py. Instead I get the following error:

cwd: /home/tom/exercism/
cmd: pytest --color=yes python/matrix/matrix.py

/usr/bin/sh: 1: pytest: not found

This path error is surprising to me because I can access the pytest executable from other Python dev plugins in Emacs. My understanding was that the envrc.el managed this.

For example, when I'm viewing my Python buffer and I open a new Emacs vterm buffer I can do the following:

direnv: loading ~/exercism/python/.envrc
direnv: export +AR +AS +CC +CONFIG_SHELL +CXX +DETERMINISTIC_BUILD +HOST_PATH +IN_LORRI_SHELL +IN_NIX_SHELL +LD +NIX_BINTOOLS +NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu +NIX_BUILD_CORES +NIX_BUILD_TOP +NIX_CC +NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu +NIX_CFLAGS_COMPILE +NIX_ENFORCE_NO_NATIVE +NIX_HARDENING_ENABLE +NIX_INDENT_MAKE +NIX_LDFLAGS +NIX_LOG_FD +NIX_STORE +NM +OBJCOPY +OBJDUMP +PYTHONHASHSEED +PYTHONNOUSERSITE +PYTHONPATH +RANLIB +READELF +SIZE +SOURCE_DATE_EPOCH +STRINGS +STRIP +_PYTHON_HOST_PLATFORM +_PYTHON_SYSCONFIGDATA_NAME +allowSubstitutes +buildInputs +builder +configureFlags +depsBuildBuild +depsBuildBuildPropagated +depsBuildTarget +depsBuildTargetPropagated +depsHostHost +depsHostHostPropagated +depsTargetTarget +depsTargetTargetPropagated +doCheck +doInstallCheck +extraClosure +name +nativeBuildInputs +nobuildPhase +origArgs +origBuilder +origExtraClosure +origOutputs +origPATH +origSystem +out +outputs +patches +phases +preHook +preferLocalBuild +propagatedBuildInputs +propagatedNativeBuildInputs +shell +shellHook +stdenv +strictDeps +system ~PATH ~XDG_DATA_DIRS
tom@janet:~/exercism/python/matrix$ which pytest
/nix/store/ss47q6p4kczpmzshgr56wd9bqmg08ibm-python3.9-pytest-6.2.5/bin/pytest

When viewing my Python buffer I can also run the pytest command from the M-! prompt.

I've also tried "refresing" my direnv environment by executing the envrc-reload and lsp-restart-workspace commands multiple times.

Prompt to save unsaved file

If my current python file is unsaved, I'd like to be prompted to save it before continuing with the tests. Otherwise, I get a false passed after I change something and forget to save.

Adding custom plugins support easily

Hello there,
I am using your package more and more, and keep liking it. In my python projects I usually defines some custom command lines arguments for pytest, and found a nice way to add them dynamically to the transient menu.

I rely on .dir-locals.el for projects variables, to store custom transients menu and load them accordingly:

(defvar pytest-local-transient '((:info "No local options")) "Local options for creating local prefixes." )

;; Custom Group specification 
;; https://www.gnu.org/software/emacs/manual/html_mono/transient.html#Group-Specifications
(transient-append-suffix 'python-pytest-dispatch '(-2)
 ["Local Options" 
  :setup-children (lambda (_) 
     (list (transient-parse-suffix transient--suffixes pytest-local-transient)))
]))

And then define custom transient suffix in a .dir-locals.el file:

;; $MY_PYTHON_PROJECT/.dir-locals.el
((python-mode (pytest-local-transient .
                ((
                    "b" "Backend to run" "--backend="
                    :multi-value repeat
                    :choices ("cpu" "gpu")
                )))
))

Let me know if you would like to have this as a PR, but as it is fairly minimal coda I think it will still be happy if it stayed comfy in my config.

run in pipenv created venv

apologies I'm missing something (I'm quite new to python), but I cannot figure out how to run this in a pipenv environment. I have done pyenv-workon and selected an environment

I set the pythong pytest executable to "pipenv run py.test"
(I also tried pointing it to the venv)

From the command line

web on  pytest-in-ci [⇡$!] via 🐍 system took 4s
➜ pipenv run py.test --color=no 'server/dad/tests/test_graphql_auth.py::TestGraphQL::test_device_params'
======================================================================================== test session starts ========================================================================================
platform darwin -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0
Django settings: dad.settings (from environment variable)
rootdir: /Users/ahonnecke/Code/repos/web/server, inifile: pytest.ini
plugins: env-0.6.2, django-3.1.2
collected 1 item

server/dad/tests/test_graphql_auth.py .                                                                                                                                                       [100%]

===================================================================================== 1 passed in 1.19 seconds ======================================================================================

web on  pytest-in-ci [⇡$] via 🐍 system took 4s

From the popup:

cwd: /Users/ahonnecke/Code/repos/web/
cmd: pipenv run py.test --color=no 'server/dad/tests/test_graphql_auth.py::TestGraphQL::test_device_params'

Courtesy Notice: Pipenv found itself running within a virtual environment, so it will automatically use that environment, instead of creating its own for any project.
====================================== test session starts =======================================
platform darwin -- Python 3.6.5, pytest-3.5.1, py-1.5.3, pluggy-0.6.0
rootdir: /Users/ahonnecke/Code/repos/web/server, inifile: pytest.ini
collecting 0 items / 1 errors                                                                    
============================================= ERRORS =============================================
________________________ ERROR collecting dad/tests/test_graphql_auth.py _________________________
ImportError while importing test module '/Users/ahonnecke/Code/repos/web/server/dad/tests/test_graphql_auth.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
server/dad/tests/test_graphql_auth.py:6: in <module>
    from dad.schema import schema
server/dad/schema.py:4: in <module>
    from django.utils import timezone
E   ModuleNotFoundError: No module named 'django'
==================================== 1 error in 0.06 seconds =====================================
ERROR: not found: /Users/ahonnecke/Code/repos/web/server/dad/tests/test_graphql_auth.py::TestGraphQL::test_device_params
(no name '/Users/ahonnecke/Code/repos/web/server/dad/tests/test_graphql_auth.py::TestGraphQL::test_device_params' in any of [<Module 'dad/tests/test_graphql_auth.py'>])
¯

I have django installed in the pipenv shell, but not locally

Set commonly used pytest flags as the default

Currently I add --pdb to the executable path so I don't have to select it every time that I run a test, but it seems rather hacky. I think that it would be nice to have a set of default flags that populate as selected in the dispatch popup (that way on the rare occasion that I don't want --pdb set I can turn it off without changing the executable).

Set working directory

Thanks for a great package!

My situation is this. We have a monorepo at work with several Python projects in it. When I run python-pytest-file, it chooses the repo root as the working directory, from where it can't find the module being tested.

In my case the directory I want to run pytest from is somewhere in the middle between the root and the test file.

Is it possible to somehow set the working directory?

And if not, it's a feature request :)

Fix MELPA Stable build

The current build of emacs-python-pytest on MELPA Stable depends on dash version 2.12.0.

Unfortunately, that version of dash lacks the -as-> macro, which was introduced in commit a3b40f8f. No released version of dash includes this macro, though an issue exists requesting a new release.

Please update the dependencies once a new version of dash is released (or rewrite the stable functionality so it doesn't depend on unreleased features, but this is obviously less desirable for several reasons).

PDB autocompletion

It would be nice to have dot-completion on locals, for example. Maybe some integration with realgud?

Respect `projectile-compilation-dir` for working directory.

The projectile-test-project command and other commands set default-directory to (projectile-compilation-dir) - see https://github.com/bbatsov/projectile/blob/2c948f3a8ed378ae5fd800d2c66aece06ba058b8/projectile.el#L4705

It would be helpful if emacs-python-pytest did the same. It means that you can customize the cwd for a test run using your .dir-locals.el file e.g.:

 (python-mode .
              ((projectile-project-compilation-dir . "my_sub_project_dir")))

This seems like a much nicer workaround for the case of monorepos than the one mentioned in the readme. For example, this method means that if we have multiple different pytest.ini or conftest.py in different sub-projects, they can be picked up correctly. Running with cwd as the root directory is not going to work for many monorepo setups.

Implementation seems to be as simple as changing the definition of python-pytest---project-root:

(defun python-pytest--project-root ()
  "Find the project root directory."
  (let ((projectile-require-project-root nil))
    (projectile-compilation-dir)))

This is working for me, I don't know what other complications it might bring.

How to run the tests using the "compile" command?

Hi, congratulations on the great work done on this project!

I would really like to be able to run the tests through the Emacs compilation framework, it would give me the power to use "compile", "recompile" and "kill-compilation".
Is there any way to configure this package to do this?

Thanks!

requires direnv

When I have this in my startup file:

(require 'python-pytest)
(require 'direnv)

startup fails with:

Symbol's value as variable is void: direnv-non-file-modes

Switching the two lines around fixes this.

I guess you might as well just directly depend on direnv?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.