{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "d42a9120-8d70-4b10-8d6c-b59692fd03ad", "metadata": {}, "outputs": [], "source": [ "%%capture\n", "%load_ext autoreload\n", "%autoreload 2" ] }, { "cell_type": "code", "execution_count": null, "id": "11cb390f-b0f4-438d-b524-db7242d22ee9", "metadata": {}, "outputs": [], "source": [ "#| default_exp: test" ] }, { "cell_type": "code", "execution_count": null, "id": "dd03783f-252c-40f5-b92f-0f3f9278ce09", "metadata": {}, "outputs": [], "source": [ "#| export\n", "import ast,copy,contextlib,inspect,os,operator,reprlib,textwrap,traceback\n", "from typing import Any,Callable,Generator\n", "from dataclasses import dataclass" ] }, { "cell_type": "code", "execution_count": null, "id": "2cf5d527", "metadata": {}, "outputs": [], "source": [ "from nb.core import pubattr" ] }, { "cell_type": "markdown", "id": "5b8abf6a-c94a-43e5-a1d1-81b1a1d64656", "metadata": {}, "source": [ "# Testing\n", "> Utilities for testing within notebooks" ] }, { "cell_type": "markdown", "id": "12e34b1f", "metadata": {}, "source": [ "## Re-constructing source code and program state during runtime" ] }, { "cell_type": "markdown", "id": "93a3d5fe", "metadata": {}, "source": [ "When writing test libraries, it can be incredibly useful to understand what the call site source code looks like.\n", "\n", "For instance, let's say you call `equal(x in [1, 2, 3], should_exist)`. When we're in `equal`, the arguments have already been evaluated and we simply have two booleans as arguments, each `True` or `False`. If this test fails, it likely isn't *that* helpful to see `False != True`. \n", "\n", "Instead, it is likely much *more* helpful to see something like `x in [1, 2, 3] != should_exist` where `x = 4` and `should_exist=True`." ] }, { "cell_type": "markdown", "id": "86b4b04c", "metadata": {}, "source": [ "Let's take a look at `inspect.currentframe` to start, which returns the frame object for the caller's stack frame.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "id": "058c5afe", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['clear',\n", " 'f_back',\n", " 'f_builtins',\n", " 'f_code',\n", " 'f_globals',\n", " 'f_lasti',\n", " 'f_lineno',\n", " 'f_locals',\n", " 'f_trace',\n", " 'f_trace_lines',\n", " 'f_trace_opcodes']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "pubattr(inspect.currentframe())" ] }, { "cell_type": "markdown", "id": "5cd6117c", "metadata": {}, "source": [ "Okay, so we can get the *current* frame, but we want the caller's frame. For any given frame, we can get the *outer frames* of it via `inspect.getouterframes`." ] }, { "cell_type": "code", "execution_count": null, "id": "28ec6212", "metadata": {}, "outputs": [], "source": [ "def f(x,y,z,a=1):\n", " return inspect.getouterframes(inspect.currentframe())[1]\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a7fa576a", "metadata": {}, "outputs": [], "source": [ "with open(\"/tmp/tmp.txt\", mode=\"a\"):\n", " caller_fm = f(\n", " 1+1,\n", " 2,\n", " max(5, 2),\n", " a=2,\n", " )\n" ] }, { "cell_type": "code", "execution_count": null, "id": "f2088db2", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[' caller_fm = f(\\n']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "caller_fm.code_context" ] }, { "cell_type": "code", "execution_count": null, "id": "c463da2f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "Positions(lineno=2, end_lineno=7, col_offset=16, end_col_offset=5)" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "caller_fm.positions" ] }, { "cell_type": "markdown", "id": "cf730643", "metadata": {}, "source": [ "From this, we can see `code_context` has the first line of context of where we're executing `f`. Furthermore, note `positions` has all the information around we're extract out only our call to `f` from this block of code." ] }, { "cell_type": "markdown", "id": "95cd0a65", "metadata": {}, "source": [ "Okay, so what do we do from here? We _could_ use `code_context` and pass in `context=X` to `inspect.getouterframes`. However, there isn't a great static value to pass in for `context` since a function could span an arbitrary number of lines.\n", "\n", "So, what could we do instead? The `inspect` module has a function called `inspect.getsourcelines`. Given a frame, we can get the source code with `inspect.getsourcelines` and we can extract out our exact function from the source code via the `positions` on the frame object." ] }, { "cell_type": "code", "execution_count": null, "id": "cde6030a", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['with open(\"/tmp/tmp.txt\", mode=\"a\"):\\n',\n", " ' caller_fm = f(\\n',\n", " ' 1+1,\\n',\n", " ' 2,\\n',\n", " ' max(5, 2),\\n',\n", " ' a=2,\\n',\n", " ' )\\n']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "src, _ = inspect.getsourcelines(caller_fm.frame)\n", "src" ] }, { "cell_type": "code", "execution_count": null, "id": "022f2436", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[' caller_fm = f(\\n',\n", " ' 1+1,\\n',\n", " ' 2,\\n',\n", " ' max(5, 2),\\n',\n", " ' a=2,\\n',\n", " ' )\\n']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "srcl = src[caller_fm.positions.lineno-1:caller_fm.positions.end_lineno]\n", "srcl" ] }, { "cell_type": "markdown", "id": "0b306110", "metadata": {}, "source": [ "So, now we have the *lines* of source code we're interested in. However, we also need to look at the *column offsets* of the first and last line to get only our call to `f`." ] }, { "cell_type": "code", "execution_count": null, "id": "a2c3f459", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'f'" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "srcl[0][caller_fm.positions.col_offset]" ] }, { "cell_type": "code", "execution_count": null, "id": "5a7d9955", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\\n'" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "srcl[-1][caller_fm.positions.end_col_offset]" ] }, { "cell_type": "code", "execution_count": null, "id": "c30f907f", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'f(\\n 1+1,\\n 2,\\n max(5, 2),\\n a=2,\\n )'" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fn_src = \"\".join(\n", " [srcl[0][caller_fm.positions.col_offset:]] +\n", " srcl[1:-1] +\n", " [srcl[-1][:caller_fm.positions.end_col_offset]]\n", ")\n", "fn_src" ] }, { "cell_type": "markdown", "id": "70b80328", "metadata": {}, "source": [ "Beautiful! Anywhere we are, we can get the current frame, get the caller frame, get the source code for that frame, and extract out the function call that got us to where we are.\n", "\n", "Now, how can we extract out the arguments to the function call? One approach we can use here is to use the `ast` module to parse the function call into a tree that is knowledable about what each piece of syntax means. That then allows us to easily find the function arguments without having to parse raw text." ] }, { "cell_type": "code", "execution_count": null, "id": "54df1747", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['1 + 1', '2', 'max(5, 2)']" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fn_src_args = [ast.unparse(arg) for arg in ast.parse(fn_src).body[0].value.args]\n", "fn_src_args" ] }, { "cell_type": "code", "execution_count": null, "id": "ee5cb9e8", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'a': '2'}" ] }, "execution_count": null, "metadata": {}, "output_type": "execute_result" } ], "source": [ "fn_src_kwargs = {kw.arg: ast.unparse(kw.value) for kw in ast.parse(fn_src).body[0].value.keywords}\n", "fn_src_kwargs" ] }, { "cell_type": "markdown", "id": "0dde3bf7", "metadata": {}, "source": [ "Okay, we should now have everything we need. Let's put it together." ] }, { "cell_type": "code", "execution_count": null, "id": "a6c67919", "metadata": {}, "outputs": [], "source": [ "#| export\n", "def get_call_args(frames_up: int = 1) -> tuple[list[str], dict[str,Any]]:\n", " \"Get the source code expressions of the caller's arguments.\"\n", " fm_info = inspect.getouterframes(inspect.currentframe())[frames_up+1]\n", " src, _ = inspect.getsourcelines(fm_info.frame)\n", " srcl = src[fm_info.positions.lineno - 1:fm_info.positions.end_lineno]\n", " if len(srcl) == 0:\n", " raise RuntimeError(\n", " \"`get_call_args` is designed to be called from within a function, \" +\n", " \"not at the top-level. If you want to call it at the top level, pass `frames_up=0`.\"\n", " )\n", " elif len(srcl) == 1:\n", " fn_src = srcl[0][fm_info.positions.col_offset:fm_info.positions.end_col_offset]\n", " else:\n", " fn_src = \"\".join(\n", " [srcl[0][fm_info.positions.col_offset:]] +\n", " srcl[1:-1] +\n", " [srcl[-1][:fm_info.positions.end_col_offset]]\n", " )\n", " call_node = ast.parse(fn_src).body[0].value\n", " args_src = [ast.unparse(arg) for arg in call_node.args]\n", " kwargs_src = {kw.arg: ast.unparse(kw.value) for kw in call_node.keywords}\n", " return args_src, kwargs_src" ] }, { "cell_type": "markdown", "id": "487c29d9", "metadata": {}, "source": [ "Because `get_call_args()` is expected to be used from within a function, it generally will not work properly by default if you call it from the top-level." ] }, { "cell_type": "code", "execution_count": null, "id": "bbe2859c", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "`get_call_args` is designed to be called from within a function, not at the top-level. If you want to call it at the top level, pass `frames_up=0`.\n" ] } ], "source": [ "try: get_call_args(); assert False, \"should have raised\"\n", "except RuntimeError as e: print(e)" ] }, { "cell_type": "markdown", "id": "ce788841", "metadata": {}, "source": [ "However, you _can_ have it work if you pass `frames_up=0` (i.e. the current frame we're calling `get_call_args()` from rather than the caller frame)." ] }, { "cell_type": "code", "execution_count": null, "id": "1f3b1abb", "metadata": {}, "outputs": [], "source": [ "args, kwargs = get_call_args(frames_up=0)\n", "assert args == [], f\"Got {args}\"\n", "assert kwargs == {\"frames_up\": \"0\"}, f\"Got {kwargs}\"" ] }, { "cell_type": "markdown", "id": "5a48fa09", "metadata": {}, "source": [ "When you're in a function, it works as expected." ] }, { "cell_type": "code", "execution_count": null, "id": "b7730389", "metadata": {}, "outputs": [], "source": [ "def f(a, b=1):\n", " return get_call_args()" ] }, { "cell_type": "code", "execution_count": null, "id": "19890aa0", "metadata": {}, "outputs": [], "source": [ "args, kwargs = f(1+1,b=max(10, 20))\n", "assert args == [\"1 + 1\"], f\"Got {args}\"\n", "assert kwargs == {\"b\": \"max(10, 20)\"}, f\"Got {kwargs}\"" ] }, { "cell_type": "markdown", "id": "b9aba848", "metadata": {}, "source": [ "It also works with multi-line function calls.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "b8b7195c", "metadata": {}, "outputs": [], "source": [ "args, kwargs = f(\n", " 1,\n", " b=10,\n", " \n", " \n", ")\n", "assert args == [\"1\"], f\"Got {args}\"\n", "assert kwargs == {\"b\": \"10\"}, f\"Got {kwargs}\"" ] }, { "cell_type": "markdown", "id": "f93a8882", "metadata": {}, "source": [ "If you use it with a function within a function, you'll get the arguments for the inner function.\n" ] }, { "cell_type": "code", "execution_count": null, "id": "ce0666f5", "metadata": {}, "outputs": [], "source": [ "def nested_f(a, b=1):\n", " def inner_f(c, d, e=1):\n", " return get_call_args()\n", " return inner_f(5 * 5, 10 / 10)" ] }, { "cell_type": "code", "execution_count": null, "id": "3555f6cf", "metadata": {}, "outputs": [], "source": [ "args, kwargs = nested_f(1)\n", "assert args == [\"5 * 5\", \"10 / 10\"], f\"Got {args}\"\n", "assert kwargs == {}, f\"Got {kwargs}\"" ] }, { "cell_type": "markdown", "id": "97d47759", "metadata": {}, "source": [ "However, you can still get the outer function arguments with the `frames_up` keyword argument." ] }, { "cell_type": "code", "execution_count": null, "id": "2a42fc2b", "metadata": {}, "outputs": [], "source": [ "def nested_f(a, b=1):\n", " def inner_f(c, d, e=1):\n", " return get_call_args(frames_up=2)\n", " return inner_f(5 * 5, 10 / 10)" ] }, { "cell_type": "code", "execution_count": null, "id": "b3687819", "metadata": {}, "outputs": [], "source": [ "args, kwargs = nested_f(1)\n", "assert args == [\"1\"], f\"Got {args}\"\n", "assert kwargs == {}, f\"Got {kwargs}\"" ] }, { "cell_type": "markdown", "id": "5d991fd4", "metadata": {}, "source": [ "## Assertions" ] }, { "cell_type": "markdown", "id": "a25dcdf0", "metadata": {}, "source": [ "### Raises" ] }, { "cell_type": "code", "execution_count": null, "id": "623a480c", "metadata": {}, "outputs": [], "source": [ "#| export\n", "@dataclass\n", "class ExceptionInfo:\n", " type_: type[Exception]|None=None\n", " value: Exception|None=None\n", " traceback: str|None=None" ] }, { "cell_type": "code", "execution_count": null, "id": "0ad5fcef-f04d-469d-8ad1-94d3a98694e4", "metadata": {}, "outputs": [], "source": [ "#| export\n", "@contextlib.contextmanager\n", "def raises(\n", " exc: type[Exception]=Exception, # The exception type to check is raised.\n", " contains: str|None=None, # Check whether the raised exception contains this message.\n", ") -> Generator[ExceptionInfo, None, None]:\n", " \"Asserts that the body of the context manager raises `exc`.\"\n", " raised = True\n", " try:\n", " info = ExceptionInfo()\n", " yield info\n", " raised = False\n", " except exc as e:\n", " info.type_ = type(e)\n", " info.value = e\n", " info.traceback = traceback.format_tb(e.__traceback__)\n", " if contains and contains not in str(e):\n", " raise AssertionError(f\"Raised {e} but message does not contain {contains}\") from e\n", " assert raised, \"Did not raise\"" ] }, { "cell_type": "code", "execution_count": null, "id": "7c478098-7a09-403c-a62b-3c34cf0f7bab", "metadata": {}, "outputs": [], "source": [ "with raises() as e:\n", " raise Exception(\"abc\")\n", "assert type(e) == ExceptionInfo\n", "assert e.type_ == Exception\n", "assert e.value.args == ('abc',)\n", "assert len(e.traceback) > 0" ] }, { "cell_type": "markdown", "id": "765265ca", "metadata": {}, "source": [ "### Primitives (expect, expect_fail)" ] }, { "cell_type": "code", "execution_count": null, "id": "10ba9dcd", "metadata": {}, "outputs": [], "source": [ "#| export\n", "def expect(\n", " a, b,\n", " cmp:Callable,\n", " negstr:str|None=None, # Used in the error message on failure: 'a {negstr} b'. Defaults to 'not {cmp.__name__}'.\n", " frames_up:int|None=1, # The number of frames up to look at to get the source expressions.\n", " truncate:bool=True, # Truncate the repr representations of a and b when shown.\n", "):\n", " \"Expect that cmp(a, b) is true.\"\n", " if negstr is None: negstr = f'not {cmp.__name__}'\n", " args_src, _ = get_call_args(frames_up)\n", " a_repr = reprlib.repr(a) if truncate else repr(a)\n", " b_repr = reprlib.repr(b) if truncate else repr(b)\n", " a_src = args_src[0] if len(args_src) > 0 else a_repr\n", " b_src = args_src[1] if len(args_src) > 1 else b_repr\n", " lines = [f'{a_src} {negstr} {b_src}']\n", " if len(args_src) > 0 and a_repr != args_src[0]: lines.append(f' where {args_src[0]} = {a_repr}')\n", " if len(args_src) > 1 and b_repr != args_src[1]: lines.append(f' where {args_src[1]} = {b_repr}')\n", " assert cmp(a, b), \"\\n\".join(lines)" ] }, { "cell_type": "markdown", "id": "b583f813", "metadata": {}, "source": [ "`expect` is a basic primitive for creating other assertion helpers. It takes two arguments and a callable and checks whether calling the callable with the two arguments yields `True`. If it doesn't, it prints a friendly error message." ] }, { "cell_type": "code", "execution_count": null, "id": "19d62642", "metadata": {}, "outputs": [], "source": [ "with raises() as e: expect(1, 2, operator.eq)\n", "assert e.type_ == AssertionError\n", "assert e.value.args[0] == '1 not eq 2'" ] }, { "cell_type": "markdown", "id": "1ea3c94e", "metadata": {}, "source": [ "If the `repr` of either argument is too long when being shown in the output, it will be automatically truncated via `reprlib.repr`." ] }, { "cell_type": "code", "execution_count": null, "id": "dec5f3d2", "metadata": {}, "outputs": [], "source": [ "with raises() as e: expect('a' * 1000, 'b' * 1000, operator.eq)\n", "assert e.value.args[0] == \"\"\"'a' * 1000 not eq 'b' * 1000\n", " where 'a' * 1000 = 'aaaaaaaaaaaa...aaaaaaaaaaaaa'\n", " where 'b' * 1000 = 'bbbbbbbbbbbb...bbbbbbbbbbbbb'\"\"\"" ] }, { "cell_type": "markdown", "id": "b7724e85", "metadata": {}, "source": [ "If we want to see everything, we can turn the truncation off:" ] }, { "cell_type": "code", "execution_count": null, "id": "2e03d976", "metadata": {}, "outputs": [], "source": [ "with raises() as e: expect('a' * 1000, 'b' * 1000, operator.eq, truncate=False)\n", "assert e.value.args[0] == f\"\"\"'a' * 1000 not eq 'b' * 1000\n", " where 'a' * 1000 = '{'a' * 1000}'\n", " where 'b' * 1000 = '{'b' * 1000}'\"\"\"" ] }, { "cell_type": "markdown", "id": "ef59b47e", "metadata": {}, "source": [ "The operator in the error message can be customized with `negstr`:" ] }, { "cell_type": "code", "execution_count": null, "id": "b9eedc92", "metadata": {}, "outputs": [], "source": [ "with raises() as e: expect(1, 2, operator.eq, negstr='!=')\n", "assert e.value.args[0] == '1 != 2'" ] }, { "cell_type": "markdown", "id": "a2df82d4", "metadata": {}, "source": [ "Furthermore, if you pass in expressions rather than constants, you'll see a print out of what the expressions were:" ] }, { "cell_type": "code", "execution_count": null, "id": "84055a16", "metadata": {}, "outputs": [], "source": [ "with raises() as e: expect(1+1, 2*10, operator.eq, negstr='!=')\n", "assert e.value.args[0] == '1 + 1 != 2 * 10\\n where 1 + 1 = 2\\n where 2 * 10 = 20'" ] }, { "cell_type": "markdown", "id": "91ea0818", "metadata": {}, "source": [ "If you end up creating a test helper with `expect`, you'll want to use `frames_up=2` to get the correct caller frame now, so `expect` grabs the right function invocation source code." ] }, { "cell_type": "code", "execution_count": null, "id": "ec18eb15", "metadata": {}, "outputs": [], "source": [ "def f(a,b,f=1):\n", " expect(a,b,cmp=operator.eq,frames_up=f)" ] }, { "cell_type": "markdown", "id": "8819d27d", "metadata": {}, "source": [ "If we don't change `frames_up` (f) to 2, we'll get an error message for the call stack _inside f_ (because we're the caller of `expect`)." ] }, { "cell_type": "code", "execution_count": null, "id": "5f8837b1", "metadata": {}, "outputs": [], "source": [ "with raises() as e: f(1, 2)\n", "assert e.value.args[0] == 'a not eq b\\n where a = 1\\n where b = 2'" ] }, { "cell_type": "markdown", "id": "af756a6c", "metadata": {}, "source": [ "Instead, we want to use `frames_up=2` to tell `expect` to look at the source code expressions for the *caller of f*." ] }, { "cell_type": "code", "execution_count": null, "id": "7b4bd85a", "metadata": {}, "outputs": [], "source": [ "with raises() as e: f(1, 2, f=2)\n", "assert e.value.args[0] == '1 not eq 2'" ] }, { "cell_type": "code", "execution_count": null, "id": "d1514687", "metadata": {}, "outputs": [], "source": [ "#| export\n", "def expect_fail(a, b, cmp:Callable, exc:type[Exception]=Exception, contains:str|None=None):\n", " \"Expect that cmp(a, b) raises `exc` and optionally that `exc` also contains `contains`.\"\n", " with raises(exc, contains): cmp(a, b)" ] }, { "cell_type": "markdown", "id": "3ae99417", "metadata": {}, "source": [ "`expect_fail` is another primitive that allows us to check whether some comparison should result in an exception being raised." ] }, { "cell_type": "code", "execution_count": null, "id": "69096bc9", "metadata": {}, "outputs": [], "source": [ "expect_fail(1, 0, operator.itruediv)" ] }, { "cell_type": "markdown", "id": "2d182509", "metadata": {}, "source": [ "By default, it will check that any `Exception` is raised. However, we can be more specific and also check that the exception message contains some string." ] }, { "cell_type": "code", "execution_count": null, "id": "823ada13", "metadata": {}, "outputs": [], "source": [ "expect_fail(1, 0, operator.itruediv, exc=ZeroDivisionError, contains='division by zero')" ] }, { "cell_type": "markdown", "id": "a0b25b81", "metadata": {}, "source": [ "If our expectation fails, `expect_fail` raises an `AssertionError`." ] }, { "cell_type": "code", "execution_count": null, "id": "0e6df664", "metadata": {}, "outputs": [], "source": [ "with raises(exc=AssertionError) as e: expect_fail(1, 1, operator.itruediv)\n", "assert e.value.args[0] == 'Did not raise'" ] }, { "cell_type": "markdown", "id": "4ca8f337", "metadata": {}, "source": [ "### Higher Level Assertions" ] }, { "cell_type": "code", "execution_count": null, "id": "2b503871-3f39-4013-a7ae-f5143af3138e", "metadata": {}, "outputs": [], "source": [ "#| export\n", "def equal(a, b):\n", " \"Assert that a == b.\"\n", " expect(a, b, operator.eq, negstr='!=', frames_up=2)" ] }, { "cell_type": "code", "execution_count": null, "id": "cc7872bb", "metadata": {}, "outputs": [], "source": [ "with raises() as e: equal(1, 2)\n", "assert e.value.args[0] == '1 != 2'" ] }, { "cell_type": "code", "execution_count": null, "id": "ec0a5998", "metadata": {}, "outputs": [], "source": [ "equal(1, 1)" ] }, { "cell_type": "code", "execution_count": null, "id": "9611b552", "metadata": {}, "outputs": [], "source": [ "#| export\n", "def nequal(a, b):\n", " \"Assert that a != b\"\n", " expect(a, b, operator.ne, negstr='==', frames_up=2)" ] }, { "cell_type": "code", "execution_count": null, "id": "4e8a42da", "metadata": {}, "outputs": [], "source": [ "with raises() as e: nequal(1, 1)\n", "assert e.value.args[0] == '1 == 1'" ] }, { "cell_type": "code", "execution_count": null, "id": "b26a3d35", "metadata": {}, "outputs": [], "source": [ "nequal(1, 2)" ] }, { "cell_type": "code", "execution_count": null, "id": "9523b71e", "metadata": {}, "outputs": [], "source": [ "#| export\n", "def is_true(a):\n", " \"Assert that a is truthy.\"\n", " expect(bool(a), True, operator.eq, negstr='is not truthy', frames_up=2)" ] }, { "cell_type": "code", "execution_count": null, "id": "505710d7", "metadata": {}, "outputs": [], "source": [ "is_true(True)\n", "is_true(\"abc\")\n", "is_true(123)\n", "is_true(['a'])" ] }, { "cell_type": "code", "execution_count": null, "id": "183b172b", "metadata": {}, "outputs": [], "source": [ "with raises(): is_true(False)\n", "with raises(): is_true(\"\")\n", "with raises(): is_true([])" ] }, { "cell_type": "code", "execution_count": null, "id": "f76c0add", "metadata": {}, "outputs": [], "source": [ "#| export\n", "def is_false(a):\n", " \"Assert that a is falsy.\"\n", " expect(bool(a), False, operator.eq, negstr='is not falsy', frames_up=2)" ] }, { "cell_type": "code", "execution_count": null, "id": "cc6907f0", "metadata": {}, "outputs": [], "source": [ "is_false(False)\n", "is_false(\"\")\n", "is_false([])" ] }, { "cell_type": "code", "execution_count": null, "id": "6c583e54", "metadata": {}, "outputs": [], "source": [ "with raises(): is_false(True)\n", "with raises(): is_false(\"abc\")\n", "with raises(): is_false(123)\n", "with raises(): is_false(['a'])" ] }, { "cell_type": "markdown", "id": "33be6990", "metadata": {}, "source": [ "## Environment" ] }, { "cell_type": "markdown", "id": "07e106e0", "metadata": {}, "source": [ "`env` allows us to temporarily set environment variables with a context manager. Therefore, if one of our test cases needs a few environment variables set differently, we can easily do that without affecting our broader state." ] }, { "cell_type": "code", "execution_count": null, "id": "664f33bf", "metadata": {}, "outputs": [], "source": [ "#| export\n", "@contextlib.contextmanager\n", "def env(**kwargs) -> Generator[None, None, None]:\n", " \"Temporarily set environment variables.\"\n", " old = {k: os.environ.get(k) for k in kwargs}\n", " os.environ.update(kwargs)\n", " try: yield\n", " finally:\n", " for k, v in old.items():\n", " if v is None: os.environ.pop(k, None)\n", " else: os.environ[k] = v" ] }, { "cell_type": "markdown", "id": "62d5fa07", "metadata": {}, "source": [ "When you use `env`, you can pass in an arbitrary number of keyword arguments to set new or override existing environment variables. If the environment variable was pre-existing, it will be reset to its previous value outside of the context manager. If it didn't exist previously, it'll be popped out of `os.environ`." ] }, { "cell_type": "code", "execution_count": null, "id": "47785cc3", "metadata": {}, "outputs": [], "source": [ "os.environ['CBA'] = 'SOMEVAL'\n", "equal(os.environ.get('ABC'), None)\n", "with env(ABC='123', CBA='321'):\n", " equal(os.environ.get('ABC'), '123')\n", " equal(os.environ.get('CBA'), '321')\n", "equal(os.environ.get('ABC'), None)\n", "equal(os.environ.get('CBA'), 'SOMEVAL')\n", "del os.environ['CBA']" ] }, { "cell_type": "code", "execution_count": null, "id": "078e15c8", "metadata": {}, "outputs": [], "source": [ "import nb; nb.export_nb('test.ipynb', src_dir='../nb/')" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }