Gergan Zhekov
Gergan Zhekov

Reputation: 1064

Can I emulate input for my function inside the Test Case?

I am currently trying to make a Test Case for my program, but I am facing a difficulty. The way, I structured my code there is a function that takes the input, and according to that input it builds up a graph, and then there is a function that calculates something about the graph. I am also required to have this type of input for the job I am applying to. ( I can't do a simple unit test with a graph as an input).

The test file so far looks like this:

import unittest
from main_file import calculate, create_grid

class TestCase1(unittest.TestCase):

        def test1(self):

            data = create_grid()
            self.assertEqual(2, calculate(data))

The way it works right now, I input the needed data by myself with create_grid(). Is there a way I can emulate the computer/program to do it by itself (with specific values, as this is what I want). Thank you very much!

EDIT1:

This is the function code

def create_grid():
    rows, cols = [int(x) for x in input("Enter two numbers here: " + "\n").split()]

    for _ in range(rows):
        row = list(map(str, input().split()))
        grid.append(row)
    return grid

Upvotes: 0

Views: 27

Answers (1)

martbln
martbln

Reputation: 314

from unittest.mock import patch
from main_file import calculate, create_grid

class TestCase1(unittest.TestCase):

    def test1(self):
        with patch('builtins.input', side_effect=[1,2,3]):
            data = create_grid()
            self.assertEqual(2, calculate(data))

Upvotes: 1

Related Questions