mardi 28 mai 2019

Testing User Input - Python

I am having troubles with testing my input for my code in Python. I tried a couple of solutions, but there is something that I am missing, so I would appreciate it if you could give me some tips.

First here is a snippet from my main file of code that I want to test:

if __name__ == '__main__':

    n = int(input())
    m = int(input())

    grid = []

    for _ in range(n):
        grid.append(list(map(str, input().rstrip().split())))

    calculate(grid)

When I run my code, I input "n", then "m", then a grid is created according to the user input (each row on a new row..), and a function is executed that calculates something on the grid and the function returns the result. It all works great, but now I need to create a couple of test cases for it (that test different inputs against expected outputs).

First, I tried this: (on a separate .py file)

from unittest import mock
from unittest import TestCase
import main_file

class DictCreateTests(TestCase):
    @mock.patch('main_file.input', create=True)
    def testdictCreateSimple(self, mocked_input):
        mocked_input.side_effect = ['2', '2', 'R G B\nR G B'] #this is the input I need for my color grid
        self.assertEqual(calculate(grid), 2)

if __name__ == '__main__':
    unittest.main()

I then researched for some more options and I tried this option, which got me the closest:

import unittest
import os

class Test1(unittest.TestCase):

    def test_case1(self):
        input = "2\n2\nR G B\nR G B"
        expected_output = '2'
        with os.popen("echo " + input + "' | python main_file.py") as o:
            output = o.read()
        output = output.strip() # Remove leading spaces and LFs
        self.assertEqual(output, expected_output)

if __name__ == '__main__':
    unittest.main()

Unfortunately, even though it passed the test, I discovered that it always accepts the first letter/number of input as a result, when it compares it out to the expected output. So, I am thinking it has something to do with the multiple values I need to input. I tried separating them on different inputs (input1 + input2+ input3), but it still didn't work.

I would very much appreciate it if anyone could give me some tips on how to do it! Thank you in advance!

Aucun commentaire:

Enregistrer un commentaire