<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Devidas Gaikwad on Medium]]></title>
        <description><![CDATA[Stories by Devidas Gaikwad on Medium]]></description>
        <link>https://medium.com/@devidasgaikwad?source=rss-e2eaaba18e93------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*owvrF1ct0UfyhE9V.</url>
            <title>Stories by Devidas Gaikwad on Medium</title>
            <link>https://medium.com/@devidasgaikwad?source=rss-e2eaaba18e93------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:30:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devidasgaikwad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Common Pytest Interview Questions: A Series — Part 1]]></title>
            <link>https://medium.com/@devidasgaikwad/common-pytest-interview-questions-a-series-part-1-48f6017685f7?source=rss-e2eaaba18e93------2</link>
            <guid isPermaLink="false">https://medium.com/p/48f6017685f7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[pytest]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Devidas Gaikwad]]></dc:creator>
            <pubDate>Tue, 09 Sep 2025 15:18:34 GMT</pubDate>
            <atom:updated>2025-09-09T15:33:20.940Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Common Pytest Interview Questions: A Series — Part 1</strong></h3><h3>1. What is Pytest, and why do we use it?</h3><p>Pytest is an open-source <strong>testing framework for Python</strong> that makes it easy to write simple, scalable, and robust test cases. It is a fundamental tool for <strong>unit testing</strong> and <strong>functional testing</strong> in Python projects.</p><p>We use Pytest because it simplifies the testing process significantly:</p><ul><li><strong>Minimal boilerplate</strong>: You can start writing tests with just a few lines of code.</li><li><strong>Automatic test discovery</strong>: It automatically finds and runs test files and functions, so you don’t need to manually register them.</li><li><strong>Clear, simple syntax</strong>: It uses the standard Python assert keyword, which is more readable and intuitive than the assertion methods found in other frameworks like Python&#39;s built-in unittest.</li><li><strong>Rich features</strong>: It supports advanced features like fixtures, parametrization, and markers, which help you write more efficient and maintainable tests.</li><li><strong>Detailed reporting</strong>: When a test fails, Pytest provides a detailed report showing exactly which assertion failed and why.</li></ul><h3>2. What is a test fixture in Pytest?</h3><p>A <strong>test fixture</strong> is a function that provides a consistent, reliable environment for a test to run. It performs setup tasks (e.g., creating a temporary file, connecting to a database) and, optionally, teardown tasks (e.g., deleting the file, closing the connection). This ensures that each test is independent and repeatable.</p><p>You define a fixture using the <strong>@pytest.fixture</strong> decorator.</p><h4>Example</h4><p>Let’s say you have a function that reads from a configuration file. You can use a fixture to create a temporary file with sample data for your test.</p><p>Python</p><pre>import pytest<br>import os<br>import tempfile<br><br>@pytest.fixture<br>def temp_config_file():<br>    # 1. Setup: Create a temporary file and write content to it.<br>    fd, path = tempfile.mkstemp(suffix=&#39;.ini&#39;)<br>    with os.fdopen(fd, &#39;w&#39;) as tmp:<br>        tmp.write(&quot;[settings]\n&quot;)<br>        tmp.write(&quot;database = &#39;my_db&#39;\n&quot;)<br>    <br>    # 2. Yield the path to the fixture&#39;s resource.<br>    yield path<br>    <br>    # 3. Teardown: This code runs after the test finishes.<br>    os.remove(path)<br># A test that uses the fixture<br>def test_read_database_setting(temp_config_file):<br>    # The &#39;temp_config_file&#39; argument automatically receives the path from the fixture.<br>    config_path = temp_config_file<br>    <br>    # In a real-world scenario, you would have a function to read this file<br>    # For this example, we&#39;ll just read it directly to demonstrate the setup.<br>    with open(config_path, &#39;r&#39;) as f:<br>        content = f.read()<br>    <br>    # Assert that the content is as expected.<br>    assert &quot;database = &#39;my_db&#39;&quot; in content</pre><p>In this example, the temp_config_file fixture creates a file, makes it available to the test via the yield statement, and then automatically cleans it up (removes the file) after the test is complete.</p><h3>3. How do you run a test with Pytest?</h3><p>You execute tests by running the pytest command in your terminal. Pytest automatically discovers your tests based on a set of conventions.</p><p><strong>Test Discovery Rules:</strong></p><ul><li>Files must be named test_*.py or *_test.py.</li><li>Functions within those files must be named test_*.</li><li>Classes must be named Test* (e.g., TestUser).</li></ul><h4>Command Examples</h4><p>Assume you have a project with the following structure:</p><pre>my_project/<br>├── my_module.py<br>└── tests/<br>    ├── test_database.py<br>    └── test_api.py</pre><ul><li><strong>To run all tests in the current directory and its subdirectories:</strong></li><li>Bash</li></ul><p>pytest</p><ul><li><strong>To run a specific test file:</strong></li></ul><p>pytest tests/test_database.py</p><ul><li><strong>To run a specific test function inside a file</strong></li></ul><p>pytest tests/test_api.py::test_create_user</p><h3>4. What is an assertion in Pytest, and how do you use it?</h3><p>An <strong>assertion</strong> is a statement that checks if a condition is true. It is the core of any test, as it’s how you verify that the code you’re testing is behaving as expected.</p><p>Pytest uses the standard Python <strong>assert</strong> keyword. If the condition following assert is False, Pytest catches the failure and provides a detailed error message, making it easy to debug.</p><h4>Example</h4><p>Python</p><pre># A simple function to test<br>def divide(a, b):<br>    return a / b<br><br># A test case with assertions<br>def test_division_by_two():<br>    result = divide(10, 2)<br>    # This assertion checks if the result is equal to 5.0<br>    assert result == 5.0<br>def test_division_by_zero():<br>    # This assertion checks if calling divide(10, 0) raises a ZeroDivisionError<br>    import pytest<br>    with pytest.raises(ZeroDivisionError):<br>        divide(10, 0)</pre><p>Pytest’s output for a failing assertion is highly informative. For example, if you ran assert divide(10, 2) == 6, Pytest would show E assert 5.0 == 6, clearly indicating that the actual value was 5.0 while the expected value was 6.</p><p>&lt;br&gt;</p><h3>5. What is the difference between assert and assert not in Pytest?</h3><p>While both use the assert keyword, they check for opposite conditions.</p><ul><li><strong>assert</strong> checks if a condition is <strong>truthy</strong> (evaluates to True).</li><li><strong>assert not</strong> checks if a condition is <strong>falsy</strong> (evaluates to False).</li></ul><p>This is a standard Python concept that applies directly to Pytest.</p><h4>Example</h4><p>Python</p><pre>def is_even(number):<br>    return number % 2 == 0<br><br>def test_even_number():<br>    # &#39;assert&#39; checks if is_even(4) evaluates to True<br>    assert is_even(4)<br>def test_odd_number():<br>    # &#39;assert not&#39; checks if is_even(5) evaluates to False<br>    assert not is_even(5)</pre><h3>6. What is the pytest.ini file, and what is its purpose?</h3><p>The <strong>pytest.ini</strong> file is a configuration file that allows you to customize and control Pytest&#39;s behavior for your project. You place this file in the root directory of your project.</p><p>Its main purpose is to <strong>standardize test execution</strong> for everyone on your team. This prevents developers from needing to remember specific command-line arguments.</p><h4>Example pytest.ini</h4><p>Ini, TOML</p><pre>[pytest]<br># Tell Pytest where to look for tests<br>testpaths = tests src<br><br># Register a custom marker<br>markers =<br>    slow: mark a test as slow to run<br># Set a default command-line option<br>addopts = -v --strict-markers</pre><p>With this file, anyone running pytest from the project&#39;s root will automatically use these settings. For instance, running pytest -m &quot;not slow&quot; will skip all tests marked with @pytest.mark.slow.</p><h3>7. How do you write a test case in Pytest?</h3><p>You write a test case by creating a regular Python function that follows the Pytest naming conventions (starts with test_). Within this function, you include one or more assert statements to verify the behavior of your code.</p><h4>Example</h4><p>Python</p><pre># Assuming you have a file named &#39;calculator.py&#39;<br># with the function &#39;add&#39;<br>def add(a, b):<br>    return a + b<br><br># In a separate test file named &#39;test_calculator.py&#39;<br>def test_add_two_positive_numbers():<br>    &quot;&quot;&quot;A test case for adding two positive numbers.&quot;&quot;&quot;<br>    result = add(2, 3)<br>    assert result == 5<br>def test_add_positive_and_negative():<br>    &quot;&quot;&quot;A test case for adding a positive and a negative number.&quot;&quot;&quot;<br>    result = add(5, -3)<br>    assert result == 2</pre><h3>8. What is a test suite in Pytest?</h3><p>In Pytest, a <strong>test suite</strong> is a collection of related tests. Unlike other frameworks that might require a specific class or object to define a suite, Pytest’s approach is simpler and more organic: a test suite is simply a logical grouping of tests.</p><p>This grouping is typically achieved by placing related test functions into a single <strong>test file</strong> or organizing multiple test files within a dedicated <strong>directory</strong>.</p><h3>9. How do you skip a test in Pytest?</h3><p>You can skip a test using Pytest’s <strong>markers</strong>, which are decorators that you add to a test function. The two main decorators for skipping tests are:</p><ul><li><strong>@pytest.mark.skip</strong>: Unconditionally skips a test.</li><li><strong>@pytest.mark.skipif</strong>: Skips a test based on a specific condition.</li></ul><h4>Examples</h4><p>Unconditional Skip:</p><p>This is useful for tests that are not yet stable or are temporarily disabled.</p><p>Python</p><pre>import pytest<br><br>@pytest.mark.skip(reason=&quot;This feature is disabled in the current release.&quot;)<br>def test_unstable_feature():<br>    # This test will not run<br>    assert True</pre><p>Conditional Skip:</p><p>This is essential for tests that should only run in a specific environment or with a certain dependency.</p><p>Python</p><pre>import sys<br>import pytest<br><br># Skip this test if the Python version is less than 3.10<br>@pytest.mark.skipif(sys.version_info &lt; (3, 10), reason=&quot;requires Python 3.10 or higher&quot;)<br>def test_new_syntax():<br>    # This test will only run on Python 3.10 and above<br>    assert &quot;hello&quot;.startswith(&quot;h&quot;)</pre><h3>10. How do you parametrize a test in Pytest?</h3><p><strong>Parametrization</strong> is a powerful technique that allows you to run the same test function multiple times with different sets of input data and expected outputs. This drastically reduces code duplication and makes your tests more concise and maintainable.</p><p>You use the <strong>@pytest.mark.parametrize</strong> decorator to achieve this.</p><h4>Example</h4><p>Imagine you want to test a function that checks if a number is even. Instead of writing a separate test for each number, you can parametrize a single test.</p><p>Python</p><pre>import pytest<br><br>def is_even(number):<br>    return number % 2 == 0<br># The decorator takes two arguments:<br># 1. A string of comma-separated parameter names (&quot;input, expected&quot;).<br># 2. A list of tuples, where each tuple contains the values for the parameters.<br>@pytest.mark.parametrize(&quot;input, expected&quot;, [<br>    (2, True),    # Test case 1: 2 should be even<br>    (4, True),    # Test case 2: 4 should be even<br>    (3, False),   # Test case 3: 3 should not be even<br>    (0, True),    # Test case 4: 0 should be even<br>    (-2, True)    # Test case 5: -2 should be even<br>])<br>def test_is_even(input, expected):<br>    &quot;&quot;&quot;This test will run once for each tuple in the list.&quot;&quot;&quot;<br>    assert is_even(input) == expected</pre><p>This single test function will run five times, with Pytest automatically passing a different input and expected value for each run, and it will generate a separate report for each test run. This approach is far more efficient than writing five individual test functions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48f6017685f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>