Coder Social home page Coder Social logo

packtpublishing / crafting-test-driven-software-with-python Goto Github PK

View Code? Open in Web Editor NEW
64.0 8.0 34.0 85 KB

Crafting Test-Driven Software with Python, published by Packt

License: MIT License

Python 96.61% Gherkin 1.89% Makefile 0.49% RobotFramework 1.00%

crafting-test-driven-software-with-python's Introduction

Crafting Test-Driven Software with Python

Book Name

This is the code repository for Crafting Test-Driven Software with Python, published by Packt.

Write test suites that scale with your applications needs and complexity, using Python and PyTest

What is this book about?

Test-driven development (TDD) is a set of best practices that helps developers to build more scalable software, and is used to increase the robustness of software by using automatic tests. This book shows you how to apply TDD practices efficiently in Python projects.

This book covers the following exciting features:

  • Find out how tests can make your life easier as a developer and discover related best practices
  • Explore and learn PyTest, the most widespread testing framework for Python
  • Get to grips with the most common PyTest plugins, including coverage, flaky, xdist, and picked
  • Write functional tests for WSGI web applications with WebTest
  • Run end-to-end tests for web applications using the Robot framework

If you feel this book is for you, get your copy today!

https://www.packtpub.com/

Instructions and Navigations

All of the code is organized into folders. For example, Chapter01.

The code will look like the following:

import unittest

class MyTestCase(unittest.TestCase):
    def test_one(self):
        pass

Following is what you need for this book: This book is for Python developers looking to get started with test-driven development and developers who want to learn about the testing tools available in Python. Developers who want to create web applications with Django and Python and plan to implement TDD methodology with PyTest will find this book useful. Basic knowledge of Python programming is required.

With the following software and hardware list you can run all code files present in the book (Chapter 1-12).

Software and Hardware List

Chapter Software required OS required
1-12 Python 3.9,3.8 or 3.7 Windows, Mac OS X, and Linux (Any)
5-10 PyTest 6.0.2+ Windows, Mac OS X, and Linux (Any)
1-12 pip 18+ Windows, Mac OS X, and Linux (Any)
1-12 Google Chrome or Firefox Windows, Mac OS X, and Linux (Any)

Related products

Get to Know the Author

Alessandro Molina is a Python developer since 2001, who has always been interested in Python as a Web Development Platform. He worked as CTO and team leader of Python teams for the past 10 years and is currently core developer of the TurboGears2 web framework and maintainer of Beaker Caching/Session framework. He also authored the Modern Python Standard Library Cookbook. created the DEPOT file storage framework and the DukPy JavaScript interpreter for Python and collaborated with various Python projects related to web development, such as FormEncode, ToscaWidgets, and the Ming MongoDB ORM.

Other books by the author

Download a free PDF

If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.

https://packt.link/free-ebook/9781838642655

crafting-test-driven-software-with-python's People

Contributors

amol- avatar packt-itservice avatar packtutkarshr avatar saurabhk710 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

crafting-test-driven-software-with-python's Issues

Chapter 7 - BDD test for "Listing" feature failed

Here is the error captured from terminal

pytest -v
================================================= test session starts ==================================================
platform win32 -- Python 3.9.5, pytest-6.2.5, py-1.11.0, pluggy-1.0.0 -- C:\bin\python\python-3.9.5\python.exe
cachedir: .pytest_cache
benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
rootdir: C:\Working\gitea\Learn_Python_TDD_packt\Crafting-Test-Driven-Software-with-Python\Source_Code\Chapter07
plugins: anyio-3.3.0, dash-1.21.0, flaky-3.7.0, bdd-5.0.0, benchmark-3.4.1, cov-3.0.0, forked-1.4.0, testmon-1.2.2, xdist-2.5.0
collected 23 items

