【Pythonプログラミング入門】テストコードの書き方を解説!(pytest)

Pythonプログラミングに関する情報を発信しているサプーです! 
この動画はPythonのテストコードの書き方について解説しています。

・テストコードとは?
・pytestの使い方
これらについて説明しています💙

💻 動作環境 💻
Windows 10
Python 3.9.0

⭐️ チャプター ⭐️
0:00 今日のテーマ「Pythonのテストコード」
0:30 テストとは?
4:10 テストコードの書き方
10:13 モックの書き方
15:04 例外のテストコードの書き方
17:38 エンディング

 #python 
#programming 

What is GEEK

Buddha Community

【Pythonプログラミング入門】テストコードの書き方を解説!(pytest)
Royce  Reinger

Royce Reinger

1646539560

Pytest-cov: Coverage Plugin for Pytest

This plugin produces coverage reports. Compared to just using coverage run this plugin does some extras:

  • Subprocess support: you can fork or run stuff in a subprocess and will get covered without any fuss.
  • Xdist support: you can use all of pytest-xdist's features and still get coverage.
  • Consistent pytest behavior. If you run coverage run -m pytest you will have slightly different sys.path (CWD will be in it, unlike when running pytest).

All features offered by the coverage package should work, either through pytest-cov's command line options or through coverage's config file.

  • Free software: MIT license

Installation

Install with pip:

pip install pytest-cov

For distributed testing support install pytest-xdist:

pip install pytest-xdist

Upgrading from ancient pytest-cov

pytest-cov 2.0 is using a new .pth file (pytest-cov.pth). You may want to manually remove the older init_cov_core.pth from site-packages as it's not automatically removed.

Uninstalling

Uninstall with pip:

pip uninstall pytest-cov

Under certain scenarios a stray .pth file may be left around in site-packages.

  • pytest-cov 2.0 may leave a pytest-cov.pth if you installed without wheels (easy_install, setup.py install etc).
  • pytest-cov 1.8 or older will leave a init_cov_core.pth.

Usage

pytest --cov=myproj tests/

Would produce a report like:

-------------------- coverage: ... ---------------------
Name                 Stmts   Miss  Cover
----------------------------------------
myproj/__init__          2      0   100%
myproj/myproj          257     13    94%
myproj/feature4286      94      7    92%
----------------------------------------
TOTAL                  353     20    94%

Documentation

http://pytest-cov.rtfd.org/

Coverage Data File

The data file is erased at the beginning of testing to ensure clean data for each test run. If you need to combine the coverage of several test runs you can use the --cov-append option to append this coverage data to coverage data from previous test runs.

The data file is left at the end of testing so that it is possible to use normal coverage tools to examine it.

Limitations

For distributed testing the workers must have the pytest-cov package installed. This is needed since the plugin must be registered through setuptools for pytest to start the plugin on the worker.

For subprocess measurement environment variables must make it from the main process to the subprocess. The python used by the subprocess must have pytest-cov installed. The subprocess must do normal site initialisation so that the environment variables can be detected and coverage started.

Acknowledgements

Whilst this plugin has been built fresh from the ground up it has been influenced by the work done on pytest-coverage (Ross Lawley, James Mills, Holger Krekel) and nose-cover (Jason Pellerin) which are other coverage plugins.

Ned Batchelder for coverage and its ability to combine the coverage results of parallel runs.

Holger Krekel for pytest with its distributed testing support.

Jason Pellerin for nose.

Michael Foord for unittest2.

No doubt others have contributed to these tools as well.

Overview

docsDocumentation Status
testsGitHub Actions Status AppVeyor Build Status Requirements Status
package

PyPI Package latest release conda-forge PyPI Wheel Supported versions Supported implementations

Commits since latest release

Author: Pytest-dev
Source Code: https://github.com/pytest-dev/pytest-cov 
License: MIT License

#python #pytest 

Pytest Flask: A Set Of Pytest Fixtures to Test Flask Applications

pytest-flask

An extension of pytest test runner which provides a set of useful tools to simplify testing and development of the Flask extensions and applications.

To view a more detailed list of extension features and examples go to the PyPI overview page or package documentation.

How to start?

Considering the minimal flask application factory bellow in myapp.py as an example:

from flask import Flask

def create_app(config_filename):
   # create a minimal app
   app = Flask(__name__)
   app.config.from_pyfile(config_filename)

   # simple hello world view
   @app.route('/hello')
   def hello():
      return 'Hello, World!'

   return app

You first need to define your application fixture in conftest.py:

from myapp import create_app

@pytest.fixture
def app():
    app = create_app()
    return app

Finally, install the extension with dependencies and run your test suite:

$ pip install pytest-flask
$ pytest

Contributing

Don’t hesitate to create a GitHub issue for any bug or suggestion. For more information check our contribution guidelines.

Download Details:
Author: pytest-dev
Source Code: https://github.com/pytest-dev/pytest-flask
License: MIT License

#flask #python #pytest 

Edureka Fan

Edureka Fan

1582641538

