Need help testing this function using pytest . I try to test is but with every test it keeps altering my csv file . how can i bypass some variables?

43 views Asked by At

This is the function I'm trying to test:

def withdraw():
    while 1:
        try:
            wd = float(input("How much $ would you like to withdraw? :"))
            break
        except ValueError:
            print("You must enter Numbers")
    df1 = pd.read_csv("capital.csv")
    blnc =df1["Balance"]
    blnc2 = float(blnc.iloc[0])
    nblc = (blnc2) - (wd)
    npnl = {"Balance": [nblc]}
    df3 = pd.DataFrame(npnl)
    df3.to_csv("capital.csv", mode="w")
    return (nblc)

this is as far as i can get with the pytest code :

import pytest
from project import withdraw

def test_withdraw(monkeypatch):
    monkeypatch.setattr("builtins.input", lambda _: "1000")
    blnc2 = 2000

    assert withdraw() == 1000

after running this it gives me a fail and the assert withdraw() = the value on csv file - 1000 and saves it back to the csv. altering it every time i run the test .

I'm just trying to test this function , i cant find a way to bypass the csv files so the rest can be tested, i was going to change my code but there must be a way to bypass that Im just not that good yet. Been on it for days .

1

There are 1 answers

2
John Gordon On

It's generally best not to do automated testing on functions that accept user input.

Instead, handle the user input in its own separate function, and then pass the input amount directly to the business function:

amount = accept_user_input()
my_business_function(amount)

Then in your test, you can just call the business function with a predefined amount:

my_business_function(500)