tests/functional/test_acceptance.py::TestAddingEntries::test_basic PASSED [ 4%]
tests/functional/test_acceptance.py::TestAddingEntries::test_surnames PASSED [ 8%]
tests/functional/test_acceptance.py::TestAddingEntries::test_international_numbers PASSED [ 13%]
tests/functional/test_acceptance.py::TestAddingEntries::test_invalid_strings PASSED [ 17%]
tests/functional/test_acceptance.py::TestAddingEntries::test_reload PASSED [ 21%]
tests/functional/test_acceptance.py::test_deleting_contacts PASSED [ 26%]
tests/functional/test_acceptance.py::test_listing_added_contacts[Mario-Luigi-Mario,Luigi] FAILED [ 30%]
tests/functional/test_acceptance.py::test_listing_added_contacts[John-Jane-John,Jane] FAILED [ 34%]
tests/unit/test_adding.py::TestAddContacts::test_basic PASSED [ 39%]
tests/unit/test_adding.py::TestAddContacts::test_special PASSED [ 43%]
tests/unit/test_adding.py::TestAddContacts::test_international PASSED [ 47%]
tests/unit/test_adding.py::TestAddContacts::test_invalid PASSED [ 52%]
tests/unit/test_adding.py::TestAddContacts::test_short PASSED [ 56%]
tests/unit/test_adding.py::TestAddContacts::test_missing PASSED [ 60%]
tests/unit/test_application.py::test_application PASSED [ 65%]
tests/unit/test_application.py::test_clear PASSED [ 69%]
tests/unit/test_application.py::TestRun::test_add PASSED [ 73%]
tests/unit/test_application.py::TestRun::test_add_surname PASSED [ 78%]
tests/unit/test_application.py::TestRun::test_empty PASSED [ 82%]
tests/unit/test_application.py::TestRun::test_nocmd PASSED [ 86%]
tests/unit/test_application.py::TestRun::test_invalid PASSED [ 91%]
tests/unit/test_persistence.py::TestLoading::test_load PASSED [ 95%]
tests/unit/test_persistence.py::TestSaving::test_save PASSED [100%]

======================================================= FAILURES =======================================================
_________________________________ test_listing_added_contacts[Mario-Luigi-Mario,Luigi] _________________________________

self = <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>
argname = 'pytestbdd_given_I have a first Mario contact'

def _get_active_fixturedef(
    self, argname: str
) -> Union["FixtureDef[object]", PseudoFixtureDef[object]]:
    try:
      return self._fixture_defs[argname]

E KeyError: 'pytestbdd_given_I have a first Mario contact'

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:589: KeyError

During handling of the above exception, another exception occurred:

request = <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>
step = <pytest_bdd.parser.Step object at 0x0000022458CF3670>
scenario = <pytest_bdd.parser.Scenario object at 0x0000022458CF3100>

def _find_step_function(request, step, scenario):
    """Match the step defined by the regular expression pattern.

    :param request: PyTest request object.
    :param step: Step.
    :param scenario: Scenario.

    :return: Function of the step.
    :rtype: function
    """
    name = step.name
    try:
        # Simple case where no parser is used for the step
      return request.getfixturevalue(get_step_fixture_name(name, step.type))

C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:77:


self = <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>
argname = 'pytestbdd_given_I have a first Mario contact'

def getfixturevalue(self, argname: str) -> Any:
    """Dynamically run a named fixture function.

    Declaring fixtures via function argument is recommended where possible.
    But if you can only decide whether to use another fixture at test
    setup time, you may use this function to retrieve it inside a fixture
    or test function body.

    :raises pytest.FixtureLookupError:
        If the given fixture could not be found.
    """
  fixturedef = self._get_active_fixturedef(argname)

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:581:


self = <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>
argname = 'pytestbdd_given_I have a first Mario contact'

def _get_active_fixturedef(
    self, argname: str
) -> Union["FixtureDef[object]", PseudoFixtureDef[object]]:
    try:
        return self._fixture_defs[argname]
    except KeyError:
        try:
          fixturedef = self._getnextfixturedef(argname)

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:592:


self = <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>
argname = 'pytestbdd_given_I have a first Mario contact'

def _getnextfixturedef(self, argname: str) -> "FixtureDef[Any]":
    fixturedefs = self._arg2fixturedefs.get(argname, None)
    if fixturedefs is None:
        # We arrive here because of a dynamic call to
        # getfixturevalue(argname) usage which was naturally
        # not known at parsing/collection time.
        assert self._pyfuncitem.parent is not None
        parentid = self._pyfuncitem.parent.nodeid
        fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)
        # TODO: Fix this type ignore. Either add assert or adjust types.
        #       Can this be None here?
        self._arg2fixturedefs[argname] = fixturedefs  # type: ignore[assignment]
    # fixturedefs list is immutable so we maintain a decreasing index.
    index = self._arg2index.get(argname, 0) - 1
    if fixturedefs is None or (-index > len(fixturedefs)):
      raise FixtureLookupError(argname, self)

