{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#default_exp test" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#export\n", "from local.core.imports import *" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from local.notebook.showdoc import *\n", "from PIL import Image" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Test\n", "\n", "> Helper functions to quickly write tests in notebooks" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Simple test functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can check that code raises an exception when that's expected (`test_fail`). To test for equality or inequality (with different types of things) we define a simple funciton `test` that compares two object with a given `cmp` operator." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#export\n", "def test_fail(f, msg='', contains=''):\n", " \"Fails with `msg` unless `f()` raises an exception and (optionally) has `contains` in `e.args`\"\n", " try: f()\n", " except Exception as e:\n", " assert not contains or contains in str(e)\n", " return\n", " assert False,f\"Expected exception but none raised. {msg}\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def _fail(): raise Exception(\"foobar\")\n", "test_fail(_fail, contains=\"foo\")\n", "\n", "def _fail(): raise Exception()\n", "test_fail(_fail)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#export\n", "def test(a, b, cmp,cname=None):\n", " \"`assert` that `cmp(a,b)`; display inputs and `cname or cmp.__name__` if it fails\"\n", " if cname is None: cname=cmp.__name__\n", " assert cmp(a,b),f\"{cname}:\\n{a}\\n{b}\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "test([1,2],[1,2], operator.eq)\n", "test_fail(lambda: test([1,2],[1], operator.eq))\n", "test([1,2],[1], operator.ne)\n", "test_fail(lambda: test([1,2],[1,2], operator.ne))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "data": { "text/markdown": [ "
all_equal
[source]all_equal
(**`a`**, **`b`**)\n",
"\n",
"Compares whether `a` and `b` are the same length and have the same contents"
],
"text/plain": [
"equals
[source]equals
(**`a`**, **`b`**)\n",
"\n",
"Compares `a` and `b` for equality; supports sublists, tensors and arrays too"
],
"text/plain": [
"