
    
        
        
        
                
        
        
        
                
        
        
        
                
        
        
        
            
{"version":"https:\/\/jsonfeed.org\/version\/1","title":"mathspp.com feed","home_page_url":"https:\/\/mathspp.com\/blog\/tags\/testing","feed_url":"https:\/\/mathspp.com\/blog\/tags\/testing.json","description":"Stay up-to-date with the articles on mathematics and programming that get published to mathspp.com.","author":{"name":"Rodrigo Gir\u00e3o Serr\u00e3o"},"items":[{"title":"TIL #095 \u2013 better test parametrisation in pytest","date_published":"2024-04-22T17:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/til\/better-test-parametrisation-in-pytest","url":"https:\/\/mathspp.com\/blog\/til\/better-test-parametrisation-in-pytest","content_html":"<p>Today I learned how to use named tuples to improve readability and flexibility of test parametrisations in pytest.<\/p>\n\n<h2 id=\"better-test-parametrisation-in-pytest\">Better test parametrisation in pytest<a href=\"#better-test-parametrisation-in-pytest\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Today I attended a <a href=\"https:\/\/pretalx.com\/pyconde-pydata-2024\/talk\/DSFWRC\/\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">pytest tutorial<\/a> at <a href=\"https:\/\/2024.pycon.de\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">PyCon DE 2024<\/a> and I learned a couple of really neat tricks to improve parametrised tests.<\/p>\n<p>Let's take a look at them!<\/p>\n<h3 id=\"stacking-the-parametrize-mark\">Stacking the <code>parametrize<\/code> mark<a href=\"#stacking-the-parametrize-mark\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p>One quick tip is that you can stack <code>parametrize<\/code> to run all permutations of different parameters.<\/p>\n<p>For example, if <code>calc<\/code> is a function that does basic arithmetic operations, the test below will test 9 different additions:<\/p>\n<pre><code class=\"language-py\">import pytest\n\n@pytest.mark.parametrize(\"a\", [-3, 0, 5])\n@pytest.mark.parametrize(\"b\", [-8, 0, 42])\ndef test_calc_add(a, b):\n    assert calc(a, b, \"+\") == a + b<\/code><\/pre>\n<p>Running this test, you get the following output:<\/p>\n<pre><code>test_calc.py::test_calc_add[-8--3] PASSED     [ 11%]\ntest_calc.py::test_calc_add[-8-0] PASSED      [ 22%]\ntest_calc.py::test_calc_add[-8-5] PASSED      [ 33%]\ntest_calc.py::test_calc_add[0--3] PASSED      [ 44%]\ntest_calc.py::test_calc_add[0-0] PASSED       [ 55%]\ntest_calc.py::test_calc_add[0-5] PASSED       [ 66%]\ntest_calc.py::test_calc_add[42--3] PASSED     [ 77%]\ntest_calc.py::test_calc_add[42-0] PASSED      [ 88%]\ntest_calc.py::test_calc_add[42-5] PASSED      [100%]<\/code><\/pre>\n<p>With this pattern you cannot specify a test output for each single test, so this will only work if you have a different way of computing the result or if the expected result is always the same.<\/p>\n<p>For tests where you must specify the expected result but you also want to test all permutations of certain parameters, you can use the REPL and <code>itertools.product<\/code> to programmatically generate all the tests instead of having to write them down by hand.<\/p>\n<h3 id=\"parametrising-with-named-tuples\">Parametrising with named tuples<a href=\"#parametrising-with-named-tuples\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p>You can add a lot of flexibility and readability in your parametrised tests if you use named tuples<sup id=\"fnref1:1\"><a href=\"#fn:1\" class=\"footnote-ref\">1<\/a><\/sup>.\nInstead of listing tuples with plenty of different values, we can create a named tuple to wrap around those tuples, which then lets us use named parameters <em>and<\/em> default arguments in our parametrisation cases!<\/p>\n<p>As an example, consider a test that's parametrised in the conventional way:<\/p>\n<pre><code class=\"language-py\">import pytest\n\n@pytest.mark.parametrize(\n    [\"a\", \"b\", \"op\", \"result\", \"flag1\", \"flag2\"],\n    [\n        (10, 15, \"+\", 25, True, False),\n        (10, 15, \"-\", -5, True, False),\n        (3, 18, \"*\", 54, False, False),\n        (18, 3, \"\/\", 6, True, False),\n        (5, 0, \"\/\", None, True, True),\n    ]\n)\ndef test_something(a, b, op, result, flag1, flag2):\n    # do stuff with a, b, op, ...\n    ...<\/code><\/pre>\n<p>If you create a named tuple, you could use the names of the parameters to help disambiguate the two flags, for example, and you could also add default values:<\/p>\n<pre><code class=\"language-py\">from typing import NamedTuple\nimport pytest\n\nclass CaseParam(NamedTuple):\n    a: int\n    b: int\n    op: str\n    result: int\n    flag1: bool = True\n    flag2: bool = False\n\n@pytest.mark.parametrize(\n    [\"a\", \"b\", \"op\", \"result\", \"flag1\", \"flag2\"],\n    [\n        CaseParam(10, 15, \"+\", 25),\n        CaseParam(10, 15, \"-\", -5),\n        CaseParam(3, 18, \"*\", 54, flag1=False),\n        CaseParam(18, 3, \"\/\", 6),\n        CaseParam(5, 0, \"\/\", None, flag2=True),\n    ]\n)\ndef test_something(a, b, op, result, flag1, flag2):\n    # do stuff with a, b, op, ...\n    ...<\/code><\/pre>\n<p>This does add more code to your tests, so it's not really reasonable to do it for every single parametrisation you'll create, but it might come in handy for more complex parametrisations.\nI really liked this...<\/p>","summary":"Today I learned how to use named tuples to improve readability and flexibility of test parametrisations in pytest.","date_modified":"2025-09-06T19:56:10+02:00","tags":["modules","productivity","programming","pytest","python","testing"],"image":"\/user\/pages\/02.blog\/04.til\/095.better-test-parametrisation-in-pytest\/thumbnail.webp"},{"title":"TIL #094 \u2013 pytest.raises: parameter match","date_published":"2024-04-22T16:00:00+02:00","id":"https:\/\/mathspp.com\/blog\/til\/pytest.raises-parameter-match","url":"https:\/\/mathspp.com\/blog\/til\/pytest.raises-parameter-match","content_html":"<p>Today I learned about the parameter <code>match<\/code> used in <code>pytest.raises<\/code>.<\/p>\n\n<h2 id=\"pytest-raises-parameter-match\"><code>pytest.raises<\/code>: parameter <code>match<\/code><a href=\"#pytest-raises-parameter-match\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Today I attended a <a href=\"https:\/\/pretalx.com\/pyconde-pydata-2024\/talk\/DSFWRC\/\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">pytest tutorial<\/a> at <a href=\"https:\/\/2024.pycon.de\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">PyCon DE 2024<\/a> and very early in the tutorial I learned about the parameter <code>match<\/code> that you can use with <code>pytest.raises<\/code>.<\/p>\n<p>The parameter <code>match<\/code> accepts a regex pattern that is tested against the error message and your test only passes if the error message matches the regex.<\/p>\n<p>The initial example given was this:<\/p>\n<pre><code class=\"language-py\">def parse_pos_number(s: str) -&gt; int:\n    n = int(s)\n    if n &lt; 0:\n        raise ValueError(\"No negativity allowed!\")\n    return n<\/code><\/pre>\n<p>This function raises a <code>ValueError<\/code> if you pass it a negative value but it will also raise a (different) <code>ValueError<\/code> if you pass it a string that doesn't look like an integer:<\/p>\n<pre><code class=\"language-py\">parse_pos_number(\"-1\")  # ValueError: No negativity allowed!\nparse_pos_number(\"a\")   # ValueError: invalid literal for int() with base 10: 'a'<\/code><\/pre>\n<p>So, when writing a test to make sure that <code>parse_pos_number<\/code> fails when giving it a negative number, we should also ensure that the <code>ValueError<\/code> is \u201cthe correct one\u201d.\nThe test would look like this:<\/p>\n<pre><code class=\"language-py\">import pytest\n\ndef test_with_negative_number():\n    with pytest.raises(ValueError, match=\"No negativity allowed!\"):\n        parse_pos_number(\"-1\")<\/code><\/pre>\n<p>The trainer also put forward that this parameter <code>match<\/code> can be quite useful if you have a (custom) error that is raised in multiple situations.\nAdding <code>match<\/code> to your tests will also test your error messages and it acts as a \u201cdocumentation\u201d test.<\/p>","summary":"Today I learned about the parameter `match` used in `pytest.raises`.","date_modified":"2025-07-23T16:49:02+02:00","tags":["modules","programming","pytest","python","testing"],"image":"\/user\/pages\/02.blog\/04.til\/094.pytest.raises-parameter-match\/thumbnail.webp"},{"title":"TIL #090 \u2013 patching module globals with pytest","date_published":"2024-01-25T09:30:00+01:00","id":"https:\/\/mathspp.com\/blog\/til\/patching-module-globals-with-pytest","url":"https:\/\/mathspp.com\/blog\/til\/patching-module-globals-with-pytest","content_html":"<p>Yesterday I spent the whole day tryint to patch a module global.\nThis is what I ended up with.<\/p>\n\n<h2 id=\"patching-module-globals-with-pytest\">Patching module globals with <code>pytest<\/code><a href=\"#patching-module-globals-with-pytest\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<p>Suppose you have a small project that has an April Fool's joke set up:<\/p>\n<pre><code class=\"language-py\">## constants.py\n\nAPRIL_FOOLS = False<\/code><\/pre>\n<pre><code class=\"language-py\">## useful_code.py\n\nfrom constants import APRIL_FOOLS\n\ndef add(a, b):\n    if APRIL_FOOLS:\n        result = a - b\n    else:\n        result = a + b\n    return result<\/code><\/pre>\n<p>Now, suppose you want to test your April Fool's joke with <code>pytest<\/code>.\nOne thing I found online was that you could use the fixture <code>monkeypatch<\/code> and its method <code>setattr<\/code>, something like this:<\/p>\n<pre><code class=\"language-py\">## test_useful_code.py\n\nimport pytest\n\nimport constants\nimport useful_code\n\ndef test_add_on_april_fools(monkeypatch):\n    monkeypatch.setattr(constants, \"APRIL_FOOLS\", True)\n    assert useful_code.add(10, 5) == 5<\/code><\/pre>\n<p>(I'm sparing you from hearing about all of the embarrissingly dumb things I tried before getting to this point!)<\/p>\n<p>If you run this test with <code>pytest test_useful_code.py<\/code> you get a failure:<\/p>\n<pre><code>FAILED test_useful_code.py::test_add_on_april_fools - assert 15 == 5<\/code><\/pre>\n<p>What's happening, then?\nTake a moment to think about it...<\/p>\n<p>What's happening is that when I import <code>useful_code<\/code> into the testing file, that module will then run the line <code>from constants import APRIL_FOOLS<\/code>, which sets the variable <code>APRIL_FOOLS<\/code> inside the namespace of the module <code>useful_code<\/code>, which is <em>separate<\/em> from the namespace of the module <code>constants<\/code>!<\/p>\n<p>After banging my head against the wall for a while, I realised I could tweak my code to work with this testing approach!\nAll I had to do was use <code>constants.APRIL_FOOLS<\/code> instead of using <code>APRIL_FOOLS<\/code> directly:<\/p>\n<pre><code class=\"language-py\">## useful_code.py\n\nimport constants\n\ndef add(a, b):\n    if constants.APRIL_FOOLS:\n        result = a - b\n    else:\n        result = a + b\n    return result<\/code><\/pre>\n<p>Now, if you run your test it will pass and the mocking of the variable will have succeeded!<\/p>\n<p>The reason this works is that now we're accessing <code>APRIL_FOOLS<\/code> via the <code>constants<\/code> namespace, so when we patch the value of <code>APRIL_FOOLS<\/code> in <code>constants<\/code>, that patched value will be visible when the constant is used elsewhere.<\/p>\n<p>You could also patch <code>APRIL_FOOLS<\/code> directly in the module <code>useful_code<\/code>, but if you have a constant that is used in many different modules, it is much easier (and better) to patch it <em>once<\/em> where it is defined versus patching it many times wherever it is imported.<\/p>\n<p>I'm not claiming this is <em>the best solution<\/em> to this problem but it's certainly <em>a solution that works<\/em>.\nIf you have better ideas that have more or less the same complexity, let me know!<\/p>\n<p>For reference, this is a simplification of a \u201creal\u201d issue I had when trying to add tests to <a href=\"https:\/\/github.com\/Textualize\/textual\/pull\/4062\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">this Textual PR of mine<\/a>.<\/p>","summary":"Today I learned how to patch module globals with pytest.","date_modified":"2025-07-23T16:49:02+02:00","tags":["programming","pytest","python","testing"],"image":"\/user\/pages\/02.blog\/04.til\/090.patching-module-globals-with-pytest\/thumbnail.webp"},{"title":"TIL #076 \u2013 Hypothesis for code refactoring","date_published":"2023-08-08T18:10:00+02:00","id":"https:\/\/mathspp.com\/blog\/til\/hypothesis-for-code-refactoring","url":"https:\/\/mathspp.com\/blog\/til\/hypothesis-for-code-refactoring","content_html":"<p>Today I learned how to use Hypothesis to do confident code refactoring.<\/p>\n\n<h2 id=\"hypothesis-for-code-refactoring\">Hypothesis for code refactoring<a href=\"#hypothesis-for-code-refactoring\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h2>\n<h3 id=\"what-is-hypothesis\">What is Hypothesis?<a href=\"#what-is-hypothesis\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p><a href=\"https:\/\/hypothesis.readthedocs.io\/en\/latest\/index.html\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">Hypothesis<\/a> is a Python library that you can use when testing your code.\nIn a nutshell, Hypothesis will generate test cases automatically for you.<\/p>\n<p>In case you already know what that means, Hypothesis enables property-based testing, which is a &ldquo;testing paradigm&rdquo;.\nIn case you are interested, I've written about <a href=\"https:\/\/semaphoreci.com\/blog\/property-based-testing-python-hypothesis-pytest\" target=\"_blank\" rel=\"nofollow noopener noreferrer\" class=\"external-link no-image\">getting started with Hypothesis<\/a> before.<\/p>\n<p>One of the cool things about Hypothesis is that you can use it when you are refactoring code and you want to be as certain as possible that you are not breaking anything.\nLet me give you a concrete example.<\/p>\n<h3 id=\"code-refactoring\">Code refactoring<a href=\"#code-refactoring\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p>Recently I played a bit with the <a href=\"\/blog\/til\/damerau-levenshtein-distance\">Damerau-Levenshtein distance<\/a> and I implemented it in Python.\nThe code (taken from <a href=\"\/blog\/til\/damerau-levenshtein-distance\">this TIL article<\/a>) looked like this:<\/p>\n<pre><code class=\"language-py\">from functools import lru_cache\n\n@lru_cache\ndef dl(a, b):\n    edit_distances = []\n\n    if len(a) == len(b) == 0:\n        edit_distances.append(0)\n\n    if len(a) &gt; 0:\n        edit_distances.append(dl(a[:-1], b) + 1)\n\n    if len(b) &gt; 0:\n        edit_distances.append(dl(a, b[:-1]) + 1)\n\n    if len(a) &gt; 0 and len(b) &gt; 0:\n        edit_distances.append(dl(a[:-1], b[:-1]) + (a[-1] != b[-1]))\n\n    if len(a) &gt; 1 and len(b) &gt; 1 and a[-1] == b[-2] and a[-2] == b[-1]:\n        edit_distances.append(dl(a[:-2], b[:-2]) + (a[-1] != b[-1]))\n\n    return min(edit_distances)<\/code><\/pre>\n<p>However, this was just a basic implementation that translated the mathematical formula that the Wikipedia page showed.\nI wanted to have a go at rewriting this in a better way.\nI wanted to <em>refactor<\/em> the code.<\/p>\n<p>So, I did.\nI came up with this alternative implementation:<\/p>\n<pre><code class=\"language-py\">from functools import lru_cache\n\n@lru_cache\ndef dl(a, b):\n    if not a or not b:\n        return len(a) + len(b)\n\n    levenshstein = min(\n        dl(a[:-1], b) + 1,\n        dl(a, b[:-1]) + 1,\n        dl(a[:-1], b[:-1]) + (a[-1] != b[-1]),\n    )\n\n    if a[:-1] and b[:-1] and a[-1] == b[-2] and b[-1] == a[-2]:\n        return min(\n            levenshstein,\n            dl(a[:-2], b[:-2]) + (a[-1] != b[-1]),\n        )\n\n    return levenshstein<\/code><\/pre>\n<p>Now, the question is:\nare these two functions the same?\nDo the two functions compute the same thing?<\/p>\n<p>Enter: Hypothesis!<\/p>\n<h3 id=\"verifying-a-code-refactor-with-hypothesis\">Verifying a code refactor with Hypothesis<a href=\"#verifying-a-code-refactor-with-hypothesis\" class=\"toc-anchor after\" data-anchor-icon=\"#\" aria-label=\"Anchor\"><\/a><\/h3>\n<p>Because Hypothesis generates random test cases for you, what you can do is create a test where Hypothesis generates two random strings, we feed the two strings to the two alternative implementations, and then we check if they return the same result!<\/p>\n<p>In essence, if <code>dl<\/code> and <code>dl2<\/code> are the two functions, you just need to write this:<\/p>\n<pre><code class=\"language-py\">## dl.py\nfrom functools import lru_cache\n\nfrom hypothesis import given\nfrom hypothesis.strategies import text\n\n@lru_cache\ndef dl(a, b):\n    ...\n\n@lru_cache\ndef dl2(a, b):\n    ...\n\n@given(text(max_size=15), text(max_size=15))\ndef test_dl_match(a, b):\n    assert dl(a, b) == dl2(a, b)<\/code><\/pre>\n<p>Then, you can run your tests &ndash; for example, with <code>pytest dl.py<\/code> &ndash; and wait for Hypothesis's verdict.\nIf the test passes, that's because the two functions <em>probably<\/em> compute the same thing.<\/p>\n<p>In this case, the test passes, so the two functions likely are the same and my refactor is OK!<\/p>\n<p>Notice that this doesn't guarantee that the two functions are correct!...<\/p>","summary":"Today I learned how to use Hypothesis to do confident code refactoring.","date_modified":"2025-07-23T16:49:02+02:00","tags":["hypothesis","programming","python","testing"],"image":"\/user\/pages\/02.blog\/04.til\/076.hypothesis-for-code-refactoring\/thumbnail.webp"}]}