PyTest Tutorial | Unit Testing Framework In Python | How to use PyTest

This Edureka video on ‘Pytest’ will help you understand how we can write simple tests in python with a use case for testing an API. Following are the topics discussed:

What is Pytest?
Getting Started With Pytest
Create Your First Test With Pytest
Multiple Tests
Grouping Multiple Tests
Pytest Fixtures
Parameterized Tests
Testing An API Using Pytest

#python #pytest #testing

Pytest Mypy: Mypy Static Type Checker Plugin for Pytest

pytest-mypy

Mypy static type checker plugin for pytest

Features

  • Runs the mypy static type checker on your source files as part of your pytest test runs.
  • Does for mypy what the pytest-flake8 plugin does for flake8.
  • This is a work in progress – pull requests appreciated.

Installation

You can install "pytest-mypy" via pip from PyPI:

$ pip install pytest-mypy

Usage

You can enable pytest-mypy with the --mypy flag:

$ py.test --mypy test_*.py

Mypy supports reading configuration settings from a mypy.ini file. Alternatively, the plugin can be configured in a conftest.py to invoke mypy with extra options:

def pytest_configure(config):
    plugin = config.pluginmanager.getplugin('mypy')
    plugin.mypy_argv.append('--check-untyped-defs')

You can restrict your test run to only perform mypy checks and not any other tests by using the -m option:

py.test --mypy -m mypy test_*.py

Author: dbader
Source Code: https://github.com/dbader/pytest-mypy
License: MIT license

#python #pytest 

Pytest Mypy Testing: Plugin to Test Mypy Output with Pytest

pytest-mypy-testing — Plugin to test mypy output with pytest

pytest-mypy-testing provides a pytest plugin to test that mypy produces a given output. As mypy can be told to display the type of an expression this allows us to check mypys type interference.

Installation

python -m pip install pytest-mypy-testing

The Python distribution package contains an entry point so that the plugin is automatically discovered by pytest. To disable the plugin when it is installed , you can use the pytest command line option -p no:mypy-testing.

Writing Mypy Output Test Cases

A mypy test case is a top-level functions decorated with @pytest.mark.mypy_testing in a file named *.mypy-testing or in a pytest test module. pytest-mypy-testing follows the pytest logic in identifying test modules and respects the python_files config value.

Note that pytest-mypy-testing uses the Python ast module to parse candidate files and does not import any file, i.e., the decorator must be exactly named @pytest.mark.mypy_testing.

In a pytest test module file you may combine both regular pytest test functions and mypy test functions. A single function can be both.

Example: A simple mypy test case could look like this:

@pytest.mark.mypy_testing
def mypy_test_invalid_assignment() -> None:
    foo = "abc"
    foo = 123  # E: Incompatible types in assignment (expression has type "int", variable has type "str")

The plugin runs mypy for every file containing at least one mypy test case. The mypy output is then compared to special Python comments in the file:

  • # N: <msg> - we expect a mypy note message
  • # W: <msg> - we expect a mypy warning message
  • # E: <msg> - we expect a mypy error message
  • # R: <msg> - we expect a mypy note message Revealed type is '<msg>'. This is useful to easily check reveal_type output:

Skipping and Expected Failures

Mypy test case functions can be decorated with @pytest.mark.skip and @pytest.mark.xfail to mark them as to-be-skipped and as expected-to-fail, respectively. As with the @pytest.mark.mypy_testing mark, the names must match exactly as the decorators are extracted from the ast.

Development

  • Create and activate a Python virtual environment.
  • Install development dependencies by calling python -m pip install -U -r requirements.txt.
  • Start developing.
  • To run all tests with tox, Python 3.7, 3.8, 3.9 and 3.10 must be available. You might want to look into using pyenv.

Changelog

v0.0.10

  • Add support for pytest 7.0.x and require Python >= 3.7 (#23)
  • Bump dependencies (#24)

v0.0.9

  • Disable soft error limit (#21)

v0.0.8

  • Normalize messages to enable support for mypy 0.902 and pytest 6.2.4 (#20)

v0.0.7

  • Fix PYTEST_VERSION_INFO - by @blueyed (#8)
  • Always pass --check-untyped-defs to mypy (#11)
  • Respect pytest config python_files when identifying pytest test modules (#12)

v0.0.6 - add pytest 5.4 support

  • Update the plugin to work with pytest 5.4 (#7)

v0.0.5 - CI improvements

  • Make invoke tasks work (partially) on Windows (#6)
  • Add an invoke task to run tox environments by selecting globs (e.g., inv tox -e py-*) (#6)
  • Use coverage directly for code coverage to get more consistent parallel run results (#6)
  • Use flit fork dflit to make packaging work with LICENSES directory (#6)
  • Bump dependencies (#6)
@pytest.mark.mypy_testing
def mypy_use_reveal_type():
    reveal_type(123)  # N: Revealed type is 'Literal[123]?'
    reveal_type(456)  # R: Literal[456]?

Author: davidfritzsche
Source Code: https://github.com/davidfritzsche/pytest-mypy-testing

#python #pytest