{ "cells": [ { "cell_type": "markdown", "source": [ "# Testing how you test (with thebe)\n", "\n", "How would you check that a function like `fib` does what you expect it to? Modify the code below to test what happens when `fib` is run with different arguments. Does it give you what you expect?" ], "metadata": {} }, { "cell_type": "code", "execution_count": null, "source": [ "cache = {}\n", "def fib(n):\n", " \"\"\"\n", " Calculates the n'th Fibonacci number.\n", " \"\"\"\n", " global cache\n", " if n in cache:\n", " return cache[n]\n", "\n", " if n >= 2:\n", " return fib(n-1) + fib(n-2)\n", " else:\n", " return 1\n", "print(fib(1))" ], "outputs": [], "metadata": {} }, { "cell_type": "markdown", "source": [ "```{hint}\n", "Try running `fib(0)`, `fib(1)`, `fib(10)`. Check against the [encyclopedia of integer sequences](https://oeis.org/search?q=fibonacci&language=english&go=Search). Do the results agree? What about `fib(-1)`? How would you treat unusual cases like this?\n", "```\n", "\n", "Through our detective work, we notice that we have an off-by-one error! Indeed, the true sequence goes:\n", "\n", "$F(x) = {0, 1, 1, 2, \\ldots}$\n", "\n", "While we programmed:\n", "\n", "$F'(x) = {1, 1, 2, 3 \\ldots}$\n", "\n", "These kinds of subtle mistakes happen all the time when we write scientific code. That's why:\n", "\n", "> Most scientists who write software constantly test their code. That is, if you are a scientist writing software, I am sure that you have tried to see how well your code works by running every new function you write, examining the inputs and the outputs of the function, to see if the code runs properly (without error), and to see whether the results make sense. Automated code testing takes this informal practice, makes it formal, and automates it, so that you can make sure that your code does what it is supposed to do, even as you go about making changes around it. --Ariel Rokem, Shablona README\n", "\n", "So let's fix our code, and create tests to check that our code works as expected. That way, if we make another mistake in our code, the tests will catch it!" ], "metadata": {} } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.3" }, "orig_nbformat": 4, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 2 }