{"id":3041,"date":"2026-08-07T00:37:02","date_gmt":"2026-08-06T17:37:02","guid":{"rendered":"https:\/\/sumberlaba.com\/index.php\/2026\/08\/07\/how-to-write-unit-tests-with-pytest-a-practical-guide\/"},"modified":"2026-08-07T00:37:02","modified_gmt":"2026-08-06T17:37:02","slug":"how-to-write-unit-tests-with-pytest-a-practical-guide","status":"publish","type":"post","link":"https:\/\/sumberlaba.com\/index.php\/2026\/08\/07\/how-to-write-unit-tests-with-pytest-a-practical-guide\/","title":{"rendered":"How to Write Unit Tests with pytest: A Practical Guide"},"content":{"rendered":"<h1>How to Write Unit Tests with pytest: A Practical Guide<\/h1>\n<p>pytest is Python&#8217;s most popular testing framework, combining simple syntax with powerful features and minimal boilerplate. This practical guide covers the essentials of writing unit tests with pytest, from basic assertions to reusable fixtures, so you can start testing your code with confidence.<\/p>\n<p>Install pytest using <code>pip install pytest<\/code>. Create a test file named <code>test_*.py<\/code> or <code>*_test.py<\/code>, and place it in your project directory. Write test functions prefixed with <code>test_<\/code> \u2014 pytest automatically discovers and executes them.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/via.placeholder.com\/800x600\/4a90d9\/ffffff?text=how%20to%20write%20unit%20tests%20with%20pytest\" alt=\"Article illustration\" style=\"display:block;margin:20px auto;max-width:100%;height:auto;border-radius:8px;\" \/><\/p>\n<h2>1. Write Simple Test Functions<\/h2>\n<p>Define functions starting with <code>test_<\/code> and use <code>assert<\/code> statements to validate expected behavior:<\/p>\n<pre><code>def add(a, b):\n    return a + b\n\ndef test_add():\n    assert add(2, 3) == 5\n    assert add(-1, 1) == 0<\/code><\/pre>\n<h2>2. Test Exceptions and Floating-Point Values<\/h2>\n<p>Use <code>pytest.raises<\/code> to verify exceptions and <code>pytest.approx<\/code> for accurate floating-point comparisons:<\/p>\n<pre><code>import pytest\n\ndef divide(a, b):\n    if b == 0:\n        raise ValueError(\"Cannot divide by zero\")\n    return a \/ b\n\ndef test_divide():\n    with pytest.raises(ValueError):\n        divide(1, 0)\n    assert divide(1, 3) == pytest.approx(0.3333)<\/code><\/pre>\n<h2>3. Share Setup Code with Fixtures<\/h2>\n<p>Fixtures provide reusable setup and teardown. Decorate a function with <code>@pytest.fixture<\/code> and inject it as a test parameter:<\/p>\n<pre><code>@pytest.fixture\ndef sample_data():\n    return {\"a\": 1, \"b\": 2}\n\ndef test_sum(sample_data):\n    assert sample_data[\"a\"] + sample_data[\"b\"] == 3<\/code><\/pre>\n<h2>4. Run and Control Tests<\/h2>\n<p>Execute <code>pytest<\/code> in the terminal. Useful options include:<\/p>\n<ul>\n<li><code>-v<\/code> \u2014 verbose output<\/li>\n<li><code>-k<\/code> \u2014 filter tests by name<\/li>\n<li><code>--maxfail=1<\/code> \u2014 stop after first failure<\/li>\n<\/ul>\n<p>Detailed reports show exact tracebacks, making debugging fast and efficient.<\/p>\n<p>Writing unit tests with pytest is straightforward yet scales to complex projects. Start with simple asserts, add fixtures to organize reusable state, and explore features like parametrized tests and mocking to make your suite robust. A solid test suite keeps your code reliable and maintainable.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How to Write Unit Tests with pytest: A Practical Guide pytest is Python&#8217;s most popular testing framework, combining simple syntax with powerful features and minimal boilerplate. This practical guide covers the essentials of writing unit tests with pytest, from basic assertions to reusable fixtures, so you can start testing your code with confidence. Install pytest &hellip; <\/p>\n","protected":false},"author":2716,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"footnotes":""},"categories":[],"tags":[],"class_list":["post-3041","post","type-post","status-publish","format-standard","hentry"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/posts\/3041","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/users\/2716"}],"replies":[{"embeddable":true,"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/comments?post=3041"}],"version-history":[{"count":0,"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/posts\/3041\/revisions"}],"wp:attachment":[{"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/media?parent=3041"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/categories?post=3041"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sumberlaba.com\/index.php\/wp-json\/wp\/v2\/tags?post=3041"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}