[Tutor] Testing functions

Mats Wichmann mats at wichmann.us
Mon Jun 26 16:17:32 EDT 2023


On 6/26/23 04:16, Jack Simpson wrote:
> Hi.
> I have just been playing around with functions and wanted to know where
> should i be in putting variables to test out a function block i have
> written?
> 
> This one is just an example for demonstration but where should I be
> defining the value of username here to test the function?
> 
>>>> def hint_username(username):
> ...         if len(username) < 3:
> ...              print("Invalid username, must be at least 3 characters long")
> ...         else:
> ..   .           print("Valid username")

Here's one possibility:

You can write test functions that hold the various combinations you want 
to try.  If you use an existing test framework this is pretty simple. 
You can prepare a test function that has the same name but a "test_" 
prefix, and write the tests to validate your usage there. The great 
thing about writing tests this way - "together with your code" - is you 
often think of cases that you didn't think of originally when writing 
your function - there's even a line of thinking that you should write 
your tests first, then write the code so the tests pass. Anyway - what 
if someone misunderstands and passes an integer to your function. What 
should it do?

  So here's a really trivial example using a variant of your code 
(notice the "print" calls have been replaced with a return - it's more 
common to have a function "do something" rather than print stuff - the 
latter is kind of typical when you're just starting out but becomes less 
prominent later).  The test framework handles running the tests for you.

def hint_username(username):
       if len(username) < 3:
            return "Invalid username, must be at least 3 characters long"
       else:
            return "Valid username"

def test_hint_username():
       # are short names detected?
       assert hint_username("gb") == "Invalid username, must be at least 
3 characters long"
       # are long names accepted?
       assert hint_username("georgebrown") == "Valid username"
       # are bogus usernames rejected?
       # assert hint_username(123) == ?? what should function return here?


PyTest will perform "test discovery" - files whose names start with 
test_ if you give it no filenames to search, and locate what look like 
test functions in those, or if you give it filenames, it will look for 
test functions in those (starting wtih test_), and run them for you.
Like:

$ pytest username.py
============================= test session starts 
==============================
platform linux -- Python 3.11.3, pytest-7.3.2, pluggy-1.2.0
rootdir: /home/user/work
plugins: typeguard-4.0.0
collected 1 item

username.py . 
[100%]

============================== 1 passed in 0.00s 
===============================
$




More information about the Tutor mailing list