Automated testing of a small script

I’ve written a little script to work out how much tax I need to deduce from my expense receipts. I’ve tested the calculation, rounding and error handling manually and its seems ok. As I’m planning to create a few little scripts like this, I’d like to ensure I have automated tests to run against them.

As I don’t have a module or function that I can import into a test framework (such as my preferred Pytest) I’m not sure how I can achieve this? I have read about ‘pytest-console-scripts’ but got a bit lost, particularly as my script captures user input.

Script for reference:

# Calculator script for deducting UK 
# Value Added Tax (VAT) @ 20%
# v.0.0.1

vat_rate = 1.20

run_again = True
while run_again:

    try:
        receipt_value = input("Receipt value: ")
        net_value = float(receipt_value) / vat_rate
        refund_vat = round(float(receipt_value) - net_value, 2)
        print(f"VAT: {refund_vat}")

        if input("Run again? ") != "y":
            run_again = False
    except:
        print("Invalid input. Try again...")
else:
    exit()

So you kind of answered your own question: If you want to test it, turn it into a module and functions. Then you can write a test against the functions and simply call them in a thin veneer script. This is a common progression. First you do a dirty hack, then you formalize the dirty hack into a module with some tests, then turn that into a full project that people can pip install.

Also, when you do code it’s [code]...[/code]. I fixed it for ya.

1 Like

Thanks for the fix. I was wondering why it didn’t format correctly!

I’ll see if I can evolve this into module/function.