For the best experience, try the new Microsoft Edge browser recommended by Microsoft (version 87 or above) or switch to another browser Google Chrome / Firefox / Safari
OK

Pytest - One Solution for Unit, Functional and Acceptance Tests

Pytest-One-Solution-for-Unit-Functional-and-Acceptance-Tests-Xoriant

Python: A Digital Quality Assurance Engineer's Choice

Python is a general purpose, dynamic and flexible language, hence a lot of applications are being developed using Python. From a tester’s perspective, it has readily available modules and libraries which make scripts creation a lot easier. Tests can be written as xUnit-style classes or as functions. It provides full fledge automation testing solution for any sort of project cause and It is capable enough to perform unit, functional, system and BDD testing.

Pytest: Best among all Python testing frameworks, Pytest is a Python testing framework which provides a single solution for Unit, Functional and Acceptance testing. It is popular than the other available frameworks because of its attractive features. Below are some of the features of Pytest:

  1. Pytest offers test design with no boilerplate
  2. It does not require separate methods for assertion like  assertEquals, assertTrue, assertContains
  3. Tests can be parametrized which reduces code duplication
  4. Pytest can run tests written in unittest, doctest, autres and nose
  5. 150+ external plugins available to support all sorts of functional testing
  6. Plugins available like pytest-BDD and pytest-konira for writing tests for Behaviour Driven Testing
  7. It works wonder for GUI automation testing, when used along with testing tools like selenium webdriver or splinter

In short, Pytest is a one-stop solution for all sort of Python testing — be it unit, functional, highly complex functional or acceptance tests (BDD).

Top Most Pytest Features and Properties of Pytest Fixtures

Nervous system of pytest Fixtures are the key concept in pytest which can essentially provide baseline for test creation and execution. To declare any method as fixture just put the annotation for the method “@pytest.fixture” and put them in “Conftest.py”

Fixture example: @pytest.fixture def open_browser(): driver = webdriver.Firefox() driver.get("http://www.python.org") assert "Python" in driver.title The above designed fixture will be available for the whole project provided this should specified in project directory conftest.py file.

  • Conftest.py file contains all configuration settings, all defined fixtures, hooks implementations and it is applicable to the directory level. They get loaded by default whenever tool is invoked.

Key Points on Fixtures:

  • Fixtures have names and can be called from anywhere in the project, modules, classes and tests
  • Fixtures can return or not return any value or just execute the specified steps in it.
  • Fixtures can be passed as function arguments and in that case the returning value of fixture will be available in the mentioned method.
  • Fixture can be specified in directory level conftest.py file. Can be called from any method and it will execute the steps specified in it.
  • A fixture can take multiple fixtures, and each fixture triggers other fixture, thus serves a modular approach.
  • Fixtures can be scoped as per the need. This is a good practice keeping in mind time-expensiveness. Scope can be “session”, “module”, “class” and “function”.

Request Object: Introspect agent This is one of the useful features to search or introspect the “requesting item”. It can introspect from test function, class, module, or session. Items specified in config file or returning by some other fixtures can be used efficiently by the called fixture by “getattr” function. Just check the below mentioned fixture:

Example:

@pytest.fixture
def driver(request, browser_type):
    """return a webdriver instance for testing """
    try: 
        _driver = getattr(webdriver, browser_type)()
    except AttributeError as error:
        logger.info("Browser type %s unavailable!", browser_type) raise AttributeError
    return _driver


Finalization Code: Setting up of teardown Fixture can be used for teardown as well. This can be achieved by using “yield” keyword. Just put the fixture with the annotation “@pytest.yield_fixture“ and put the steps after “yield” keyword in the fixture. And whenever fixture will go out of scope the steps after the “yield” keyword will serves as  teardown process. Have a look at the below modified steps of the “driver” fixture.

Example:

@pytest.fixture
def driver(request, browser_type):
    """return a webdriver instance for testing """
    try: 
        _driver = getattr(webdriver, browser_type)()
    except AttributeError as error:
        logger.info("Browser type %s unavailable!", browser_type) raise AttributeError
yield _driverlogger.info("Finishing test")
logger.info('*************************') _driver.quit()

 

In the above-mentioned fixture whenever “browser_type” is not available the driver instance will be quit.

 

Fixture Parametrization: Enhances reusability Fixtures can be parametrized and can be executed multiple times with different set of data, the same way as a normal function is executed.

Use Fixture: Call for fixture from anywhere One way by which fixtures can be made available anywhere in the project is by calling them by using the decorator 
“@pytest.mark.usefixtures("fixture_1", "fixture_2")”.

Autouse Fixture: Mark the fixture for all AF are the fixtures methods which get invoked without “usefixtures” decorator or “funcgars”. Any fixture can be registered for autouse. Just need to put keyword autouse with “True” flag. “pytest.fixture(scope="module",autouse=True)”. 

Fixture will run for a class or test, or module as mentioned in the scope. If they are defined in conftest then they will be invoked by all tests present below the directory. These fixtures are particularly useful to set applicable global settings for the test session.

Auto Test Discovery in Pytest: Ease of execution One of the very useful features is auto test discovery in pytest. Its means it detects all the tests once execution command is invoked,  user only need to specify the test modules and test with a prefix “test_*.” while designing . Command line arguments can be specified with tests names, directories, node ids and file names. In case of absence of any command line arguments then collection with start from specified ‘testpaths’ (provided they need to be configured). This feature help in running all the tests, multiple tests in groups, single test, and tests belong to specific directories. Alternatively, test can be organized in specific folder structure as per the modules and thus can be executed as per the need.

At Xoriant, our expert engineering team has developed modern tools, processes, and frameworks to accelerate software release cycles using an integrated approach to testing and development. Our Continuous Quality Engineering platform coupled with a consultative approach ensures we fit within and augment your own quality engineering plans.

Does your products need a modern approach to digital quality assurance?

Speak With Xoriant Engineering Experts

Leave a reply

Your email address will not be published. Required fields are marked*

Filtered HTML

  • Web page addresses and email addresses turn into links automatically.
  • Allowed HTML tags: <a href hreflang> <p> <span> <div> <h1> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <hr> <br> <br /> <ul type> <ol start type> <li> <dl> <dt> <dd> <em> <b> <u> <i> <strong> <del> <ins> <sub> <sup> <quote> <blockquote cite> <pre> <address> <code> <strike> <caption>
  • Lines and paragraphs break automatically.