Nepo Znat
Nepo Znat

Reputation: 3300

How should I test functions that call other functions?

def task_completed(task: Task) -> None:
  _update_status(task, TaskStatus.COMPLETED)
  _process_task(task)


def task_canceled(task: Task) -> None:
  _update_status(task, TaskStatus.CANCELED)
  _process_task(task)

# ...

def _process_task(task: Task) -> None:
  send_notification(task)  # already tested
  cleanup(task)  # already tested

I have written tests for the "public" functions send_notification and cleanup. Since I defined _process_task as a "private" function I don't write a test for this one.

How should I write tests for the functions: task_completed and task_canceled

Both functions are calling the _process_task function which calls the functions send_notification and cleanup which I've already tested.

Should I just test if these two "public" functions are called or should I test everything again what theses two functions are actually doing?

Upvotes: 0

Views: 340

Answers (2)

Dirk Herrmann
Dirk Herrmann

Reputation: 5949

Your functions task_completed, task_canceled and also _process_task do not contain computations, only interactions. Therefore, if any bugs are present in these functions it will be interaction bugs: Are you calling the right functions from the right component in the right order, with the right parameter values in the right order, and are the results provided as you expect them (return values / exceptions)?

Therefore, for the test of these functions, unit-testing does not have much value: Unit-testing is about finding the bugs that can be found in the isolated component. Consequently, your functions should be tested in integration testing: This is where the abovementioned bugs can actually be found. Thus, you should not duplicate testing what send_notification and cleanup are doing, but rather that they are called (in the right way).

An interesting aspect is about how to handle _process_task during these integration tests: If you take a black-box perspective during these tests, you would have to test twice that send_notification and cleanup are called correctly (from task_completed and from task_canceled). If you take a glass-box perspective, you would only have to test that once. Whether this makes sense depends on many aspects, and thus I would not discuss it here.

Upvotes: 1

Arnaud Claudel
Arnaud Claudel

Reputation: 3138

I would write a "black box" test and simply test the behaviour of task_canceled and task_completed, without worrying of the internal behaviour.

Upvotes: 0

Related Questions