E _pytest.fixtures.FixtureLookupError: ('pytestbdd_given_I have a first Mario contact', <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>)

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:473: FixtureLookupError

During handling of the above exception, another exception occurred:

request = <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>
_pytest_bdd_example = {'first': 'Mario', 'listed_contacts': 'Mario,Luigi', 'second': 'Luigi'}

@pytest.mark.usefixtures(*args)
def scenario_wrapper(request, _pytest_bdd_example):
    scenario = templated_scenario.render(_pytest_bdd_example)
  _execute_scenario(feature, scenario, request)

C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:174:


C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:138: in _execute_scenario
step_func = _find_step_function(request, step, scenario)


request = <FixtureRequest for <Function test_listing_added_contacts[Mario-Luigi-Mario,Luigi]>>
step = <pytest_bdd.parser.Step object at 0x0000022458CF3670>
scenario = <pytest_bdd.parser.Scenario object at 0x0000022458CF3100>

def _find_step_function(request, step, scenario):
    """Match the step defined by the regular expression pattern.

    :param request: PyTest request object.
    :param step: Step.
    :param scenario: Scenario.

    :return: Function of the step.
    :rtype: function
    """
    name = step.name
    try:
        # Simple case where no parser is used for the step
        return request.getfixturevalue(get_step_fixture_name(name, step.type))
    except FixtureLookupError:
        try:
            # Could not find a fixture with the same name, let's see if there is a parser involved
            name = find_argumented_step_fixture_name(name, step.type, request._fixturemanager, request)
            if name:
                return request.getfixturevalue(name)
            raise
        except FixtureLookupError:
          raise exceptions.StepDefinitionNotFoundError(
                f"Step definition is not found: {step}. "
                f'Line {step.line_number} in scenario "{scenario.name}" in the feature "{scenario.feature.filename}"'                )

E pytest_bdd.exceptions.StepDefinitionNotFoundError: Step definition is not found: Given "I have a first Mario contact". Line 6 in scenario "Listing Added Contacts" in the feature "C:\Working\gitea\Learn_Python_TDD_packt\Crafting-Test-Driven-Software-with-Python\Source_Code\Chapter07\tests\acceptance\list_contacts.feature"

C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:86: StepDefinitionNotFoundError
___________________________________ test_listing_added_contacts[John-Jane-John,Jane] ___________________________________

self = <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>
argname = 'pytestbdd_given_I have a first John contact'

def _get_active_fixturedef(
    self, argname: str
) -> Union["FixtureDef[object]", PseudoFixtureDef[object]]:
    try:
      return self._fixture_defs[argname]

E KeyError: 'pytestbdd_given_I have a first John contact'

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:589: KeyError

During handling of the above exception, another exception occurred:

request = <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>
step = <pytest_bdd.parser.Step object at 0x0000022458CF38E0>
scenario = <pytest_bdd.parser.Scenario object at 0x0000022458CF3940>

def _find_step_function(request, step, scenario):
    """Match the step defined by the regular expression pattern.

    :param request: PyTest request object.
    :param step: Step.
    :param scenario: Scenario.

    :return: Function of the step.
    :rtype: function
    """
    name = step.name
    try:
        # Simple case where no parser is used for the step
      return request.getfixturevalue(get_step_fixture_name(name, step.type))

C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:77:


self = <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>
argname = 'pytestbdd_given_I have a first John contact'

def getfixturevalue(self, argname: str) -> Any:
    """Dynamically run a named fixture function.

    Declaring fixtures via function argument is recommended where possible.
    But if you can only decide whether to use another fixture at test
    setup time, you may use this function to retrieve it inside a fixture
    or test function body.

    :raises pytest.FixtureLookupError:
        If the given fixture could not be found.
    """
  fixturedef = self._get_active_fixturedef(argname)

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:581:


self = <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>
argname = 'pytestbdd_given_I have a first John contact'

