Home > Net >  How to write automated tests for a function that uses another function as a source of data
How to write automated tests for a function that uses another function as a source of data

Time:12-01

I am working on a small client for custom TCP protocol called MTP - memes transfer protocol (but that's irrelevant)... the thing is I couldn't ever bring myself to writing tests, as it seemed boring and pointlessly time-consuming (in reality I know, that all this is just my laziness ofc). But now there is one function in my app, where I question its behavior, so I would like to test it.

The problem is I don't know how, because there is a line, at which the function receives data from another helper function, that just serves as a parser from socket communication (I'm using TCP with netstrings "encryption") string.

Can anyone give me advice/ideas on how to approach this kind of testing? It appears really perplexing to me and the potential solutions I could have thought seemed so much difficult, that they were simply not worth further thinking.

(I didn't attach my code as it is rather long, but I am more than willing to share it upon demand)

CodePudding user response:

So as mentioned in the comments, if you can refactor the code and build it with testing in mind your life will be much easier. If you cant refactor the code and need to test what you currently have then you can consider mocking/patching the call to the other function. As you didnt show your code below is an example. I have a file called StackOverflow.py with two functions, foo and baz. foo will make a call to baz, baz would normally ask for user input an convert it to an int. In the case of our test, we want to mock out the function baz and not wait for user input.

In your case you could consider this your tcp function and instead just mock it to return what ever data you want. In my case foo takes a number and adds it to what ever number baz returns. I am mocking baz to return a random number and checking that foo returns what i expect.

from random import randint


def foo(num: int):
    return baz()   num


def baz():
    return int(input("num: "))


def test_foo_baz_num_valid(mocker):
    rand_num = randint(1, 100)
    base_num = 10
    baz_mock = mocker.patch("StackOverflow.baz")
    baz_mock.return_value = rand_num
    assert foo(base_num) == base_num   rand_num

OUTPUT

Testing started at 21:57 ...
Launching pytest with arguments StackOverflow.py --no-header --no-summary -q in C:\Users\cdoyle5\PycharmProjects\stackoverflow

============================= test session starts =============================
collecting ... collected 1 item

StackOverflow.py::test_foo_baz_num_valid PASSED                          [100%]

============================== 1 passed in 0.40s ==============================

  • Related