def _get_active_fixturedef(
    self, argname: str
) -> Union["FixtureDef[object]", PseudoFixtureDef[object]]:
    try:
        return self._fixture_defs[argname]
    except KeyError:
        try:
          fixturedef = self._getnextfixturedef(argname)

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:592:


self = <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>
argname = 'pytestbdd_given_I have a first John contact'

def _getnextfixturedef(self, argname: str) -> "FixtureDef[Any]":
    fixturedefs = self._arg2fixturedefs.get(argname, None)
    if fixturedefs is None:
        # We arrive here because of a dynamic call to
        # getfixturevalue(argname) usage which was naturally
        # not known at parsing/collection time.
        assert self._pyfuncitem.parent is not None
        parentid = self._pyfuncitem.parent.nodeid
        fixturedefs = self._fixturemanager.getfixturedefs(argname, parentid)
        # TODO: Fix this type ignore. Either add assert or adjust types.
        #       Can this be None here?
        self._arg2fixturedefs[argname] = fixturedefs  # type: ignore[assignment]
    # fixturedefs list is immutable so we maintain a decreasing index.
    index = self._arg2index.get(argname, 0) - 1
    if fixturedefs is None or (-index > len(fixturedefs)):
      raise FixtureLookupError(argname, self)

E _pytest.fixtures.FixtureLookupError: ('pytestbdd_given_I have a first John contact', <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>)

C:\bin\python\python-3.9.5\lib\site-packages_pytest\fixtures.py:473: FixtureLookupError

During handling of the above exception, another exception occurred:

request = <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>
_pytest_bdd_example = {'first': 'John', 'listed_contacts': 'John,Jane', 'second': 'Jane'}

@pytest.mark.usefixtures(*args)
def scenario_wrapper(request, _pytest_bdd_example):
    scenario = templated_scenario.render(_pytest_bdd_example)
  _execute_scenario(feature, scenario, request)

C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:174:


C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:138: in _execute_scenario
step_func = _find_step_function(request, step, scenario)


request = <FixtureRequest for <Function test_listing_added_contacts[John-Jane-John,Jane]>>
step = <pytest_bdd.parser.Step object at 0x0000022458CF38E0>
scenario = <pytest_bdd.parser.Scenario object at 0x0000022458CF3940>

def _find_step_function(request, step, scenario):
    """Match the step defined by the regular expression pattern.

    :param request: PyTest request object.
    :param step: Step.
    :param scenario: Scenario.

    :return: Function of the step.
    :rtype: function
    """
    name = step.name
    try:
        # Simple case where no parser is used for the step
        return request.getfixturevalue(get_step_fixture_name(name, step.type))
    except FixtureLookupError:
        try:
            # Could not find a fixture with the same name, let's see if there is a parser involved
            name = find_argumented_step_fixture_name(name, step.type, request._fixturemanager, request)
            if name:
                return request.getfixturevalue(name)
            raise
        except FixtureLookupError:
          raise exceptions.StepDefinitionNotFoundError(
                f"Step definition is not found: {step}. "
                f'Line {step.line_number} in scenario "{scenario.name}" in the feature "{scenario.feature.filename}"'                )

E pytest_bdd.exceptions.StepDefinitionNotFoundError: Step definition is not found: Given "I have a first John contact". Line 6 in scenario "Listing Added Contacts" in the feature "C:\Working\gitea\Learn_Python_TDD_packt\Crafting-Test-Driven-Software-with-Python\Source_Code\Chapter07\tests\acceptance\list_contacts.feature"

C:\bin\python\python-3.9.5\lib\site-packages\pytest_bdd\scenario.py:86: StepDefinitionNotFoundError
=============================================== short test summary info ================================================
FAILED tests/functional/test_acceptance.py::test_listing_added_contacts[Mario-Luigi-Mario,Luigi] - pytest_bdd.exceptio...FAILED tests/functional/test_acceptance.py::test_listing_added_contacts[John-Jane-John,Jane] - pytest_bdd.exceptions.S...============================================= 2 failed, 21 passed in 1.33s =============================================

make html not working

  • OS: Win 10
  • Python: py37

Hi I have a trouble with the Testing documentation section. When I use make html this error occurs: make: *** No rule to make target 'html'. Stop. I use make through chocolatey. TY

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.